body:
The following code comes from [AtTiny serial library][1] that I want to use:

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <util/delay.h>

    // change these to use another pin
    #define TX_PORT PORTB
    #define TX_PIN  PB0
    #define TX_DDR  DDRB
    #define TX_DDR_PIN DDB0

I have no idea which pins to connect. What do these constants mean and where are they documented?

  [1]: https://github.com/MarcelMG/AVR8_BitBang_UART_TX

title: Which pins are represented by these constants from ABR library?

Answers: 1

body:
The mapping can be found in the io.h file but also in Arduino core files.

Below is the pin mapping:

                            ATtinyX4
                          +----U----+
      (VCC)-------------1-|VCC   GND|-14------------(GND)
      (D10)-------------2-|PB0   PA0|-13----------(D0/A0)
      (D9)--------------3-|PB1   PA1|-12----------(D1/A1)
      (/RESET)----------4-|PB3   PA2|-11----------(D2/A2)
      (D8)--------------5-|PB2   PA3|-10-------(D3/A3/SS)
      (D7/A7)-----------6-|PA7   PA4|-9---(D4/A4/SCL/SCK)
      (MISO/SDA/D6/A6)--7-|PA6   PA5|-8------(D5/A5/MOSI)
                          +---------+

The serial library uses:

    #define TX_PIN  PB0

Which is `ATtinyX4 Pin #2`, or Arduino attiny core digital pin `D10` https://github.com/damellis/attiny/blob/master/variants/tiny14/pins_arduino.h.

Cheers


body:
I know that for the Arduino (and C in general) that for comparison sake, "false" is 0, while any non-zero integer is "true". The question that I have is does the bool data type "return" a concrete integer for "true" or "false"?

When I tried `Serial.print(true == 1)`, it printed `1` (which I assumed to be "true"), but when I tried `Serial.print(true == 2)`, it printed `0` (which I assumed to be "false"). When I tried `Serial.print(false == 1)`, it printed `0` and `Serial.print(false == 0)` printed a `1`.

I didn't know if "true" always evaluated to 1 and "false" always evaluated to 0, or if this is not supposed to happen.

title: Does bool return an int?

Answers: 3

body:
true is indeed 1, and false is 0.

This follows your tests:

    (true == 1) -> prints 1, because 1 == 1
    (true == 2) -> prints 0, because 1 != 2
    (false == 1) -> prints 0, because 0 != 1

In C true and false are defines and a bool/boolean is a typedef (mostly to an int, unsigned int or unsigned char), where normally false is defined to 0 and true to 1 OR 255. So you cannot rely on a specific value.

In C++ the values of true and false are resp. 1 and 0, when casted to an int.

body:
If you look at `Arduino.h`, you'll see `true`, `false` and `bool` defined as:

    #define true 0x1
    #define false 0x0
    typedef uint8_t boolean;

Using a simple test sketch, it appears that comparing `true` or `false` to anything besides a 1 or 0 does not "work".

    void setup(){

      Serial.begin(9600);

      if(false == 0){Serial.println("false=0");}
      if(false == 1){Serial.println("false=1");}
      if(false == 2){Serial.println("false=2");}
      if(false == -1){Serial.println("false=-1");}
      if(true == 0){Serial.println("true=0");}
      if(true == 1){Serial.println("true=1");}
      if(true == 2){Serial.println("true=2");}
      if(true == -1){Serial.println("true=-1");}

    }

    void loop(){}

body:
A 'bool' is defined data type based on (and identical to) an int. It's reason for existence is documentary: it's name describes how you intend to use it. There is no other difference.

'true' and 'false' are the constants 1 and 0, respectively. If you assign 'true' to a bool or any other integer type, it will get the value '1'. If you make a comparison or any other logical test (one that evaluates to true or false), that test results in a numerical value, either 1 or 0.

However you *can* evaluate (i.e. test) any integral value logically (true or false): if it is equal to zero the result will be false (0); otherwise the result will be true (1) - no matter what non-zero value the expression itself has. That is because the logical operators, '==', '!=', '>', etc., are (similar to) functions which can only return one of two values 'true' and 'false', regardless of the values of their inputs. That is another meaning of the bool datatype: when it is applied to a function, it implies to the compiler and to the reader that this function returns either true or false.


body:
I am having a very strange issue with the realtime clock in Arduino that I cannot seem to solve.  Basically, I have a program that logs data from a terrarium kit and saves each session to an SD card as a file named after the time the program started.  0

The problem with the program is that the code hangs on the statement before the setup section: “DateTime now = RTC.now().”  The realtime clock appears to be functioning correctly with the example program which makes this issue even more strange.  I am unsure if this is purely a software or hardware issue.  From scouring the internet, I have found people with a similar problem to mine where the RTC will freeze up the i2c bus on the Arduino.  However, I am unsure whether this is the issue plaguing me.  If this is indeed the issue plaguing my program, unsure of how to work around it.  I found an online solution here, however my program freezes upon launch so this would not work for me.

So far, I have tried:
-Replacing the coin-cell battery in the realtime clock (I am using 3 volt batteries)
-Replacing the datalogger shield with a new one
-Replacing the Arduino with a new one
-Checking to make sure that the jumpers were correctly soldered to the datalogger shield (Adafruit support checked mine through images and said they looked good)

I am running this program on IDE Version 1.6.9 with a program with the newer Adafruit datalogger shield on the Arduino Mega.

Any help would be greatly appreciated

    //The libraries we need for our terrarium kit
    //Download and install them all at this link:  https://drive.google.com/drive/folders/10XAFdYmnyz0dg9I6YYj80vJlHebFIZhN
    #include <OneWire.h> //Import OneWire library
    #include <DallasTemperature.h> //Import DallasTemperature library
    #include <Adafruit_Sensor.h> //Import Adafruit Sensor library
    #include <DHT.h> //Import first part of the DHT library
    #include <TimerOne.h> //Import TimerOne library
    #include <SPI.h>
    #include <SD.h>  //this refers to an old SD library needed specifically for
    #include "RTClib.h"  //this is from the rtc example folder code

    //SD Card & Realtime Clock: Initialization
    File logfile;
    RTC_DS1307 RTC;

    //Humidity Sensor: Constants
    //This #define defines the pin that the DHT is plugged into
    #define DHT_PIN 2
    //This #define defines the type of the DHT
    #define DHT_TYPE DHT22
    //This tells the code that a DHT is plugged into port DHT_PIN and the DHT is of type DHT_TYPE
    DHT dht(DHT_PIN, DHT_TYPE);

    //Moisture Sensor: Variables
    int MS_sigPin = A5; //Set the signal pin as analog pin 5
    int MS_digPin = 7; //Set the digital pin as 2
    float MS_upper = 0; //Declare highest value variable

    //Other variables
    int measurementNumber = 1; //Number of measurements taken

    //Filename:
      DateTime now = RTC.now(); //Initialize the RTC
    //  String seconds = (String)(now.second());  //Stores the seconds from the RTC upon setup as a string
     const String minutes = (String)(now.minute()); //Stores the seconds from the RTC upon setup as a string
     const String hours = (String)(now.hour());  //Stores the seconds from the RTC upon setup as a string
     const String days = (String)(now.day());  //Stores the seconds from the RTC upon setup as a string
     const String months = (String)(now.month());  //Stores the seconds from the RTC upon setup as a string
     const String years = (String)(now.year());  //Stores the seconds from the RTC upon setup as a string
     const String filename = "D_" + minutes + hours + days + months + years; //Create the file name as a timestamp

    void setup() {

      int chipSelect = 10; //chipSelect pin for the SD card

      // put your setup code here, to run once:
      Serial.begin(115200); //Set the baud rate at 56700
    //If RTC is already updated, the below is commented out
      RTC.begin();
      RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));//this is to force rtc update
    //  if (!RTC.isrunning()) {
    //
    //    Serial.println("RTC is NOT running! Starting it now.");
    //    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
    //
    //  }// end rtc if

    //{
    //The below is copied from wired, contains a second try, hoping for sd success herein.
     pinMode(chipSelect, OUTPUT);
     digitalWrite(chipSelect, HIGH);
     SD.begin(chipSelect);
    //  if (!SD.begin(10, 11, 12, 13)) {
    //    Serial.println("Card failed, or not present");
    //    delay(50);
    //    Serial.println("Trying again...");
    //    if (!SD.begin(50, 51, 52, 53)) {
    //      Serial.println("Card failed, or not present");
    //    }
    //  }

     /******************************** CSV FORMAT ******************************/

    //  Serial.print("Current Position: ");
    //  Serial.println(logfile.position());
      if(logfile.position() == 0)//Below print header line for datafile
      logfile.println("Unix Time, Date, Time, Light, Humidity, Temperature");
      //logfile.println("uni,date,time,Temperature");

      /**************************************************************************/

    //  sensors.begin();
    //  sensors.setResolution(12);

      //Humidity Sensor:
       dht.begin();

      //Moisture Sensor:
      pinMode(MS_sigPin, OUTPUT); //Set the signal pin as an output
      pinMode(MS_digPin, OUTPUT); //Set the digital pin as an output
      digitalWrite(MS_digPin, HIGH); //Turn the digital pin on

      Serial.println("DIP THE MOISTURE SENSOR IN A CUP OF WATER MAKING SURE NOT TO SUBMERGE THE TOP OF IT INTO THE WATER, ENTER IN ANY KEY WHEN YOU ARE READY TO CALIBRATE"); //Print out useful information
      while (Serial.available() == 0) //Hang the program until the user inputs a key to continue
      {

      }
      Serial.println("Starting Calibration"); //Print out useful information
      Timer1.initialize(1000000); //Initialize an interrupt every 1 second
      Timer1.attachInterrupt(Calibrate); //When the interrupt is called run the “Calibrate” function

    }
    //Calibrate the moisture sensor
    void Calibrate() //Function to calibrate the sensor
    {
    if (analogRead(MS_sigPin) > MS_upper) //If the value read by the sensor is higher than the past highest value
    {
     MS_upper = analogRead(MS_sigPin); //Set the current value as the new highest value
      }
    }

    void loop() {

    //Photocell: Variables
    int photocellPin = A0; // the cell and 10K pulldown are connected to a0

      char fileCharStorage[(filename.length()+5)]; //+4 Characters to include ".csv"
      filename.toCharArray(fileCharStorage, filename.length()+5);
      fileCharStorage[filename.length()] = 'V'; //Set the file name
      fileCharStorage[filename.length()-1] = 'S'; //Set the file name
      fileCharStorage[filename.length()-2] = 'C'; //Set the file name
      fileCharStorage[filename.length()-3] = '.'; //Set the file name
      Serial.println(filename); //Print out the filename
      Serial.println(sizeof(fileCharStorage)); //Print the length of the array storing the file name
      logfile = SD.open(fileCharStorage, FILE_WRITE);  //Creates (or opens) a file names "MMHHDDMMYYYY.CSV"

      if (logfile)
      {
        Serial.println("The SD Card is functioning properly");
      }
      else
      {
        Serial.println("A Critical Error occured while trying to initialize the SD Card!");
      }
      //Realtime Clock
      DateTime now = RTC.now();

     //Photocell:
     int photocellReading = analogRead(photocellPin); //Variable that stores the amount of light detected by the photocell as an integer

      // This code gets the humidity from the DHT
      float dhtHumidity = dht.readHumidity();
      /*
      This code gets the temperature from the DHT
      */
      float dhtTemperature = dht.readTemperature();

      Serial.println(""); //Text Formatting
      Serial.println("Starting New Measurement (" + (String)measurementNumber + ")");
      Serial.println(""); //Text Formatting
      delay(1000);

      //Print out data from the number of measurements taken
      Serial.println("The Arduino has been active for " + (String)((measurementNumber*10)-10) + " seconds");
      measurementNumber++;

      //Print out data from the RTC
        Serial.print("Unix Time (Seconds since 1/1/1970): ");
        Serial.print(now.unixtime()); // seconds since 1/1/1970
        Serial.println(", ");
        Serial.print("RTC time: ");
        Serial.print(now.month(), DEC);
        Serial.print("/");
        Serial.print(now.day(), DEC);
        Serial.print("/");
        Serial.print(now.year(), DEC);
        Serial.print(",");
        Serial.print(now.hour(), DEC);
        Serial.print(":");
        Serial.print(now.minute(), DEC);
        Serial.print(":");
        Serial.print(now.second(), DEC);
        Serial.println("");
        Serial.println("");

      //Photocell:
      Serial.println("Data from the photocell:");
      Serial.print("Analog reading = ");
      Serial.print(photocellReading); // the raw analog reading

      if (photocellReading < 10) {
      Serial.println(" - Dark"); //says that if any number is lower than 10 then it prints out dark.
      } else if (photocellReading < 200) {
      Serial.println(" - Dim"); //says that if any number is lower than 200 then it prints out dim.
      } else if (photocellReading < 500) {
      Serial.println(" - Light"); //says that if any number is lower than 500 then it prints out light.
      } else if (photocellReading < 800) {
      Serial.println(" - Bright"); //says that if any number is lower than 800 then it prints out bright
      } else {
      Serial.println(" - Very bright"); //says that if any number higher than 800 then it prints out very bright
    }
      Serial.println("");

    // Humidity Sensor:
      Serial.println("Data from the humidity sensor:");
      Serial.print("Humidity: ");
      Serial.print(dhtHumidity);
      Serial.print(" %, Temp: ");
      Serial.print(dhtTemperature);
      Serial.println(" Celsius");
      Serial.println("");

      //Moisture Sensor:
      Serial.println("Data from the moisture sensor:");
      float percent = (analogRead(MS_sigPin)/MS_upper)*100; //Calculate moisture percentage
      Serial.println("Moisture = " + (String)percent + "%"); //Print out the moisture percentage

      Serial.println("");
      Serial.println("--------------------------------------------------");

        //Log everything onto the SD card
        logfile.print(now.unixtime()); // seconds since 1/1/1970
        logfile.print(", ");
        logfile.print(now.month(), DEC);
        logfile.print("/");
        logfile.print(now.day(), DEC);
        logfile.print("/");
        logfile.print(now.year(), DEC);
        logfile.print(",");
        logfile.print(now.hour(), DEC);
        logfile.print(":");
        logfile.print(now.minute(), DEC);
        logfile.print(":");
        logfile.print(now.second(), DEC);
        logfile.print(", ");
        logfile.print(photocellReading);
        logfile.print(", ");
        logfile.print(dhtHumidity);
        logfile.print(", ");
        logfile.print(dhtTemperature);
        logfile.println();
        logfile.close();
    //  Delay by 1+9 (10) seconds between measurements
      delay(9000);
    }

title: Is my Realtime Clock Locking Up My Arduino? If so, how would I solve it?

Answers: 1

body:
I'm guessing that you can't call `RTC.now()` before setup like that.

It would be helpful if you told us what RTC you were using, and provided a link to the library you were using for it.

At a guess, since I don't have that info, you should probably change the declaration like this:

      //Filename:
      DateTime now;

And then in your `setup()`:

    RTC.begin();

    if (!RTC.isrunning()) {
      Serial.println("RTC is NOT running! Starting it now.");
      RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
    } // end rtc if
    now = RTC.now(); //Initialize the RTC


body:
Why does the following code return this error?  How can I make this work?

> Error: exit status 1 invalid conversion from 'const char*' to 'char'
> [-fpermissive]

```
#include "FS.h"
#include "SD.h"
#include "SPI.h"

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

  if (!SD.begin(33)) {
    Serial.println("Card Mount Failed");
  } else {
    Serial.println("Card Mount Succeeded");
  }

  File offline = SD.open("/offlineLog.txt", FILE_READ);

  while (offline.available()) {
    String line = offline.readStringUntil("\n");
    Serial.println(line);
  }
}
```

The docs say that stream.readStringUntil returns a string...

title: Reading text line by line from SD

Answers: 1

body:
The error has nothing to do with what `readStringUntil` returns. It has to do with what parameters it accepts.

The function expects a *single character* to look for. Instead you are passing it a string (C string) containing one character.

In C you represent a string (`char *`) using `""`, and a single character (`char`) using `''`.

Since `readStringUntil` expects a `char`, not a `char *`, you need to use `''`:

    String line = offline.readStringUntil('\n');


body:
I want to read the data line from a device that normally interfaces with a controller. It has 3 pins, 3.3v power, gnd, and data. I don't need the power line since the Arduino will be USB powered and I obviously don't want to just connect it straight to ground. What would be the best way to handle this without introducing extra hardware components. Can I just connect the power to an input pin, and then I can use that to see if the device is on?

I'm using an Arduino Mega2560

title: How can I discard power from a device I want to read from?

Answers: 2

body:
You don't need to "discard" power. You just ignore it.

If you don't need a connection, then don't connect it.  The only important connection is the ground connection. Everything else can be used, or not used, at your discretion.

There's nothing "magical" about a power connection. It's just a voltage that comes from a source that happens to be able to provide more current.  If you want to use it to power something, you can. If you want to just sense what the voltage is, you can. If you want to ignore it, you can.

It's not like a mountain: just because it's there, it doesn't mean you *have* to climb it...

body:
I believe you want to check whether your device is on or not without drawing power from it. Something like the following circuit could be useful:

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

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

<!-- End schematic -->

R2 limits the current going into Arduino input pin. Resistor with value around 1K should be good given the voltages you mentioned. Arduino can read the input pin to see whether the device is on or off.

R1 pulls Arduino input pin to ground in when the device is off. This gives a "0" value at the input pin. R1 can be a high value ~10K. High value would limit current leakage to ground via R1.
Though this answer won't exactly satisfy your requirement of not using additional components.


body:
This following error message I am getting while compiling:

    Arduino: 1.6.8 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    In file included from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/opt.h:51:0,

                     from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/init.h:40,

                     from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/IPAddress.h:27,

                     from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:31,

                     from C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:20:

    C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:1301:2: error: #error TCP_MSS must be defined

     #error TCP_MSS must be defined

      ^

    C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:2381:2: error: #error LWIP_IPV6 must be defined

     #error LWIP_IPV6 must be defined

      ^

    C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:3534:2: error: #error LWIP_FEATURES must be defined

     #error LWIP_FEATURES must be defined

      ^

    In file included from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFiSTA.h:29:0,

                     from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:34,

                     from C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:20:

    C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/include/user_interface.h:34:2: error: #error LWIP_OPEN_SRC must be defined

     #error LWIP_OPEN_SRC must be defined

      ^

    C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory

     #include <FirebaseArduino.h>

                                 ^

    compilation terminated.

    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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

please help me out to solve this issue.

title: facing issue while compiling code

Answers: 0


body:
![my circuit](https://i.stack.imgur.com/nj2jy.jpg)
![what is supposed to be](https://i.stack.imgur.com/4jCxQ.jpg)

Can someone pls help me only the two buttons clossest to the big green wire work and i don^t know why i have already tried swapping buttons

EDIT 1:
my code
[![this is my code][1]][1]

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

and i know the first two are working because they generate a tone with the piezo
the third one does nothing and the last one only makes static noises

title: Problem with arduino starter kit project 7

Answers: 1

body:
<s>I see the problem. The connections to the first 2 buttons are correct. You're missing a yellow wire linking the output of the bottom 2 buttons to AO however, so the 3rd and 4th buttons are not connected to your A0 pin at all. Add a yellow wire between row 24 and row 20 on your breadboard.</s>

## EDIT: ##

I see now that there is a green wire connecting rows 24 and 20 together. However, that is the likely place where things go wrong. I would suggest taking a couple of jumpers and connecting them to a multimeter set to continuity mode. Put one in row 28, and then test continuity to row 24, row 20, and row 16.

One of your wires may not be seated into the breadboard properly, or you may even have a bad row on your breadboard. I've seen that before.

## EDIT #2: ##

A multimeter is your friend. If you don't have one, you should get one, and learn how to use it. It's invaluable for troubleshooting circuits. (Get one that has a continuity mode that beeps when it detects continuity, and that has auto-ranging voltage and resistance measurements.)


body:
I use `arduino_debug` to upload my sketch to an Arduino Mega 2560 and to an Arduino Due from my application (Windows).

I saw the following issue:

When JAVA is not installed or it was installed only after the Arduino SW installation, the command:

    arduino_debug --port COM6 --upload mysketch.ino

doesn't successfully to upload the sketch. My Arduino is connected to `COM6` (I verified it) and the sketch's path is correct.

I got the following output:

    Initializing packages...

    Preparing boards...

    Verifying...

    Sketch uses 6222 bytes (19%) of program storage space. Maximum is 32256 bytes.
    Global variables use 318 bytes (15%) of dynamic memory, leaving 1730 bytes for local variables. Maximum is 2048 bytes.

    Uploading...

    avrdude: stk500_recv(): programmer is not responding

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

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x87

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x87

    An error occurred while uploading the sketch

    avrdude: stk500_recv(): programmer is not responding

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

Has anyone seen this issue? Does anyone know why JAVA must be installed?

title: Arduino_Debug doesn't successfully upload sketch to Arduino if JAVA is not installed

Answers: 0


body:
(Before you down-vote this, note that it is a "ringer" to answer a FAQ, with a self-answer.)

This question comes up all the time. How do you combine 2 different sketches together? Say I have a sample sketch for a DTH temp/humidity sensor and another sketch for a LCD sensor. How do I combine them?

Answers: 1

body:
This question comes up all the time. I'll explain what you need to do in general terms. Try it, and if you have problems, post a question showing your 2 starting sketches, your attempt at combining them, and detailed info on what goes wrong.

There are 3 basic parts to the main.ino file of an Arduino sketch:

 1. The declarations:

 - `#includes`
 - `#defines`
 -  global variables

 2. The `setup()` function

 3.  The `loop()` function.

You need to merge those parts separately.

1. You should merge the subsections of the declarations together (Put all the `#includes` together, all the `#define`s together, and all the global variables together. Remove any duplicate `#include`s.

If there are any duplicate `#define`s or global variables, you need to figure out how to resolve that. If the symbol and the name are the same

2. The same applies to the two `setup()`-functions you want to merge. Also, duplicate parts usually need to be there only once (considering things like `Serial.begin(...)`).

3. Also the two `loop()`s are combined the same way, but if you make use of `delay()`s you must keep in mind that these will sum up in the final sketch, making it slower than the initial sketches were. It might also might (probably won't) work correctly. You will likely need to refactor your code to use millis() instead of `delay()`.

After combining two sketches this way your global variables will be shared. You'll need to resolve any naming conflicts, or rename global variables that are different in your source sketches but should be the same. You may also have shared resources like sensors and LCD displays.

(Note that if the 2 sketches use the same resource for different things it gets more complicated, e.g. using the same pin for different purposes, using the same timer in both sketches, or using the same interrupt. Those things will require analysis and case-by-case changes.)


body:
I want to use 2nd servo only when 1st is in up state by asking user whether he wants to fire or not.(code in bold is not working )

    #include <Servo.h>

        Servo myservo;
        Servo trigervo;
        int pos = 0;
        int u = 0, p = 0, t = 0;
        int incomingByte = 0; // for incoming serial data

        void setup() {
          Serial.begin(9600);
          myservo.attach(9);
          trigervo.attach(10);
          pinMode(13, OUTPUT);
          myservo.write(0);
        }

        void loop() {
          if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
            Serial.print("I received: ");
            if (incomingByte == 111 && u == 0) {
              for (pos = 0; pos <= 80; pos += 1) {
                myservo.write(pos);
                delay(5); //
                digitalWrite(13, HIGH);
              }
              u = 1;
              p = 0;
              Serial.println(incomingByte, DEC);
              Serial.print("Want to Shoot? \n");
              Serial.print("1\n");
              ***t = Serial.read(); // from here
              if (t == 107) {
                Serial.print("2\n");
                trigervo.write(60);
                trigervo.write(0);
              } // to here, it is not working***
            } else if (incomingByte == 102 && p == 0) {

              for (pos = 100; pos >= 0; pos -= 1) {
                myservo.write(pos);
                delay(7);
                digitalWrite(13, HIGH);
              }
              u = 0;
              p = 1;
              Serial.println(incomingByte, DEC);
            }
            Serial.println(incomingByte, DEC);

          }
        }

title: Wanted to control 2 servos with serial read

Answers: 1

body:
Without knowing, what exactly you want it to do (since you didn't tell us), I see 2 problems in your code:

1. The code around the line marked with "from here" will ask the user over Serial, if he wants to shoot, but directly after it, it will read a value, without waiting for the user to input something. `Serial.read()` will not wait for data to arrive, it will just return -1 if nothing is in the buffer. You have to check, if there is actually something in the buffer with `Serial.available()` and only proceed, if there is actually data to read.

2. In the following if-statement, you first write the value 60 to the servo and directly after it, without any delay, the value 0. The servo doesn't have enough time to get to 60 - or to even start to move - before you tell him to go to 0. The servo needs time for movements.

---

Apart from the specific problems with your code, I would use a finite state machine (FSM), to implement it, instead. You declare a global state variable, which represents the possible states, in which your machine can be. If I assume some type of gun/shooting device, these states could be `ASK_USER_TO_POSITION_GUN' and 'ASK_USER_TO_SHOOT'. In each state you check the Serial interface (first with `Serial.available()` then reading with `Serial.read()` if it returns something greater than 0) and based on that input you first take the appropriate action and then do the state transition, by changing the state variable.

As example of the general structure:

    int state = 0;

    void loop(){
        switch(state){
            case 0:
                if(Serial.available()>0){
                    int input = Serial.read();
                    //take appropriate action
                    state = 1; //do state transistion
                }
                break;
            case 1:
                if(Serial.available()>0){
                    int input = Serial.read();
                    //take appropriate action
                    state = 0; //do state transition
                }
                break;
        }
    }

Depending on the exact actions to do, you can also tune this, by reading Serial outside of the switch statement and in the case statement only check the input variable. In this case reset the input variable after every interaction.

EDIT: For giving a better explanation about finite state machines, I've drawn a graphical representation of the states. Mostly it is way easier to code, when you first have drawn such a graph to visualize the codes functionality. Note, that this is the logic from your code. You may want it to work another way, but this is beyond the scope and only for understanding. Also note the different numbers of the states than I used above, which I only change, because I needed more states.

See first this graph:

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

We begin in state 0, where we are waiting for user input through serial. If we go some input, we make a decision: If the value is 111, we will transition to the next state (state 1) to position the gun, else we will wait again for more input. In stage 1, we are positioning the gun and go directly to state 2. There we are again waiting for user input. If we received something, we will again make a decision: On the value 107 we will do the transition to state 3 to shoot, else we will go to state 0, to ask again for positioning, like we did before. In state 3 we are shooting and directly go to state 0 again. This is rather strict division into states.

Since in state 1 and 3 we are only doing a short action and then going directly to another state, we might cut those states away, implementing the corresponding code in the transition from state 0 to 2 and vice versa. This is the logic from my FSM code example above (action together with transition). The graph would look like this:

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

Which version you should implement depends on other factors. If you are OK with the action code to be blocking, you can implement version 2, since it has less states. If you want to write the action in a non-blocking style, you might find version 1 easier to implement.

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


body:
This code is used to toggle an arduino on and off , the problem is that i can't comprehend it at all. can someone explain to me how does it work ?

    New = digitalRead(button);
      if ( New!=old)
      {
        if ( New == HIGH ){
          if (LEDstatus == LOW)
        {  digitalWrite(LED,HIGH);
        LEDstatus = HIGH;
        }
        else
        {
          digitalWrite(LED,LOW);
          LEDstatus=LOW;
        }
        }
        old=New;
      }

title: Question about a code

Answers: 1

body:
First, fix the indentation:

 New = digitalRead(button);
 if ( New!=old) {                        // If the button state has changed
  if ( New == HIGH ) {                // If the button is now in the pressed state
   if (LEDstatus == LOW) {         // If the LED was off
    digitalWrite(LED,HIGH);     // Turn the LED on
    LEDstatus = HIGH;           // Remember the LED state for next time
   } else {                        // The LED was on, so turn it off
    digitalWrite(LED,LOW);
    LEDstatus=LOW;              // Remember the LED state for next time
   }
  }
  old=New;
 }

That makes the code a whole lot easier to understand.

It only does something when the button is pressed (switches to HIGH state). It doesn't do anything when you release the button.

Each button press changes the state of the LED.

if it was off, it turns it on. If it was on, it turns it off.


body:
I have a question with Serial Print. I want the Sensor reading values to fall under 3 columns, and each column should have the readings from the same sensor.

Raw Value |    Sensor 1 |   Sensor 2  |   Sensor 3

how can I modify this code do this?

Below I have posted my code and what I currently see using the Serial Monitor

        void loop(){

      RawValue0 = analogRead(analogIn0);
      Voltage0 = (RawValue0 / 1023.0) * 5000; // 5000 to get millivots.
      tempC0 = (Voltage0-500) * 0.1; // 500 is the offset
      tempF0 = (tempC0 * 1.8) + 32; // conver to F
      Serial.print("Raw Value = " );  // shows pre-scaled value
      Serial.print(RawValue0);
      Serial.print("\t milli volts = "); // shows the voltage measured
      Serial.print(Voltage0,0); //
      Serial.print("\t Sensor 1: Temperature in C = ");
      Serial.print(tempC0,1);
      Serial.print("\t Sensor 1: Temperature in F = ");
      Serial.println(tempF0,1);
      delay(500);

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

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

title: Issue with Indenting the Serial Print data in the Serial Monitor

Answers: 2

body:
Columns with lines?

The `sprintf` function can fill data with spaces to align them. However, the Arduino `sprintf` function does not support floating point variables. The `dtostrf` function has already a fixed output width by itself.
The sketch below is a combination of UTF-8 characters and the `dtostrf` and `sprintf` functions.

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

      Serial.println();
      Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
      Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
      Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
    }

    void loop() {
      int raw = random(0, 1024);
      float c = random(-1000, 1000) / 10.0;
      float f = random(-500, 1500) / 10.0;

      char buffer_c[20];
      char buffer_f[20];

      dtostrf(c, 6, 1, buffer_c);
      dtostrf(f, 6, 1, buffer_f);

      char buffer[80];
      sprintf(buffer, "┃ M ┃ %s ┃ %s ┃", raw, buffer_c, buffer_f);
      Serial.println(buffer);

      delay(500);
    }

----------

The strlen() function can not be used before printing a floating point number to the serial port, since its length is determined while printing characters to the serial port. The final number of bytes that is written is the return value.
There is a way to use that return value, by using a dummy write to a dummy serial port. After that the number of spaces to align the floating point number can be calculated.

That reduces the code size from 6160 to 4708 for an Arduino Uno.

    class DummyClass : public Stream
    {
      int available() {return 0;}
      int read() {return 0;}
      int peek() {return 0;}
      void flush() {return;}
      size_t write(uint8_t) {return 1;}
      using Print::write;
    };

    DummyClass Dummy;

    const int width_r = 4;
    const int width_c = 6;
    const int width_f = 6;

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

      Serial.println();
      Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
      Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
      Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
    }

    void loop() {
      int raw = random(0, 1024);
      float c = random(-1000, 1000) / 10.0;
      float f = random(-500, 1500) / 10.0;

      int i;
      Serial.print("┃ ");
      Spaces(width_r - Dummy.print(raw));
      Serial.print(raw);
      Serial.print(" ┃ ");
      Spaces(width_c - Dummy.print(c,1));
      Serial.print(c,1);
      Serial.print(" ┃ ");
      Spaces(width_f - Dummy.print(f,1));
      Serial.print(f,1);
      Serial.print(" ┃");
      Serial.println();

      delay(500);
    }

    void Spaces(int n)
    {
      for(int i=0; i<n; i++) {
        Serial.print(' ');
      }
    }

I advise not to use this "Dummy" trick. It is mere a coding exercise. I can not find a problem with this trick, but I'm not 100% sure that it is okay.

body:
Here is a sketch that uses a different approach than Jot uses in his answer. There is no question that Jot's answer is excellent and takes very few lines of code to accomplish.

I thought it would look nice if the Raw Value, an integer, was centered under the "Raw Value" column when it was at it's maximum value of 1023. A value of 1 would be right-ish justified, but still aligned with the center in mind.

The floating point numbers, which could be positive or negative, should be right justified I thought, so I wrote a second function to deal with those numbers.

    int RawValue0;
    float Voltage0, tempC0, tempF0;

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

      Serial.println();
      Serial.println("Raw Value | Sensor 1 | Sensor 2 | Sensor 3");
      Serial.println("------------------------------------------");

      RawValue0 = 1023; //analogRead(analogIn0);
      Voltage0 = 11.0; //(RawValue0 / 1023.0) * 5000; // 5000 to get millivots.
      tempC0 = -100.0; //(Voltage0-500) * 0.1; // 500 is the offset
      tempF0 = 1212.0; //(tempC0 * 1.8) + 32; // conver to F
    }

    void loop(){

      // Increment the variables to simulate test data.
      RawValue0 += 51;
      if(RawValue0 > 1023){RawValue0 = 0;}
      Voltage0 += 99.99;
      if(Voltage0 > 9999.99){Voltage0 = 0.0;}
      tempC0 -= 99.99;
      if(tempC0 < -9999.99){tempC0 = 0.0;}

      // Print out the data in columns.
      printNumber(RawValue0);
      Serial.print("   | ");
      printNumber(Voltage0);
      Serial.print(" | ");
      printNumber(tempC0);
      Serial.print(" | ");
      printNumber(tempF0);
      Serial.println();
      delay(250);
    }

    long printNumber(int number){
      Serial.print("   ");
      int spaces = 0;
      if(number < 1000){spaces = 1;}
      if(number < 100){spaces = 2;}
      if(number < 10){spaces = 3;}
      for(int i = 0; i < spaces; i++){
        Serial.print(" ");
      }
      Serial.print(number);
    }

    float printNumber(float number){
      int spaces = 0;
      if(number > -1000.00){Serial.print(" ");}
      if(number < 1000){spaces = 1;}
      if(number < 100){spaces = 2;}
      if(number < 10){spaces = 3;}
      if(number < 0){spaces = 0;}
      if(number == -99.99){spaces = 1;}
      for(int i = 0; i < spaces; i++){
        Serial.print(" ");
      }
      Serial.print(number);
    }

When I compile Jot's sketch, it's 6640 bytes. If you remove his "fancy" header, it drops to 6414 bytes. My sketch is 5124 bytes. There is a certain amount of "overhead" involved when using `sprintf()`.

The question you have to ask yourself is, "Does saving 1000 bytes matter?".


body:
I'm looking for a way to get lots of sensory data from my Arduino Micro to a PHP script.
My current attempt is using the following AT-commands:

    Sent: [AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54]
    Res: [AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_]

As you can see I send a long GET-parameter to my server with shortened parameter Names like t0 for temperature sensor number zero, l for light and so on.

In the response from my **SIM800l** I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.

After that command when it tries to finish the HTTP request I get a lot of errors as AT-command responses and no GET data arrives on my script.

----------

I check wheter or not data has arrived with the following function on my server:

    ob_start();
    echo "Var_dump of GET\n";
    var_dump($_GET);

    echo "Var_dump of POST\n";
    var_dump($_POST);
    $vd_res = ob_get_clean();

    file_put_contents('postdump.log', $vd_res."\n",FILE_APPEND);

When typing some data directly into the browser it saves my sent data in postdump.log so I'm pretty sure the SIM-module can't handle the given amount of data.

Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

title: Send big amouts of data to PHP script via gsm module SIM800L

Answers: 1

body:
> Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

Do a POST request. You can send huge amounts of data in the body.

> In the response from my SIM800l I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.

Nope.

I guess you're doing something like:

    sendCommand("AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54");
    delay(1000);
    printResponse();

The problem there is that you're relying on the internal buffer of `SoftwareSerial` (or `HardwareSerial` if you use a real serial port). You wait for a predefined time for characters to arrive, and then after that time print them out.  The serial code has a 64 byte buffer.

I see that kind of code all over the place, and it's the worst possible way of reading serial. Whoever posted the first instance of such code and started this chain of evil should be taken outside and shot.

Instead you must read the serial *properly*. Being lazy like that doesn't work.

Read [this blog post](https://majenko.co.uk/blog/reading-serial-arduino) to learn more about reading serial data properly.


body:
I have recently started digging into ESP8266 and learned a little about AT commands and i would really like to add the Wi-Fi functionality in my electronics project, which already uses an Arduino UNO R3. I think it would be much easier to use the Wemos D1 R2 since it is basically an UNO + ESP8266. Here is a link to the official product information page: https://wiki.wemos.cc/products:d1:d1 and its schematic: https://wiki.wemos.cc/_media/products:d1:d1_v2.0.0.pdf

I would like to know if it's possible to use the Arduino IDE to program on the Wemos D1 as i do with the normal UNO but also at the same time, be able to send AT commands using its on-board ESP8266?

title: Can i use Arduino IDE with the Wemos D1 R2 AND also use its ESP8266 module to send AT commands?

Answers: 1

body:
*A year ago I ported my project from Uno with esp8266 (Uno WiFi Dev Ed) to Wemos D1 R2.*

Wemos D1 R2 board has esp8266 as the only MCU. The AT firmware is an application running in the esp8266. An Arduino sketch with esp8266 boards package is an application too, so it replaces the AT firmware.

Instead of AT commands you will use for networking the WiFi library of the esp8266 arduino package. It is much simpler and there are many examples.

The esp8266 and the D1 R2 board have 3.3 V logic level on pins. So be careful with inputs and check if your devices will read the 3.3 V as HIGH.

In code use Dx constants matching the labels on the board. D1 R2 has less pins then Uno. I recommend to use I2C devices if possible. I had a Grove Base shield on D1 R2, so I have [a mapping][2] of D1 R2 pins to 'Uno' pins.

Some of the esp8266 pins are read at boot as boot configuration. Pins D3 (io 0)
and D4 (io 2) have pull-up on board and pin D8 (io 15) has pull-down on board. Not all devices will work on this pins. [Here][1] is a pin overview of the NodeMcu and Wemos boards.

The esp8266 has only one ADC pin. The A0 of the esp8266 can read 0 to 1 V. Wemos boards have a voltage divider on A0 so the board's pin can read 0 to 3.3 V. Don't read A0 in every loop. WiFi part of the esp8266 uses the ADC hardware too and continuous reading of A0 interferes with WiFi operations.

The Wemos D1 R2 has a strong power regulator 7 to 20 V for Vin and power jack. You can power devices from 5V and 3.3V pin. I use Grove relay modules powered from 5V pin and controlled by logic signal at 3.3 V.

  [1]: https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845
  [2]: https://github.com/jandrassy/Regulator/blob/8262f28b7452df0b75aa6c5a7bc676e14cd0cd26/Regulator/gbs-d1r2.h#L1


body:
I am trying to communicate with two i2c components using an arduino nano - some [ADS1115s][1] and some [i2c flow sensors][3] each connected to a different [i2c multiplexer][2], but they seem to be conflicting.

Some of the ADS1115s are 0x49 addresses, the same as all the flow sensors. The full code works, including constructing and initialising the ads1115s, but if I then try to read from them also, I don't get almost any data from the flow sensors (they just read 0 or close to when they should be reading around 8192 for zero flowrate). Any help or suggestions much appreciated!

I've put the full code at the bottom as its quite long and I keep changing it anyway but the important parts are here:

ADS1115:

    Adafruit_ADS1115();  //Construct an instance of an ADS1115 with the default address (0x48)
    ads1115.begin();  // Initialize ads1115
    int16_t readADC_Differential_0_1(void);  //Perform a differential analog to digital conversion on the voltage between channels 0 and 1.

tca9548a multiplexer:

    #define TCAADDR 0x70

    void tcaselect(uint8_t i) {
      if (i > 7) return;

      Wire.beginTransmission(TCAADDR);
      Wire.write(1 << i);
      Wire.endTransmission();
    }

    tcaselect(i);

Zephyr flow sensors:

    void getflows (int sensor, float range, float flowreading) {
    Wire.requestFrom(0x49, 2);
    while (Wire.available())   // slave may send less than requested
      {
        int flowdata = Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowdata = flowdata << 8;
        flowdata |= Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowreading = range * ((flowdata / 16384.0) - 0.5) / 0.4;
        //Serial.print("sensor 3 flow = "); Serial.println(flow3);
        //Serial.println();         // print the character
        //Serial.println();
      }
      delay(20);
}

The full code:

    #include <ModbusRtu.h>
    #include <Wire.h>
    #include <Adafruit_ADS1015.h>
    #include <SPI.h>
    #include <PID_v1.h>
    #include <math.h>

    //modbus
    #define ID          1
    #define TXEN        2

    //valve TTL and DAC CS pins - nos correspond to valve driver numberings in rig box
    //Current connections - O2high = 1 = A, CO2 = 2 = B, O2low = 3 = C
    #define ATTL       5
    #define CTTL       4
    #define BTTL       3

    #define BCS         7
    #define CCS         8
    #define ACS         9

    #define tempfreq    5
    #define tempnum     3
    ///////////////////////////////////////////
    //Sensor ranges - USER DEFINED
    float DACrange = 3500.0; //ml/min

    int POutrange = 2000; //mbar abs
    int PInrange = 2000; //mbar abs
    ///////////////////////////////////////////

    //ADC multiplexer
    #define TCAADDR      0x70
    #define TCA2ADDR      0x77

    //Input resistor values
    float         T1R2  =  2320.0;
    float         FPR1  =  3090.0;
    float         FPR2  =  12010.0;

    //max variation from setpoint before PID cycle
    int maxdif    =  5;
    //max variation from setpoint at end of PID cycle
    int PIDdif    =  1;

    ///////////////////////////////////////////
    //MATHS
    //scale factor
    long FPscale = 10000000;
    long flowscale = 10000000;
    //vrefs - with scale factors applied
    float vref   = 2.5; //tscaled
    float Tref   = 1.0; //tscaled
    long FPref  = 20000000; //FPscaled
    //divisions - integrated to sensor range in long format for calculations
    float FPdiv = (FPR1 + FPR2) / FPR2;
    int Vmax = 5;

    int Poutfac = (int)((POutrange / Vmax) * FPdiv);
    int Pinfac = (int)((PInrange / Vmax) * FPdiv);

    //ADC mv/bit
    float Tbit = 0.00003125;
    long FPbit = 625; //- with scale factor of 10,000,000

    //temp sensor steinhart constants
    double sA = 0.001462146;
    double sB = 0.0002393355;
    double sC = 0.0000000963049;

    //declare holding constants
    int16_t hT1 = 0;
    int16_t hT2 = 0;
    int16_t hT3 = 0;
    int16_t hT4 = 0;
    int16_t hT5 = 0;
    int16_t hT6 = 0;
    int16_t hT7 = 0;
    int16_t hT8 = 0;

    int16_t hFP1 = 0;
    int16_t hFP2 = 0;
    int16_t hFP3 = 0;
    int16_t hFP4 = 0;
    int16_t hFP5 = 0;
    int16_t hFP6 = 0;
    int16_t hFP7 = 0;
    int16_t hFP8 = 0;

    //intermediates
    int i = 0;
    int j = 0;
    int b[3];
    int loopnum = tempfreq;
    float tres = 0.0;
    double treslog = 0.0;
    long lconv = 0;
    int16_t O2dif = 0;
    int16_t CO2dif = 0;
    int16_t N2dif = 0;
    int16_t gasdif = 0;
    int gasreading = 0;
    int hFP = 0;
    uint16_t val = 0;
    bool truePID;
    bool trueAPID = false;
    bool trueBPID = false;
    bool trueCPID = false;
    int (*gasreadfunc)();

    int flowdata = 0;
    float flow3 = 0.0;
    float flow2 = 0.0;
    float flow4 = 0.0;
    float flow5 = 0.0;
    long reading = 0;

    uint16_t Setpt;
    int CS;
    int TTL;

    //initialise nested functions
    //void eachPID(int16_t (*)(), int16_t, int, bool);

    enum
    {
      Error1,    //CHANNEL 0  //0
      Error2,    //CHANNEL 1
      FP2a,      //CHANNEL 2  //1
      FP2b,      //CHANNEL 3
      T1a,       //CHANNEL 4  //2
      T1b,       //CHANNEL 5
      T2a,       //CHANNEL 6  //3
      T2b,       //CHANNEL 7
      T3a,       //CHANNEL 8  //4
      T3b,       //CHANNEL 9
      T4a,       //CHANNEL 10 //5
      T4b,       //CHANNEL 11
      Flow2a,    //CHANNEL 12 //6
      Flow2b,    //CHANNEL 13
      Flow3a,    //CHANNEL 14 //7
      Flow3b,    //CHANNEL 15
      Flow4a,    //CHANNEL 16 //8
      Flow4b,    //CHANNEL 17
      Flow5a,    //CHANNEL 18 //9
      Flow5b,    //CHANNEL 19
      A_set,     //CHANNEL 20
      B_set,     //CHANNEL 21
      C_set,     //CHANNEL 22
      HOLDING_REGS_SIZE
    };

    unsigned int holdingRegs[HOLDING_REGS_SIZE];

    /**
        Modbus object declaration
        u8id : node id = 0 for master, = 1..247 for slave
        u8serno : serial port (use 0 for Serial)
        u8txenpin : 0 for RS-232 and USB-FTDI
                     or any pin number > 1 for RS-485
    */
    Modbus slave(1, 0, TXEN); // this is slave @1 and RS-485

    //Construct ADCs at addresses
    Adafruit_ADS1115 adcOne(0x48);
    Adafruit_ADS1115 adcTwo(0x49);
    Adafruit_ADS1115 adcThree(0x4B);
    Adafruit_ADS1115 adcFour(0x4A);

    // SPI - set up the speed, data order and data mode
    SPISettings settings(4000000, MSBFIRST, SPI_MODE0);

    //PID
    //Define Variables we'll be connecting to
    double Output, Setpoint, Input;

    //Define the aggressive and conservative Tuning Parameters
    double aggKp = 4, aggKi = 0.2, aggKd = 1;
    double consKp = 1, consKi = 0.05, consKd = 0.25;

    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint, aggKp, aggKi, aggKd, DIRECT);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    void tcaselect(uint8_t i, int address) {
      if (i > 7) return;

      Wire.beginTransmission(address);
      Wire.write(1 << i);
      Wire.endTransmission();
    }

    void setup() {
      ///////////////////////////////////////////////////////////////////////////////////////////////
      //DAC
      pinMode (BCS, OUTPUT);
      digitalWrite(BCS, HIGH);
      pinMode (CCS, OUTPUT);
      digitalWrite(CCS, HIGH);
      pinMode (ACS, OUTPUT);
      digitalWrite(ACS, HIGH);

      pinMode (ATTL, OUTPUT);
      digitalWrite(ATTL, LOW);
      pinMode (CTTL, OUTPUT);
      digitalWrite(CTTL, LOW);
      pinMode (BTTL, OUTPUT);
      digitalWrite(BTTL, LOW);
      ///////////////////////////////////////////////////////////////////////////////////////////////
      //ADC
      adcOne.begin();
      adcTwo.begin();
      adcThree.begin();
      adcFour.begin();

      // 2/3x gain +/- 6.144V  1 bit = 0.1875mV (default)
      // ads1015.setGain(GAIN_ONE);     // 1x gain   +/- 4.096V  1 bit = 0.125mV
      // ads1015.setGain(GAIN_TWO);     // 2x gain   +/- 2.048V  1 bit = 0.0625mV
      // ads1015.setGain(GAIN_FOUR);    // 4x gain   +/- 1.024V  1 bit = 0.03125mV
      // ads1015.setGain(GAIN_EIGHT);   // 8x gain   +/- 0.512V  1 bit = 0.015625mV
      // ads1015.setGain(GAIN_SIXTEEN); // 16x gain  +/- 0.256V  1 bit = 0.0078125mV

      //////////////////////////////////////////////////////////////////////////////////////////////
      //Flow sensor serial number readouts
      getflows(2, 750.0, flow2);
      getflows(3, 400.0, flow3);
      getflows(4, 50.0, flow4);
      getflows(5, 400.0, flow5);

      //////////////////////////////////////////////////////////////////////////////////////////////
      //PID
      //initialize the variables we're linked to
      Input = 0;
      Setpoint = 0;

      //Define the aggressive and conservative Tuning Parameters
      float aggKp = 4, aggKi = 0.2, aggKd = 1;
      float consKp = 1, consKi = 0.05, consKd = 0.25;

      //turn the PID on
      myPID.SetMode(AUTOMATIC);
      //////////////////////////////////////////////////////////////////////////////////////////////
      // start modbus communication
      slave.begin(115200);

      // initialize SPI:
      SPI.begin();

      //Serial.begin(115200);
      gettemperatures();

      holdingRegs[Error2] = 0;
    }

    void loop() {
      //each tempfreq no of loops, it reads the temp sensors also
      loopnum++;
      if (loopnum > tempfreq) {
        gettemperatures();
        loopnum = 0;
      }

      holdingRegs[Error1] = 0;//set to 0 for normal operation, 65535 = PID control
      //Serial.print("Holding Regs Error1 "); Serial.print(holdingRegs[Error1]); Serial.print(", holdingRegs[Error2]"); Serial.println(holdingRegs[Error2]);

      //flow and pressure sensors
      tcaselect(0, TCAADDR);
      adcOne.setGain(GAIN_TWO);
      //adcTwo.setGain(GAIN_TWO);
      //adcThree.setGain(GAIN_TWO);
      //adcFour.setGain(GAIN_TWO);

      //hFP1 = adcOne.readADC_Differential_0_1();
      hFP2 = adcOne.readADC_Differential_2_3();
      //hFP3 = adcTwo.readADC_Differential_0_1();
      //hFP4 = adcTwo.readADC_Differential_2_3();
      //hFP5 = adcThree.readADC_Differential_0_1();
      //hFP6 = adcThree.readADC_Differential_2_3();
      //hFP7 = adcFour.readADC_Differential_0_1();
      //hFP8 = adcFour.readADC_Differential_2_3();

      //FPconv(hFP1, &holdingRegs[FP1a], &holdingRegs[FP1b], Pinfac);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      FPconv(hFP2, &holdingRegs[FP2a], &holdingRegs[FP2b], Poutfac);
      //Serial.print("hFP2: "); Serial.println(hFP2);
      //FPconv(hFP3, &holdingRegs[FP3a], &holdingRegs[FP3b], CO2fac);
      //Serial.print("hFP3: "); Serial.println(hFP3);
      //FPconv(hFP4, &holdingRegs[FP4a], &holdingRegs[FP4b], O2fac);
      //Serial.print("hFP4: "); Serial.println(hFP4);
      //FPconv(hFP5, &holdingRegs[FP5a], &holdingRegs[FP5b], Finfac);
      //Serial.print("hFP5: "); Serial.println(hFP5);
      //FPconv(hFP6, &holdingRegs[FP6a], &holdingRegs[FP6b], N2fac);
      //Serial.print("hFP6: "); Serial.println(hFP6);
      //FPconv(hFP7, &holdingRegs[FP7a], &holdingRegs[FP7b], Finfac);
      //Serial.print("hFP7: "); Serial.println(hFP7);
      //FPconv(hFP8, &holdingRegs[FP8a], &holdingRegs[FP8b], Finfac);
      //Serial.print("hFP8: "); Serial.println(hFP8);
      //Serial.println("");

      getflows(2, 750.0, flow2);
      getflows(3, 400.0, flow3);
      getflows(4, 50.0, flow4);
      getflows(5, 400.0, flow5);

      flowconvert();

      //modbus communication
      slave.poll( holdingRegs, HOLDING_REGS_SIZE );

      checkgasflow(1);
      checkgasflow(2);
      checkgasflow(3);

      //delay(1000);
    }

    void gasread(int gastoread) {
      switch (gastoread) {
        case 1: //O2high
          getflows(3, 400.0, flow3);
          gasreading = flow2;
          Setpt = A_set;
          CS = ACS;
          TTL = ATTL;
          truePID = trueAPID;
          //return gasreading;
          break;
        case 2: //CO2
          getflows(4, 50.0, flow4);
          Setpt = B_set;
          CS = BCS;
          TTL = BTTL;
          truePID = trueBPID;
          //return gasreading;
          break;
        case 3: //O2low
          getflows(5, 400.0, flow5);
          Setpt = C_set;
          CS = CCS;
          TTL = CTTL;
          truePID = trueCPID;
          //return gasreading;
          break;
      }
    }

    void checkgasflow(int gastoread) {
      gasread(gastoread);
      Input = (double)gasreading;
      Setpoint = (double)Setpt;
      gasdif = Input - Setpoint;
      if (abs(gasdif) < PIDdif) {
        truePID = 1;
        return;
      }
      else {
        GasPID();
      }
    }

    void GasPID() {
      holdingRegs[Error1] = 65535; //set to 0 for normal operation, 65535 = PID control

      //modbus communication
      slave.poll( holdingRegs, HOLDING_REGS_SIZE );

      do {
        eachPID(1);
        eachPID(2);
        eachPID(3);
      } while (!trueAPID || !trueBPID || !trueCPID);

      holdingRegs[Error1] = 0;
    }

    void eachPID(int gastoread) {
      gasread(gastoread);
      Input = (double)gasreading;
      Setpoint = (double)Setpt;
      gasdif = Input - Setpoint;
      if (abs(gasdif) < PIDdif) {
        truePID = 1;
        return;
      }
      else if (abs(gasdif) < 10)
      { //we're close to setpoint, use conservative tuning parameters
        truePID = 0;
        myPID.SetTunings(consKp, consKi, consKd);
      }
      else
      {
        //we're far from setpoint, use aggressive tuning parameters
        truePID = 0;
        myPID.SetTunings(aggKp, aggKi, aggKd);
      }
      myPID.Compute();
      val = (uint16_t)Output;
      DACspi(CS, val, TTL);
    }

    void FPconv (int16_t FPin, uint16_t *hRega, uint16_t *hRegb, int FPfac) {
      lconv = (FPfac * (FPref + (long)(FPbit * FPin)));
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
    }

    void Flowconv (float FPin, uint16_t *hRega, uint16_t *hRegb) {
      lconv = (long)(FPin*flowscale);
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
    }

    void Tconv (int16_t Tin, uint16_t *hRega, uint16_t *hRegb) {
      tres = T1R2 * ((vref / (Tref + (Tbit * Tin))) - 1.0);
      treslog = log(tres);
      lconv = lround(10000000.0 * ((1.0 / (sA + sB * treslog + sC * (pow(treslog, 3.0)))) - 273.15));
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
    }

    void DACspi(uint16_t CS, uint16_t val, int TTL) {
      digitalWrite(CS, LOW);
      if (val > 0) {
        digitalWrite(TTL, HIGH);
      }
      else {
        digitalWrite(TTL, LOW);
      }
      SPI.transfer16(val);
      digitalWrite(CS, HIGH);
    }

    void gettemperatures() {
      tcaselect(6, TCAADDR);
      adcOne.setGain(GAIN_FOUR);
      adcTwo.setGain(GAIN_FOUR);
      adcThree.setGain(GAIN_FOUR);
      adcFour.setGain(GAIN_FOUR);
      //temp sensors - 2 consecutive readings to allow pins to warm up first
      for (i = 0; i < tempnum; i++) {
        hT1 = adcOne.readADC_Differential_0_1();
      }
      for (i = 0; i < tempnum; i++) {
        hT2 = adcOne.readADC_Differential_2_3();;
      }
      for (i = 0; i < tempnum; i++) {
        hT3 = adcTwo.readADC_Differential_0_1();
      }
      for (i = 0; i < tempnum; i++) {
        hT4 = adcTwo.readADC_Differential_2_3();
      }
      //for (i = 0; i < tempnum; i++) {
      //  hT5 = adcThree.readADC_Differential_0_1();
     // }
      //for (i = 0; i < tempnum; i++) {
      //  hT6 = adcThree.readADC_Differential_2_3();
      //}
      //for (i = 0; i < tempnum; i++) {
      //  hT7 = adcFour.readADC_Differential_0_1();
      //}
      //for (i = 0; i < tempnum; i++) {
      //  hT8 = adcFour.readADC_Differential_2_3();
      //}

      Tconv(hT1, &holdingRegs[T1a], &holdingRegs[T1b]);
      //Serial.print("hT1: "); Serial.println(hT1);
      Tconv(hT2, &holdingRegs[T2a], &holdingRegs[T2b]);
      //Serial.print("hT2: "); Serial.println(hT2);
      Tconv(hT3, &holdingRegs[T3a], &holdingRegs[T3b]);
      //Serial.print("hT3: "); Serial.println(hT3);
      Tconv(hT4, &holdingRegs[T4a], &holdingRegs[T4b]);
      //Serial.print("hT4: "); Serial.println(hT4);
      //Tconv(hT5, &holdingRegs[T5a], &holdingRegs[T5b]);
      //Serial.print("hT5: "); Serial.println(hT5);
      //Tconv(hT6, &holdingRegs[T6a], &holdingRegs[T6b]);
      //Serial.print("hT6: "); Serial.println(hT6);
      //Tconv(hT7, &holdingRegs[T7a], &holdingRegs[T7b]);
      //Serial.print("hT7: "); Serial.println(hT7);
      //Tconv(hT8, &holdingRegs[T8a], &holdingRegs[T8b]);
      //Serial.print("hT8: "); Serial.println(hT8);
    }

    void getflows (int sensor, float range, float flowreading) {
      tcaselect(sensor, TCA2ADDR);
      Wire.requestFrom(0x49, 2);

      while (Wire.available())   // slave may send less than requested
      {
        int flowdata = Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowdata = flowdata << 8;
        flowdata |= Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowreading = range * ((flowdata / 16384.0) - 0.5) / 0.4;
        //Serial.print("sensor 3 flow = "); Serial.println(flow3);
        //Serial.println();         // print the character
        //Serial.println();
      }
      delay(20);
    }

    void flowconvert (){

      Flowconv(flow2, &holdingRegs[Flow2a], &holdingRegs[Flow2b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      Flowconv(flow3, &holdingRegs[Flow3a], &holdingRegs[Flow3b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      Flowconv(flow4, &holdingRegs[Flow4a], &holdingRegs[Flow4b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      Flowconv(flow5, &holdingRegs[Flow5a], &holdingRegs[Flow5b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
    }

    /*void FPconv (int16_t FPin, uint16_t *hRega, uint16_t *hRegb, int FPfac, long FPcal) {
      lconv = (FPfac * (FPcal + FPref + (long)(FPbit * FPin)));
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
      }*/

    /*void GasPID() {
      holdingRegs[Error1] = 65535; //set to 0 for normal operation, 65535 = PID control

      //modbus communication
      slave.poll( holdingRegs, HOLDING_REGS_SIZE );

      tcaselect(0);

      do {
        eachPID(O2read, O2_set, BCS, trueAPID);
        eachPID(CO2read, CO2_set, CCS, trueBPID);
        eachPID(N2read, N2_set, ACS, trueCPID);
      } while (!trueAPID || !trueBPID || !trueCPID);

      trueAPID = !trueAPID;
      trueBPID = !trueBPID;
      trueCPID = !trueCPID;
      }*/

    /*
      void eachPID(int16_t gasReadfunc(), int16_t Setpt, int CS, bool truePID, int TTL) {
      Setpoint = (double)Setpt;

      for (i = 0; i < 3; i++) {
        hFP = (*gasreadfunc)();
      }
      Input = (double)hFP;
      gasdif = Input - Setpoint;
      if (abs(gasdif) < PIDdif) {
        truePID = 1;
        return;
      }
      else if (abs(gasdif) < 10)
      { //we're close to setpoint, use conservative tuning parameters
        myPID.SetTunings(consKp, consKi, consKd);
      }
      else
      {
        //we're far from setpoint, use aggressive tuning parameters
        myPID.SetTunings(aggKp, aggKi, aggKd);
      }
      myPID.Compute();
      val = (uint16_t)Output;
      DACspi(CS, val, TTL);
      }*/

    /*//Connections
      int16_t O2read() {
      gasread = adcOne.readADC_Differential_0_1();
      return gasread;
      }
      int16_t CO2read() {
      gasread = adcOne.readADC_Differential_2_3();
      return gasread;
      }
      int16_t N2read() {
      gasread = adcTwo.readADC_Differential_0_1();
      return gasread;
      }*/

    /*// SPI communication with DAC
      DACspi(BCS, holdingRegs[CO2_set], BTTL); //CO2 controller
      DACspi(CCS, holdingRegs[N2_set], CTTL); //N2 controller
      DACspi(ACS, holdingRegs[O2_set], ATTL); //O2 controller*/

  [1]: https://www.adafruit.com/product/1085
  [2]: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout/wiring-and-test
  [3]: https://www.mouser.co.uk/datasheet/2/187/honeywell-sensing-airflow-zephyr-haf-series-digita-740409.pdf

title: conflict with different i2c devices

Answers: 2

body: I had not realised that once opened, the tca9548a channels stay open until either POR or the RESET pin is brought low. Hence when using two multiplexers I just needed to use an extra wire to the RESET pin on each from the nano.

body:
You pass `flowreading` to `void getflows (int sensor, float range, float flowreading)` as a value and therefore changing `flowreading` has no effect on the variable you pass to that function.

Instead, you need to do `void getflows (int sensor, float range, float *flowreading)`.


body:
I'm trying to set up an Arduino Mega with a SIM800L module and trying to get Modbus TCP running on said Mega. I've set Modbus TCP over wifi and serial before but I used libraries for those. The problem is, I can't find a suitable library for SIM800L that has Modbus support in it. The project is supposed to get Modbus TCP to places without wifi, using a static IP enabled sim card. My question here is, am I missing something? While working with ESP8266 and Serial, I was able to find a ton of libraries to work with, but SIM800 series returns nothing for me.
Thanks!

title: Arduino Mega with SIM800L running Modbus TCP/IP

Answers: 0


body:
I connected my brand new Arduino Nano 3.0 clone with CH340G and installed the drivers. It detects in Device Manager as USB-SERIAL CH340 (COM6). Under the Tools menu, i selected the correct board, the processor set to ATmega328P and the COM port. I couldn't upload my sketch so i tried uploading an example Blink sketch from Arduino IDE. The uploading is stuck. I keep waiting and nothing happens. I have read somewhere else that i should enable verbose output for compilation and upload, which i did and here is the output for trying to upload the basic Blink sketch.

    Arduino: 1.8.9 (Windows 7), Board: "Arduino Nano, ATmega328P"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\admin\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\admin\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\admin\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path C:\Users\admin\AppData\Local\Temp\arduino_build_747566 -warnings=none -build-cache C:\Users\admin\AppData\Local\Temp\arduino_cache_890158 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avrdude.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.arduinoOTA.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\admin\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\admin\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\admin\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path C:\Users\admin\AppData\Local\Temp\arduino_build_747566 -warnings=none -build-cache C:\Users\admin\AppData\Local\Temp\arduino_cache_890158 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avrdude.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.arduinoOTA.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
    Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp" -o nul
    Generating function prototypes...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp" -o "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\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\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp" -o "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core: C:\Users\admin\AppData\Local\Temp\arduino_cache_890158\core\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a
    Linking everything together...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp.o" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/..\\arduino_cache_890158\\core\\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566" -lm
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.eep"
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.hex"
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-size" -A "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf"
    Sketch uses 930 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -CC:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b115200 -D -Uflash:w:C:\Users\admin\AppData\Local\Temp\arduino_build_747566/Blink.ino.hex:i
    An error occurred while uploading the sketch

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

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

             Using Port                    : COM6
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd8

    avrdude done.  Thank you.

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

title: Arduino Nano 3.0 CH340G clone cannot upload sketch from Arduino IDE

Answers: 1

body:
You normally just have to press 'reset' on the board button 1 sec before clicking 'Upload'.

I had to do this with cheap Nano clone.


body:
I bought a GSM module, and I want to connect it with Arduino but I have a problem.

I linked GSM SIM800L with regular LM2596 12 V 2 VA I changed tension to 5 V, So far the GSM is working but if I connect TX_ARDUINO with RX_GSM the module enters in the loop of the restart.

The picture explains the montage.

[![Fritzing of LM2596, SIM800L and Arduino Uno][1]][1]

  [1]: https://i.stack.imgur.com/QGeI6.png "Fritzing of LM2596, SIM800L and Arduino Uno"

title: How I can connect module GSM SIM800L?

Answers: 1

body:
[![Arduino Sim800l][1]][1]

Follow [this tutorial][2] on how to connect your Sim800l with Arduino.

  [1]: https://i.stack.imgur.com/tWSY5.jpg
  [2]: https://www.teachmemicro.com/arduino-sim800l-tutorial/


body:
I have a nice sketch running which monitors a few things and displays output on an OLED display. Now I want to save the data to an SD card, but with or without the card module attached I'm getting constant reboots when I add 1 single line of code:

    #include <SD.h>

Any idea what may be happening?

title: SD.h causing constant reboot

Answers: 1

body:
The following libraries are probably used:

- SD Card, using a buffer of 512 bytes (see also the comment of DataFiddler below).
- SSD1306 OLED library, using a buffer of 1,024 bytes
- Serial, using a buffer of 128 bytes (64 for RX, 64 for TX, see comment of Majenko below)

Since there is only 2,048 bytes of SRAM in an Arduino, this leaves 384 bytes. If you actually READ a file you are already above the maximum.

Your own global variables also will consume a considerable amount of SRAM.

Than, if you execute your sketch, parameters and local variables are stored on the stack (in SRAM), so even if your program starts well, it might/will run in problems when calling functions.


body:
I am following [this tutorial][1], and have wired Arduino using this diagram:

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

This is what it looks like:

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

These options are selected in Arduino IDE:

[![enter image description here][4]][4]

This is the program I'm uploading:

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

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

When I upload it, it's uploaded on the Atmega on arduino board, not the one on breadboard. Both chips are ATMEGA328P.

I also tried to put 10μF capacitor between GND and RESET pins of the arduino board, which led to following errors:

    Sketch uses 936 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\Jakub\AppData\Local\Temp\arduino_build_319338/BlinkTestAtmega.ino.hex:i

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x12
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

    avrdude done.  Thank you.

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

Note that I have a homemade ATTINY programmer shield for this arduino board and it works without problems.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
  [2]: https://i.stack.imgur.com/sckRD.png
  [3]: https://i.stack.imgur.com/JTp6O.jpg
  [4]: https://i.stack.imgur.com/GUJwX.png

title: Arduino as ISP - program is being uploaded on Arduino, not breadboard

Answers: 1

body:
Use the "Upload using programmer" in Sketch menu to upload a sketch over ISP

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

warning, it deletes the bootloader

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


body: I made a script for my Arduino Pro Micro that was very large (Global variables were 98% of the intended storage). The Arduino was not recognised by Windows after loading the script and I don't know how to fix this issue.

title: Arduino not recognised by windows after using a lot of the storage

Answers: 0


body:
Let me preface by saying that I am not super experienced with electronics. I have an Adafruit Feather 32u4 that is using Hardware SPI to communicate over Bluetooth. Unfortunately, I'm also hoping to use the SD library, which also uses Hardware SPI. I am hoping to change the board to use Software SPI instead, so that the two may work together.

The Bluefruit code by default has the following commented out:

    /* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
    Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
                                 BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
                                 BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

Which leads me to believe I could use SW SPI but simply uncommenting this and commenting out the HW SPI doesn't seem to work.

I am just not sure if it's not compatible with the board, or I need to do more than this...?

title: Adafruit Feather 32u4 BLE compatible with Software SPI?

Answers: 1

body:
Read SparkFun's guide, [Serial Peripheral Interface (SPI)][1], especially the [multiple slaves][2] section:

----

> ### Multiple slaves
>
> There are two ways of connecting multiple slaves to an SPI bus:
>
> 1. In general, each slave will need a separate SS line. To talk to a particular slave, you'll make that slave's SS line low and keep the
> rest of them high (you don't want two slaves activated at the same
> time, or they may both try to talk on the same MISO line resulting in
> garbled data). Lots of slaves will require lots of SS lines; if you're
> running low on outputs, there are binary decoder chips that can
> multiply your SS outputs.
>
> [![enter image description here][3]][3]
>
> 2. On the other hand, some parts prefer to be daisy-chained together, with the MISO (output) of one going to the MOSI (input) of the next.
> In this case, a single SS line goes to all the slaves. Once all the
> data is sent, the SS line is raised, which causes all the chips to be
> activated simultaneously. This is often used for daisy-chained shift
> registers and addressable LED drivers.
>
> [![enter image description here][4]][4]
>
> Note that, for this layout, data overflows from one slave to the next,
> so to send data to any one slave, you'll need to transmit enough data
> to reach all of them. Also, keep in mind that the first piece of data
> you transmit will end up in the last slave.
>
> This type of layout is typically used in output-only situations, such
> as driving LEDs where you don't need to receive any data back. In
> these cases you can leave the master's MISO line disconnected.
> However, if data does need to be returned to the master, you can do
> this by closing the daisy-chain loop (blue wire in the above diagram).
> Note that if you do this, the return data from slave 1 will need to
> pass through all the slaves before getting back to the master, so be
> sure to send enough receive commands to get the data you need.

  [1]: https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi/all
  [2]: https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi/all#slave-select-ss
  [3]: https://i.stack.imgur.com/dskyc.png
  [4]: https://i.stack.imgur.com/soEKe.png


body:
![enter image description here](https://i.stack.imgur.com/0hOAj.jpg)

hello friends do you know if, can this shield (SIM808 EVB V3.2) charge a lithium battery directly or i need additional hardware?, I know that module has conection for battery but it can charge it?

title: Shield SIM808 EVB V3.2 charge a Lithium battery?

Answers: 1

body:
The module does not include a charging circuit for Lithium-ion cells.

----------

**EDIT**

According to the [SIM808 Hardware Design document, Page 28][1], the SIM808 module **does** integrate Lithium-ion cell charging.

It states that the battery should have it's own overcharge, over discharge, over current protection, and reverse-polarity protection.

  [1]: https://seeeddoc.github.io/Mini_GSM-GPRS_Plus_GPS_Breakout-SIM808/res/SIM808_Hardware_Design_V1.00.pdf#page=28


body:
What is required is controlling the brightness of an LED using both Buttons and a Potentiometer,
Button A: Increase

Button B: Decrease /Dim

Potentiometer: Increase and Decrease,

This however must happen on 1 single circuit and must display the results on an LCD.

If I do this separately, meaning buttons without potentiometer and visa versa, I win, the moment I combine the two. I get flickering when working the buttons, due to the potentiometer.

Alternative Research:[https://www.instructables.com/id/Smooth-Potentiometer-Input/][1]

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

    #include <LiquidCrystal.h>
    #include <Wire.h>
    // ------------------------------------------------------------

    int LED1          = 9;
    int ButtonLeft    = 8;
    int ButtonRight   = 7;
    int brightness    = 0;

    // ------------------------------------------------------------
    byte buttonState1     = 0;
    byte lastButtonState1 = 0;

    byte buttonState2     = 0;
    byte lastButtonState2 = 0;

    unsigned long switchMillis;

    // ------------------------------------------------------------

    int potValue1 = 0;
    int potValue2 = 0;
    int potPin= A0;
    int readValue;
    int writeValue;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    // ------------------------------------------------------------
    void setup() {

      lcd.begin(16, 2);
      pinMode (potPin, INPUT);
      pinMode(LED1,OUTPUT);
      pinMode(ButtonLeft,INPUT);
      pinMode(ButtonRight,  INPUT);
      lcd.clear ();
    }

    // ------------------------------------------------------------
    void loop(){

        if (millis() - switchMillis >= 5)
      {
        switchMillis = millis();
        checkSwitches();
      }

       readValue = analogRead(potPin);
       writeValue = (255./1023.) * readValue;
       analogWrite(LED1, writeValue);

        potValue1 = analogRead(potPin) / 10;
        potValue2 = potValue1 / 1.02;

        lcd.setCursor(0,0);
        lcd.print("Potent=");
        lcd.print(potValue1);
        lcd.print("%");
        delay(100);
        lcd.print(" ");
        delay(1);
    }

    void checkSwitches() {

        analogWrite(LED1, brightness);
        delay(10);

      buttonState1 = digitalRead(ButtonLeft);

      if(buttonState1 == HIGH){
        brightness--;
        if(brightness < 0){
          brightness = 0;
        }
      }

      buttonState2 = digitalRead(ButtonRight);

      if(buttonState2 == HIGH){
        brightness++;
        if(brightness > 255){
          brightness = 255;
        }
      }

     lcd.setCursor (0,1);
     lcd.print ("Brightness=");
     lcd.print (brightness);
     lcd.print ("   ");
    }

  [1]: https://www.instructables.com/id/Smooth-Potentiometer-Input/
  [2]: https://i.stack.imgur.com/88swe.jpg

title: PWM Control, How to stop LED from Flickering?

Answers: 1

body:
Your code doesn't make much sense.

You set the LED to 2 different brightness values that don't have anything to do with each other: The pot brightness and the button-based brightness. You only adjust the LED based on switches once every 5 mS. Thus the LED is going to flicker between 2 different brightness values.

What do you want it to do? How do you want to control the brightness based on input from both the pot and your switches? (What is the relationship between the buttons and the pot? Should the button input alter max/min value of the pot up and down? Should holding the button down change the brightness by 1 value per a specific time unit? Say 2 increments/decrements per second?)

Describe the user interface you want to achieve, and then think through how you would do that in code.


body:
I have a 4 channel relay for my Arduino. Here's an image:

[![Relay][1]][1]

**From what I can tell, it's rated for 5V direct current because of the big `05VDC` at the bottom, but please tell me if I'm wrong? If I'm wrong, then that's the problem here.**

I've tested out an LED on 5V DC to work and connected it to output side of the relay.

I've connected my Arduino to the input, programmed with the following code:

    const int RELAY_PIN = 3;

    void setup() {
      pinMode(RELAY_PIN, OUTPUT);
      Serial.begin(96000);

    }

    void loop() {
      Serial.println("Relay ON");
      digitalWrite(RELAY_PIN, LOW);
      delay(1000);

      Serial.println("Relay OFF");
      digitalWrite(RELAY_PIN, HIGH);
      delay(1000);
    }

I can confirm that the corresponding LED on the relay for channel 4 does blink for 1 second and stay off for 1 second, which I'm expecting it's meant to do. I've never worked with an Arduino or a relay before.

However, the 5V DC LED on the other end never lights up. Why is my relay not switching on?

Edit: About the LED circuit. It is on and fully powered. If I bypass the relay and join the two wires, the LED lights up. If I plug the two wires into the relay, the LED never lights up.

Edit2: About the jumper: I have a secondary 5V power supply connected to the VCC for what I'm told is isolation. I've read a little on the matter, but am not fully aware of how it works.

Edit 3:

**Connections**

I have the following connections:

 - Output 3 (Arduino) to Input 4 (Relay)
 - 5V (Arduino) to Input VCC (Relay) [The one next to the input pins]
 - Power supply positive/ground to GND (Relay)
 - Power supply negative/live to VCC (the one next to the JD-VCC)

This did not work. What did work was the following configuration:

 - Output 3 (Arduino) to Input 4 (Relay)
 - 5V (Arduino) to Input VCC (Relay) [The one next to the input pins]
 - Jumper across VCC and JD-VCC on the Relay

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

title: Why is my relay not triggering?

Answers: 2

body:
A relay is an electromagnet-driven switch. It opens and closes that switch, but doesn't provide power.

Assuming it's like my relays, that relay can either power the relay coils AND the logic inputs, or (if you remove the jumper) use separate power for the relay coils and the logic signals.

Since you've removed the jumper, you need to provide 2 different 5V power sources to drive the relay - one high-current supply to the VCC, which runs the logic circuits and the relay coil. Another to the logic power in. Then you ground the input pin to activate one of the relay channels.

Finally, you need to wire the screw terminals on the left side into a circuit with separate power that controls something. For an LED, you'd need power, the LED, and a current-limiting resistor wired in series with the screw terminals on LED channel 1.

For an LED this is serious overkill. You could drive the LED directly (with a current limiting resistor) from the Arduino logic signal.

body:
 - From the image in the question, the jumper across pins J5 (in the
   below schematic) or JD as on the silk screen on the PBC is missing.
[![enter image description here][1]][1]

 - Using the above schematic, a choice to power the Ardino and the relays off of one 5V power supply can be made.  This appears to be done by connecting the 5V to the VCC pin, Ground to the GND pin & placing a jumper across J5.  However, it appears that the relays can be isolated from the Arduino if desired.  This appears to be done by connecting the Arduino's 5V to pin 2 of J5.  That should be enough to light up the LED indicator and therefor the optical isolator when the Arduino's output to IN1, 2, 3 or 4 is low.  Then, connect the 2nd power source 5V to pin 1 of J5 and the ground from the 2nd power source to pin GND.  This last step should provide the power to close the relays when the Arduino takes IN1, 2, 3 or 4 low.
 - Lastly, make sure the polarity of the 2nd power supply (if one is used) is correct.  The output side of the optical coupler and the transistor driving the relay only work when the current is passing in the proper direction. Not to mention, the reverse bias [flyback diode][2] (D1, 2, 3 & 4) would short out the power supply if connected in the reverse direction.  However, this catastrophe is avoided here as the transistors (Q1, 2, 3 & 4) would not pass current in the reversed direction.

  [1]: https://i.stack.imgur.com/wXP4o.png
  [2]: https://electronics.stackexchange.com/questions/100134/why-is-there-a-diode-connected-in-parallel-to-a-relay-coil


body:
I'm currently trying to control a brushless DC motor (EMAX 1806-2280Kv) with a ESC called Wasabi Eco 12A ([Wasabi Eco specifications#1][1] , [Wasabi Eco specifications#2][2])

I'm trying to control the motor via an Arduino Uno, and using their IDE to begin with. I have the following code:

    #include <Servo.h>
    Servo ESC;     // create servo object to control the ESC
    void setup() {
      delay(1000);
      ESC.attach(9, 1000, 2000); // (pin, min pulse width, max pulse width in microseconds)
      delay(2000);
       ESC.write(180);
      delay(300);
      ESC.write(0);
      delay(2000);

    }

    void loop() {

      ESC.write(1800);    // Send the signal to the ESC
      delay(100);
    }
I have tried various of combinations and non of them seems to work. The motor sometimes beeps, but not in the correct way. I have tried to look for the PPM width (which is 1000 - 2000 μS in the code) but can't seem to find it anywhere. Any suggestions of what I'm doing wrong?

  [1]: http://files.hapo-trade.at/pdf/WASABI ECO(DE+EN).pdf
  [2]: https://mih-toys.de/mediafiles/PDF/Yuki/Regler/WASABI ECO SBEC (DE + EN).pdf

title: PPM of Wasabi Eco

Answers: 0