body:
I am using __ESP-WROOM-32__ (Olimex ESP32-PoE) with __DS3231__. I have used the a patch from [PR on RTClib](https://github.com/adafruit/RTClib/pull/92) to avoid the rollover from the DS3231.

Since the DS3231 RTC provides Unix Epoch Timestamps which have a precision of only seconds, I wish to concatenate the `millis()` to the above mentioned timestamps to provide millisecond precision.

This is critical since I want to store information to InfluxDB from the nodes with ms precision. __For that the timestamps should always be 13 digits__.

##code

    #include <RTClib.h>
    #include <Wire.h>

    // PoE setting for Olimex PoE board

    #define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT
    #define ETH_PHY_POWER 12

    // Pins for I2C on Olimex PoE board
    #define I2C_SDA 13
    #define I2C_SCL 16

    RTC_DS3231 rtc;
    RTC_Millis software_time;

    void setup() {
      // put your setup code here, to run once:
      Wire.begin(I2C_SDA, I2C_SCL, 400000);
      Serial.begin(9600);
      if (!rtc.begin()) {
        Serial.println("No RTC Detected");
      }
      // adjust RTC Time
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
      // adjust software timer
      software_time.adjust(rtc.now());

    }

    void loop() {
      // put your main code here, to run repeatedly:
      DateTime rtc_now_time = rtc.now();
      DateTime software_now_time = software_time.now();
      Serial.println();
      Serial.print("RTC now: "); Serial.print(rtc_now_time.unixtime());
      Serial.println();
      Serial.print("millis: "); Serial.print(millis());
      delay(100);

    }

## Output

    RTC now: 1538502183
    millis: 28
    RTC now: 1538502183
    millis: 128
    RTC now: 1538502183
    millis: 228
    RTC now: 1538502183
    millis: 328
    RTC now: 1538502183
    millis: 428
    RTC now: 1538502183
    millis: 528
    RTC now: 1538502183
    millis: 628
    RTC now: 1538502183
    millis: 728
    RTC now: 1538502183
    millis: 828
    RTC now: 1538502183
    millis: 928
    RTC now: 1538502184
    millis: 1028

I will store the timestamps in `String` so I was thinking of concatenating the `.unixtime()` with `millis()`. However since I want all my timestamps to be of fixed lenght (13) with the increasing `millis` value seems to be difficult because as soon as the number goes more that `999` the a digit increases making the string length 14.

__Side Effect__

if the timestamps for ms do not match length of 13, InfluxDB rejects the data passed through

__Epoch Time__

the output provided above is of 10 digits which is the epoch time since 1970. The precision of the timestamps above is of seconds. If one wants to add milliseconds to it one needs to add 3 more digits behind it. If precision needs to be `microseconds` it should have 6 digits and so on..
One can check the timestamps above on [https://epochconverter.com]

Any suggestions on overcoming this issue ?

title: limit length of the generated timestamp from ESP32 with DS3231 to 13

Answers: 2

body:
the goal is to generate unique and ordered millis part of timestamps in one epoch second.

    unsigned long thisNowMillis;
    uint32_t thisNow;

-

     uint32_t now = rtc_now_time.unixtime();
     if (now != thisNow) {
       thisNow = now;
       thisNowMillis = millis();
     }
     Serial.print("millis: "); Serial.print(millis() - thisNowMillis);

not tested and it will not work for counting intervals between timestamps.

body:
For getting millisecond resolution out of an RTC, I think the only
viable solution is to sync with the 1 Hz square wave output, as
suggested by Jot in a comment. Note that, since you are only counting
seconds and milliseconds, you probably don't care about hours, minutes,
days, months, etc. So you won't use the RTC for timekeeping: only for
providing the 1 Hz reference signal and, maybe, an initial
timestamp at program startup.

Connect the SQW pin of the DS3231 to an interrupt-capable input of your
MCU. Add the following to your `setup()`:

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

    pinMode(SQW_PIN, INPUT_PULLUP);
    rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
    attachInterrupt(digitalPinToInterrupt(SQW_PIN), tick, FALLING);

Use the interrupt routine to both keep track of the total second count
(seconds elapsed since the Unix epoch) and record the `micros()` value
of the last tick:

    volatile uint32_t seconds_since_epoch;
    volatile uint32_t micros_on_tick;

    void tick() {
        seconds_since_epoch++;
        micros_on_tick = micros();
    }

Now you can combine these two values to get a millisecond-resolved
timestamp as follows:

    uint64_t millis_since_epoch() {
        noInterrupts();
        uint32_t seconds = seconds_since_epoch;
        uint32_t microseconds = micros_on_tick;
        interrupts();
        uint32_t extra_micros = micros() - microseconds;
        uint16_t extra_millis = extra_micros / 1000;
        if (extra_millis > 999)
            extra_millis = 999;
        return (uint64_t) seconds * 1000 + extra_millis;
    }

The value returned from this function is the 13-digit number you want,
provided `seconds_since_epoch` has been sensibly initialized.


body:
I have problem because I need to read values and then save them in a .txt file, but Arduino doesn't have a physical connection with my computer. It only has a connection with a computer using Ubuntu without Arduino IDE or other programs. Also, I don't have an ethernet connection and SD card. I need only to have this data stored. The best way is to send them at the end of cycle to a special text file. Has anybody faced that before?

---

I'm thinking about writing a bash script for reading all values sent by serial and then save them, but how do I get that information from serial?

title: Arduino log file directly to file

Answers: 3

body:
The Arduino IDE provides a built-in serial monitor functionality, which emulates a serial port over USB. There are many tutorials available for its use.

However, as best I recall the Arduino serial monitor does not allow you to save a log file. If you don't want to write your own code to do this you can use a different terminal emulator, such as putty.

body: Like what Chris mentioned in the [comment](https://arduino.stackexchange.com/questions/56555/arduino-log-file-directly-to-file#comment119869_56555), you can use pyserial to do it. You can even add timestamp to your data and append them to the same log file.

body:
Any serial terminal emulator application can connect to the Arduino. Select one that has log-to-file capability and open its log file after you've connected it to your Arduino's /dev/tty... device.

Start the Arduino and let it collect & send the data to your terminal program. Close the terminal app's log file (easy step to forget - ask me how I know :) and there's your data.


body:
I am in search for some examples as to how can one use the `AsyncUDPMessage` in an Application for sending out UDP packets to a host with specific IP address and Port number from an __ESP-WROOM-32__ (Olimex ESP32-PoE) module?

The Class for [AsyncUDPMessage in arduino-esp32 library](https://github.com/espressif/arduino-esp32/blob/master/libraries/AsyncUDP/src/AsyncUDP.h#L25) inherits from `Print`.

I want to send sensor measurements to InfluxDB in the Line Protocol (InfluxDB specific).

### Example

     imu,location=front,nodeid=node1 status=0.00,liac_x=-1.18,liac_y=0.02,liac_z=9.63,eul_x=0.00,eul_y=-6.81,eul_z=0.25 1538507409930

The above mentioned example is stored in the form of a `String` and the methods to send information via UDP viz. `send()` `sendTo()` all mention usage of `AsyncUDPMessage` as the first parameter.

### goal
Send the above measurement to the particular Device's IP and port

    udp.sendTo(Message, IPAddress(192,168,3,11), 8089);

I am currently using `broadcastTo(const char * data, port)` menthod to send information the InfluxDB instance.

### Code

    void loop(void) {

      DateTime now_time = rtc.now();

     // create a measurement
      influxMeasurement row("imu");
      row.addTag("location", "front");
      row.addTag("nodeid", "node1");

    // get information from BNO055
      imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
      imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
    //  Serial.print(li_ac.x());
    //  Serial.print(li_ac.y());
      row.addField("status", 0);
      row.addField("liac_x", li_ac.x());
      row.addField("liac_y", li_ac.y());
      row.addField("liac_z", li_ac.z());
      row.addField("eul_x", euler.x());
      row.addField("eul_y", euler.y());
      row.addField("eul_z", euler.z());

      // add timestamp
      row.addTimeStamp_ms(String(now_time.unixtime()) + String(millis()00));

      // print the Line Protocol output
      Serial.println(row.postString());

      // UDP Sending
      char buf[2048]; // make buffer for `broadcastTo()`
      row.postString().toCharArray(buf, sizeof(buf)); // string to char array
      // Serial.println(buf);
      udp.broadcastTo(buf ,8089);

      delay(100);
    }

### method

I create a Line protocol `String`, make a buffer, convert the string to `char []` and send it out.

### Question

1. how do I use `AsyncUDPMessage` so I can pass the string to it directly?

2. I am not sure but will `char buf[2048]` within a `loop` is a good idea as every time a buffer allocation might make the ESP32 run out of memory? And if `AsyncUDPMessage` can avoid this concern?

title: Using AysncUDPMessage for ESP32 to send string data

Answers: 1

body:
Use `udp.print(row.postString().c_str())`

AsyncUDPMessage in AsyncUDP library is only a buffer. It is used only in AsyncUDP send function:

    size_t AsyncUDPPacket::send(AsyncUDPMessage &message)
    {
        return write(message.data(), message.length());
    }


body:
I have a **GSM A6** module, like this [one][1].

I'm going to use an **Arduino Nano** as a *bridge* to communicate with it, I have an external power source (since I read that this module can consume up to 2A at its maximum consumption) (this power supply shares the GND with the module and the Arduino) and I upload the following code in the **Nano**:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11);

    void setup()
    {
      //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(9600);

      //Begin serial communication with Arduino and A6
      mySerial.begin(115200);

      Serial.println("Initializing...");
      delay(1000);

    }

    void loop()
    {
      updateSerial();
    }

    void updateSerial()
    {
      delay(500);
      while (Serial.available())
      {
        mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(mySerial.available())
      {
        Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
      }
    }

I set the **baud rate** at **115200** of my SoftwareSerial port (connected to 10 and 11 pins on the ArduinoNano) because (even if the module says that it has auto-detect speed hability) doesn't work if I set the speed at **9600** (or **any other**), and I modified the SoftwareSerial library for expand the buffer from *64k* to *512k* (trying to solve this problem) following [this page][2] instructions (also: NICE WORK in this page!!!).

And it works ... it works relatively well, I mean:
The **AT** commands to test (according to [the datasheet itself][3]) are **AT** and **ATI** (in one I recieve "*AT /r OK*" and the last one give some usefull information like the OS and other things), and they work, only they do not show me the same answer always, I leave screenshots:

[![ATI command responses][4]][4]
[![AT command responses][5]][5]

As you can see, the answers are not always **exact**, there is some garbage characters, and I **need** them to be **exact**, because my idea is to create a kind of alarm, in which the Arduino (One, Nano or Mega) sends and receives AT commands. I worked with the SIM900 module before and always received the same answer when I sent an AT command.

So... any help?!

  [1]: https://es.aliexpress.com/item/A6-GPRS-Pro-Serial-GPRS-GSM-Module-Core-DIY-Developemnt-Board-Replace-SIM900-NEW/32756244758.html
  [2]: https://lastminuteengineers.com/a6-gsm-gprs-module-arduino-tutorial/
  [3]: https://lastminuteengineers.com/datasheets/A6-A7-A6C-GSM-Module-Datasheet.pdf
  [4]: https://i.stack.imgur.com/OSmPl.jpg
  [5]: https://i.stack.imgur.com/KxQwI.jpg

title: Unexpected result with the GSM module A6

Answers: 1

body:
Apparently the SoftwareSerial library have some limitations, so I change the baudrate communication in the moduel ussing this sentence:

> AT+IPR=9600

And change the code that I upload to the Nano, changing the baudrate speed in the declaration, from:

    mySerial.begin(115200);

to

    mySerial.begin(9600);

And now all is well :D


body:
At the risk of looking like a complete idiot on the internet, I'll preface with this; I'm incredibly new to this. I'm new even to coding, and not sure what questions I should be asking.

I'm trying to run a bipolar motor with an Arduino Uno. I'm fairly sure it should be as simple as set a pin to high, plug the motor into that pin and a ground and it should run. I did this a week ago, and it worked then.

Now I'm trying to essentially run a modified version of blink with this motor running instead of the LED. Running the code with pin 13 as my positive does still flash the LED. If I set my pin to high with the motor, the motor no longer runs. However, It does run when plugged into the 5V and ground. The motor also runs straight off of the two poles of a 9V battery.

I'm unsure what I'm doing wrong. Do I need to step up the voltage of my pins somehow?

Thanks in advance.
-Alec Rosso

Edit 1:Here's the code:

    int motorPin1 = 13;
    int interval= 5000;

    void setup() {
    pinMode(motorPin1, OUTPUT);
    digitalWrite(motorPin1, HIGH);
    }

    void loop() {
    digitalWrite(motorPin1, HIGH);
    delay(interval);
    digitalWrite(motorPin1, LOW);
    delay(interval);
    }

As far as voltage or current specifications, it says DC 12V.

Edit 2: it is not a stepper motor. The serial number is TS-32GZ370-950. It's apparently a "DC geared motor."

Final Edit: I've got it working using an L298. I used a 9-volt battery in addition to my arduino's 5 volts, and everything works like a dream. Thank you for your help.

title: How do I run a bipolar motor with an arduino uno?

Answers: 2

body:
"At the risk of looking like a complete idiot on the internet,"

Without getting personal - you cannot put 10 pounds of potatoes in 5 pounds bag.

AKA you cannot run 12V device with (5V output) Arduino   BECAUSE 12V device / motor requires far more current than Arduino can safely provide.

That is the short version - you probably moved the motor at very slow speed and lucked out before you let the smoke out from the Arduino chip.

body:
Just for your knowledge and future reference - Arduino digital pins can deliver maximum of 40mA each. If you power Arduino by USB, Arduino UNO can draw maximum of 1A, and Nano maximum of 500mA. That is, the 5V pin can deliver that current, not a digital pin. Therefore pin 13(digital pin) can deliver 40mA at 5V, which is 200mW power.

Now, looking at your motor, TS-32GZ370-950,from datasheet at maximum efficiency the current needed is 140mA. Stall current is 480mA, therefore you should be able to deliver close to 480mA @ 12V for the motor to work under all possible loads. Now, that is 5.6W or so. Your 5V pin making the motor work simply meant that the load is low to medium. But you are unable to use the motor's full potential anyway.

Your driver choice is ok, because L298 can deliver up to 2 A, which is fine.
The 9V battery(Alkaline I suppose?) will work, but the lifespan will be very very short. You can look at discharge graphs here : https://www.powerstream.com/9V-Alkaline-tests.htm

It will last about 1 hour at moderate load. Consider using other types of batteries. Your motor accepts voltage up until 24V, so feel free to experiment.

Best of luck!


body:
So Ive setup the emoncms on my server and posted the example power1:100…power3:300 JSON POST and it logged in my INPUTS.
Now Im trying to send data from my arduino and it seems to post fine, but when I go to the INPUTS its not there for some reason.

Here is my code. Im just posting a temperature value to a new node:

    #include "SoftwareSerial.h"
    //For DHT22 Grove Pro
    #include "DHT.h"
    #define DHTPIN A1     // what pin we're connected to
    #define DHTTYPE DHT22   // DHT 22  (AM2302)
    DHT dht(DHTPIN, DHTTYPE);

    String ssid ="myssid";
    String password="mypassword";
    String server = "www.santiapps.com"; // www.example.com
    String uri = "/emoncms/input/post.json";// our example is /esppost.php
    #define EMON_APIKEY F("myapikey")

    byte dat [5];
    String temp ,hum;
    String data;
    char dataString[200];

    SoftwareSerial esp(6, 7);// RX, TX

    void setup() {
      esp.begin(9600);
      Serial.begin(9600);
      Serial.println("setup");
      reset();
      connectWifi();
    }

    void reset() {
      Serial.println("reset");
      esp.println("AT+RST");
      delay(1000);
      if(esp.find("OK") ) Serial.println("Module Reset");
    }

    void connectWifi() {
      Serial.println("connect to wifi");
      String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
      esp.println(cmd);
      delay(400);
      while (esp.available()){
         String inData = esp.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }

      if(esp.find("OK")) {
        Serial.println("Connected!");
      } else {
        connectWifi();
        Serial.println("Cannot connect to wifi"); }
    }

    void start_test () {
      //For DHT22 Grove Pro
      static char outstr1[15];
      static char outstr2[15];
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      dtostrf(t, 8, 2, dataString);
      Serial.println(dataString);
    }
    void loop(){
      Serial.println("loop");
      start_test();
      httppost();
      delay(100000);
    }

    void httppost () {
      esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
      if( esp.find("OK")) {
        Serial.println("TCP connection ready");
      }
      delay(1000);
      String postRequest="POST " + uri + " HTTP/1.0\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + strlen(dataString) + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + "&node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY;
      Serial.println(postRequest);
      String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
      esp.print(sendCmd);
      esp.println(postRequest.length());
      delay(500);
      if(esp.find(">")) {
        Serial.println("Sending..");
        esp.print(postRequest);
        if(esp.find("SEND OK")) {
          Serial.println("Packet sent");
          while (esp.available()) {
            String tmpResp = esp.readString();
            Serial.println(tmpResp);
          }
          // close the connection
          esp.println("AT+CIPCLOSE");
        }
      }
    }

Here is my Serial Monitor:

    setup
    reset
    connect to wifi
    Got reponse from ESP8266: AT+CWsetup
    reset
    Module Reset
    connect to wifi
    Got reponse from ESP8266:
    Got reponse from ESP8266: CLOSED
    Got reponse from ESP8266: WIFI DISCONNECT
    Got reponse from ESP8266: `BԄQR���ȤRN�ɤRN�H��OAT+CWJAP="tha
    connect to wifi
    Got reponse from ESP8266: %J:E
    Got reponse from ESP8266: HըRP=“myssid”,“mypassword”
    Got reponse from ESP8266: busy p…
    connect to wifi
    Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
    Got reponse from ESP8266: busy p…
    Got reponse from ESP8266:
    Got reponse from ESP8266: O
    connect to wifi
    Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
    Got reponse from ESP8266: WIFI DISCONNEC
    Connected!
    Cannot connect to wifi
    Cannot connect to wifi
    Cannot connect to wifi
    loop
    31.00
    TCP connection ready
    POST /emoncms/input/post.json HTTP/1.0
    Host: www.myserver.com
    Accept: /
    Content-Length: 8
    Content-Type: application/x-www-form-urlencoded
        &node=fortnite&data={a:   31.00}&apikey=mykey
        Sending..
        Packet sent

        +IPD,422:HTTP/1.1 200 OK
        Server: nginx
        Date: Tue, 02 Oct 2018 21:38:18 GMT
        Content-Type: application/json
        Connection: close
        X-Powered-By: PHP/5.4.16
        Expires: Thu, 19 Nov 1981 08:52:00 GMT
        Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
        Pragm

Here is a snapshot of the posted data when I used this URL directly in my browser:
[![My emoncms][1]][1]
http://santiapps.com/emoncms/input/post?node=emontx&fulljson={"power1":100,"power2":200,"power3":300}&apikey=mykey

￼=========
Based on jose's suggestion:
=========
I changed this code to:

    void httppost () {
      esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
      if( esp.find("OK")) {
        Serial.println("TCP connection ready");
      }

    //  //CODE USED TO BUILD COMPLETE STRING
      String apiKeyString="apikey=";
      apiKeyString.concat(EMON_APIKEY); //JOIN PARAMETER LITERAL STRING => String Object
      //Serial.println(apiKeyString); //THIS IS NOW A STRING OBJECT
      String nodeData="&node=fortnite&data={\"a\":";
      String combinado=apiKeyString+nodeData; //COMBINE BOTH PREVIOUS STRING OBJECTS
      String finalData=combinado + dataString + "}"; //COMBINE STRING OBJECT WITH CHAR[]
      Serial.println("finalData");
      Serial.println(finalData);
      //unsigned int tamano = strlen(dataString);
    //  char postThis[100] = finalData;
    //  //ADDING THIS TO POSTREQUEST +finalData; && changing length for strlen(finalData)

      delay(1000);
      String postRequest="POST " + uri + " HTTP/1.1\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + finalData.length() + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + finalData;
      Serial.println("postRequest");
      Serial.println(postRequest);
      String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

but now I dont even get the HTTP200OK response.  The result is:

    loop
    31.30
    finalData
    apikey=myKey&node=fortnite&data={"a":31.30}
    postRequest

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

title: HTTP POST/ METHOD to Emoncms doesn't work

Answers: 1

body:
Your Serial monitor output shows the content of the POST as:

`&node=fortnite&data={a:   31.00}&apikey=mykey`

I can't tell if the `&` are actually in your serial monitor, or if your copy/paste did some kind of HTML format attempt, but `&` is wrong and should be `&`

Your JSON data is not proper JSON

`{a:   31.00}`

should be

`{"a": 31.00}`

----------

Strangely, your serial monitor output also writes `Host: www.myserver.com`, which doesn't match your code, where `server` was assigned `www.santiapps.com`, so that makes it difficult to trust that the serial output you show actually came from the code.


body:
I am working with slightly modified example code for the Adafruit FeatherWing DS3231 RTC (real time clock) board. The DS3231 chip itself is from Maxim. Since the cell is described as a "backup battery" a literal interpretation suggests that you don't need the backup battery in order to operate the board if the board itself is powered and you don't mind that the device cannot remember the time when board power is lost. I might be taking the term "backup battery" too literally since it doesn't seem to work.

The Adafruit (Arduino) code:

    > #include <Wire.h>
    > #include "RTClib.h"
    > RTC_DS3231 rtc;
    > void loop()
    >{
    >     rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
    >     DateTime now = rtc.now();
    >     Serial.print(now.year());
    >     Serial.print(" ");
    >     Serial.print(now.month());
    >     Serial.print(" ");
    >     Serial.print(now.day());
    >}

The output is:

    2165 165 165

The Maxim datasheet says this about the VBAT line which is the line between the DS3231 chip and the missing backup battery:

> Backup Power-Supply Input. When using the device with the VBAT input
> as the primary power source, this pin should be decoupled using a
> 0.1μF to 1.0μF low-leakage capacitor. When using the device with the VBAT input as the backup power source, the capacitor is not required.
> If VBAT is not used, connect to ground.

So I connected it to ground and it makes no difference. I can't buy a battery until tomorrow morning. Can somebody please confirm that the backup battery is actually essential. **EDIT**: I installed a battery and it makes no difference.

Aside: A good reason for not having a backup battery if possible is to have fewer user serviceable parts.

title: backup battery for FeatherWing DS3231, RTC

Answers: 3

body:
Your code does not include the line(s) necessary to initialise the rtc.

in setup, you need something like

    rtc.begin()

If you've followed the instructions from the Adafruit website for installing the RTC library:

 - Start Arduino IDE
 - File->Examples->RTClib->ds3231

This will open the RTC usage example.

Else, go to the example on the Adafruit [Github page][1]

look to the setup() code and see how they initialise the device

  [1]: https://github.com/adafruit/RTClib/blob/master/examples/ds3231/ds3231.ino

body:
Assuming your code is in Arduino IDE "loop".
Assuming

> rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
initializes the rtc.

Your code should be continually printing the rtc.adjust value.

Hence move the rtc.djust out of the "loop" and provide some kind of delay , say 1 second, to print rtc every second.
Then we can take a look why your are getting wrong data.

body:
The problem was a bad connection for one of the serial lines.

I found the solution [at this link][1].

The battery is not necessary to make this work.

  [1]: https://forums.adafruit.com/viewtopic.php?f=22&t=109101&sid=ee24e440cc9d4ac75f73157548c855e0


body:
Hi we were asked to program something which when i enter something in the serial monitor it prints Hello world but the catch is it only prints hello world under the conditions that your input in the serial monitor is a 3 bit input and after that i need to have a code which then stops it from printing over and over again.
my only problem is that i don't really know how to count the number of bits of an input and also to stop it from printing continuously.

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

    }

    void loop() {
      String readSerial;
        String input;
        while(Serial.available() > 0){// put your main code here, to run repeatedly:
        delay(2);
      input.concat(String((char)Serial.read()));
      return input;
      }
      Serial.println("HELLO WORLD");
    }

title: Arduino Hello World in Serial monitor

Answers: 2

body:
Assuming that the sketch should print "Hello World" when the input character has 3 bits high. Here are a few different variants of counting the number of bits set in a byte.

    int bits1(int c) {
      int res = 0;
      for (int i = 0; i < 8; i++) {
        if ((1 << i) & c) res = res + 1;
      }
      return (res);
    }

    int bits2(int c) {
      int m = 0x80;
      int res = 0;
      do {
        if (m & c) res++;
      } while (m >>= 1);
      return (res);
    }

    int bits3(int c) {
      int m = 0x80;
      int res = 0;
      do {
        res += (m & c) != 0;
      } while (m >>= 1);
      return (res);
    }

    #define bits4(c) __builtin_popcount(c)

    #define bits bits4

    void setup() {
     Serial.begin(9600);
     while (!Serial);
    }

    void loop() {
      if (Serial.available() > 0) {
        int c = Serial.read();
        if (bits(c) == 3) {
          Serial.print((char) c);
          Serial.print(':');
          Serial.print(c, BIN);
          Serial.println(": Hello World");
        }
      }
    }

body:
Judging from the comments, you lag some basic knowledge. To really learn, what you are supposed to learn in this assignment, you should review your learning material or C/C++ and Arduino Tutorials on the web. Here I will only give you some hints with reasoning, that may help you in solving the assignments task. (Unfortunately it is not really clear, what exactly the task is here)

 - The `Serial` interface of the Arduino (an UART interface) sends the data in bytes, one at a time and one after another (hence the name `serial`). 1 byte is a series of 8 bits, each of them with a value of 1 or 0. Together the 8 bits form a value, that can also be expressed as a decimal value from 0 to 255. For example `01001011` is the binary equivalent of the decimal number 75. (For further explanations google the binary number system) The byte data can also be expressed as characters, as they are defined in the ASCII standard. Every binary value refers to a specific character. This is what happens in the serial monitor of the Arduino IDE. (For more explanations google ASCII)
 - Since the data is send serially, there may appear some delays in the transmission, which are unnoticeable by humans, but the Arduino is fast enough, so that the `Serial.available()` command may return 0, because at that moment a little delay in the transmission occurred. Hence it is important to catch the whole message, before trying to work with it. You can do this by either counting bytes (waiting until at least 3 bytes are available in the buffer) or by marking the end of the message with a special character (for example the newline character '\n'). There are a lot of tutorials on the web how to do both. You can start with [Majenko's blog][1].
 - You can get the number of bytes, that were received, with the return value of `Serial.available()`. It will return 3, when there are 3 ready to be read bytes in the buffer.
 - If you define a variable inside the `void loop()`, it will be thrown away when the function ends and redefined, when the function starts again (In the Arduino world the `void loop()` function is called again and again forever). You will loose all content, that was written to this variable. If you want to persist data over the executions of the `void loop()` function, you can define the variable outside of any function at the top of your program. This variable is then global and will be defined only once at the start of the program and hold for the whole lifetime of the program.
 - As wrote in the comment you should not return a value from a `void` function, since `void` mostly means, that there is no return value. And returning from the `void loop()` function will only restart this function (since we are in the Arduino world).
 - You can ditch the `delay(2)`. There is no need for it. And if it only works with the delay, then something else is not correct and you are just working with the symptoms instead with the real issue.

Also you should not try to build everything on your own and reinvent the wheel. Instead try to look at the examples, that come with the Arduino IDE. For example the `SerialEvent` example, which shows how to receive a serial message (which is ended by a newline character '\n'). Also have a look at the other related examples. If you understand, how they work, you will be able to do the assignment without any problem.

  [1]: https://majenko.co.uk/blog/reading-serial-arduino


body:
I have a [Olimex ESP32-PoE](https://www.olimex.com/Products/IoT/ESP32/ESP32-POE/open-source-hardware) board which has a __ESP-WROOM-32__.

I just found out a strange behaviour for printing floating point numbers on the board.

### Sketch

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      float a=34567891.234;
      float b=2.3456;
      a++;
      Serial.print(a+b, 4);
      Serial.println("");
      delay(1000);
    }

the sketch is extremely simple where I want to add two floating point numbers, one a big and another small to print their addition result upto 4 places.

### Output

on the serial console in the Arduino IDE

    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000
    34567896.0000

Everytime I increment the `float a` using `a++` i expect it to increment by one and print the result but the output above is completely off.

### Without Increment

    void loop() {
      // put your main code here, to run repeatedly:
      float a=34567891.234;
      float b=2.3456;
      Serial.print(a+b, 4);
      Serial.println("");
      delay(1000);

    }

### output

    34567896.0000
    34567896.0000
    34567896.0000

Same output.

Is this Board specific or is the `Serial.print` not supporting float?

title: Two floating point values do not get added and printed on ESP-WROOM-32

Answers: 2

body:
Try doubles instead of floats.

Your initial value, 34567891.234 needs 35 bits of precision to keep track of the decimals, but floats only have 24 bits pf precision. So to have enough precision to keep track of the difference between `34567891.234` and `34567891.234+1`, you need higher precision storage.

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      double a=34567891.234;
      double b=2.3456;
      a++;
      Serial.print(a+b, 4);
      Serial.println("");
      delay(1000);
    }

body:
As already stated in comments and Dave X's answer, floats have a limited
resolution. That resolution is given by the constant `FLT_EPSILON`,
which is the difference between 1 and the smallest float larger than 1.
On any system conformant to IEEE 754, `FLT_EPSILON` is 2−23,
or about 1.19e-7. The implication is that, within the interval
[1, 2], the real numbers that can be exactly represented by floats
are the multiples of `FLT_EPSILON`. The resolution, however, degrades as
you consider larger numbers. Within the interval [2, 4] it is twice
as coarse. Within [4, 8], it's four times as coarse and so on:

    interval     resolution
    ------------------------------------------
    1    – 2     2^-23 ≈ 1.19e-7 (FLT_EPSILON)
    2    – 4     2^-22
    ...
    2^23 – 2^24  1
    2^24 – 2^25  2
    2^25 – 2^26  4
    ...

Your number `a` is just slightly larger than 225. Within this
range, the numerical resolution (aka “ulp”: unit in the last place)
is 4 (last line in the table above). Thus floats in this range can
only represent exact multiples of 4. When you write

    double a=34567891.234;

the compiler replaces this by the closest float, which happens to be
34567892. Same thing for b, but in this case the rounding error is tiny
and inconsequential (about -1.1e-7). When you write

    a++;

you are replacing `a` with the float that is closest to `a+1`, which
happens to be `a` itself. So the instruction has no effect. When yo do

    Serial.print(a+b, 4);

you are computing the float closest to 34567892+2.3456, which is
34567896.

A `double` instead has a resolution `DBL_EPSILON` which is
2−52, or about 2.22e-16. This gives you some precision
margin, but be aware that AVR-based Arduinos do not really support
doubles and treat the `double` keyword as a synonym for `float`. This
may only be an issue if you ever have to move your code to a more
traditional Arduino.


body:
I have a Sigfox Arduino meassuring some sensors, sending it to the cloud and then falling asleep.

    void setup()
    {
    Serial.begin(9600);
      while (!Serial) {};
      if (!SigFox.begin()) {
        Serial.println("Shield error or not present!");
        return;
      }
      SigFox.debug();
      delay(100);
      SigFox.end();
    }

    void loop()
    {
    SigFox.begin();
      delay(100);
      SigFox.status();
      delay(1);
      SigFox.beginPacket();
      SigFox.print("123456789012");
      int ret = SigFox.endPacket(true);

      if (ret > 0) {
        Serial.println("No transmission");
      } else {
        Serial.println("Transmission ok");
      }
      Serial.println();
      SigFox.end();
    LowPower.sleep(20000);
    }

The Issue I have is that the sending to the backend doesn't work when leaving the sigfox.debug() away and that it doesn't wake up from the sleep. It stays in sleep forever.

title: MKR Fox 1200 doesn't wake up from sleep

Answers: 1

body:
Looks like same problem as described in https://forum.arduino.cc/index.php?topic=483636.0
Solution described in that thread:
Add

    LowPower.attachInterruptWakeup(RTC_ALARM_WAKEUP, alarmEvent0, CHANGE);

to setup() and create a dummy function

    void alarmEvent0() {
    }


body:
[![enter image description here][1]][1]They have holes for screw on, on top of the holes on the Arduino itself. Where can I find parts that are compatible with this case/cover? What was the intended use of this case/cover? Thanks.

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

title: How do you use the plastic cover/case that came with Arduino?

Answers: 1

body:
The cover was developed for Arduinos with on-board Ethernet with POE and similar cover has the Ethernet shield with POE. POE - power over Ethernet is 48 V, so it is better to not to touch a soldering point with this voltage.

The arduino.org boards were sold with this cover. Some of them had on-board esp8266 and soldering points leading to esp8266 sensitive pins. Again, better not to touch.

I used the cover to attach the Arduino to a DIN rail over a DIN rail clip.


body:
Working on my first real sketch, so will try to keep this short.  Feel free to ask more info if needed.

To power a flyback transformer I need to apply PWM -to- a PWM signal.  The easiest way to describe this is that while a standard PWM signal is 'on' for some set time, then 'off' for the remainder of the period, I need to send a signal where the 'on' is actually a 14kHz square wave of 50% duty...then pulse this signal ~1 to 100% duty at ~500Hz.

No problem with the 14kHz PWM - I found the PWM.h library and set that up.

But what is the best way to chop that up with a second PWM at, say 500Hz?

With some amount of kludge, can I 'bit bang' it with DO - WHILE?  Will WHILE read a variable outside the loop?  Are there easier ways?

    i=1;
    do {                                //Pulse microsecond 'frames' of high freq signal?
                                        //ie 14kHz carrier PWM'd at 500Hz = 2000 microseconds per 'frame' cycle
                                        //at 50% duty would be 1000 micros high and 1000 micros low

        pwmWrite( outpin, 128 );        //Turn on 14kHz carrier at 50% duty
        delayMicroseconds(1000);        //Delay to generate the 'HIGH' portion of the frame
        pwmWrite( outpin, 0 );          //Turn 14kHz carrier off
        delayMicroseconds(1000);        //Delay to generate the 'LOW' portion of the frame
       } while (i == 1);                //...and keep doing loop while the state is '1' or 'ON'

    delay(1000);                        //?Will this allow the above loop  to repeat while waiting here for 1 second?
    i=0;                                //i != 1, so break out of the while loop above?
                                        //then continue doing other stuff below...

Any help greatly appreciated.

title: PWM of a frequency signal?

Answers: 2

body:
Your 14kHz carrier can be generated by the `tone()` function that is part of the Arduino core. You can then use the [TimerOne](https://github.com/PaulStoffregen/TimerOne) library to toggle the tone on and off.

Here is an untested sample sketch demonstrating the usage:

    #include <TimerOne.h>

    const uint8_t outpin=4;

    void setup() {
      // put your setup code here, to run once:
      pinMode(outpin, OUTPUT);
      Timer1.initialize(1000);  // 1000 microseconds per half-cycle
      Timer1.attachInterrupt(toggleCarrier);
    }

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

    }

    void toggleCarrier() {
      static uint8_t isPlaying;
      if (isPlaying) {
        noTone(outpin);
        isPlaying=0;
      } else {
        tone(outpin, 14000);
        isPlaying=1;
      }
    }

body:
On an Arduino Mega (or an Uno with the ATmega328P replaced with an ATmega328PB, but then you'd have to adapt the code slightly), this can be done via the output compare modulator:

    void setup() {
      // CTC, OC0A toggle on compare match, prescale 1/8
      TCCR0A = _BV(COM0A0)|_BV(WGM01);
      TCCR0B = _BV(CS01);

      // toggle every 35.5 μs at 16 MHz and 1/8 prescale
      OCR0A = 70;

      // phase and frequency correct PWM, TOP is OCR1A, OC1C clear going up and set going down, no prescale
      TCCR1A = _BV(COM1C1)|_BV(WGM10);
      TCCR1B = _BV(WGM13)|_BV(CS10);

      // period of 2 ms at 16 MHz and no prescale
      OCR1A = 16000;

      // on-time of 1 ms at 16 MHz and no prescale
      OCR1C = 8000;

      // no interrupts from the timers
      TIMSK0 = 0;
      TIMSK1 = 0;

      // only output a 1 when both timers are outputting a 1
      PORTB &= ~_BV(PORTB7);

      // halt the timers and reset the prescaler
      GTCCR |= _BV(TSM);
      GTCCR |= _BV(PSRSYNC);

      // reset both timers
      TCNT0 = 0;
      TCNT1 = 0;

      // enable output
      DDRB |= _BV(DDB7);

      // let the timers run
      GTCCR &= ~_BV(TSM);
    }

    void loop() {
      // Just adjust the frequencies and duty cycle as required here.
      // Everything is handled by the hardware and takes effect immediately upon writing to the register.
      // OCR1A: the desired period of the slower signal, in 8ths of microseconds. Can be up to 65535.
      // OCR1C: the desired on-time of the slower signal, in 8ths of microseconds. Can be up to 65535.
      // OCR0A: 1 less than the desired period of the faster signal, in microseconds. Can be up to 255.
      // The on-time of the faster signal is always half of the period.
      // If necessary, you can trade precision for more range for any of the above values by adjusting the prescaler.
    }

With that sketch, pin 13 on the Mega will have the desired waveform. There's two big advantages to this method. First, it doesn't require any CPU resources at all (no loops or interrupts) once it's set up, so you can dedicate all of `loop` to reading the potentiometer and adjusting the duty cycle without worrying about glitches in the output. Second, being entirely hardware controlled means its output will be accurate and perfectly consistent (the 500 Hz component is perfect, and the 14 kHz component is approximately 14085 Hz). The one disadvantage, though, is that `millis` and everything else in the Arduino library that uses timers internally won't work quite right, since we're using the same hardware timers that they depend on.


body:
I recently received two types of Pic32 microcontrollers from Microchip, specifically the `PIC32MX270F256B` and the `PIC32MX230F256B`. I would like to use an Arduino Uno to setup the bootloader and to do all the programming. I found a tool to upload to the board [here](https://code.google.com/archive/p/ardupic32/downloads), but as it is from a 2012 forum [here](https://www.microchip.com/forums/m653443.aspx), I cannot figure out what it is exactly used for. It seems to be able to upload hex files, but in which format and to what is unclear to me. I also found Arduino bootloaders for a similar group of microcontroller [here](https://github.com/chipKIT32/PIC32-avrdude-bootloader), however I cannot tell exactly which version I need, if any, or how to upload it.

Any help on how to use these tools or others would be greatly appreciated as my only experience with Arduino before this is with a simple to program to Arduino Uno.

title: Programing a Bare Pic32

Answers: 1

body:
I am unaware of any Arduino-based tools for installing a bootloader on a PIC32. If you are going to work with PIC32 you really should invest in a proper programmer.

I often use (pretty much throw-away) Chinese clones of the PICkit2 programmer. You can find them on eBay nice and cheap.  Genuine Microchip programmers are pretty expensive, so these cheap clones are quite handy...

You will also want to install the [chipKIT environment](https://chipkit.net/wiki/index.php?title=ChipKIT_core) into the Arduino IDE.

When it comes to the bootloader there are no official boards that use those chips. So you will need to compile your own version, which is not trivial. You will need to install MPLAB-X and the XC32 compiler and create a new profile within the project with the right settings for your board.

And then of course you will have to craft a board configuration for your custom board.

All-in-all it's quite a complex task porting a new board / chip to the chipKIT environment, and you would probably be better off directly using MPLAB-X and programming directly in C (although it's harder to get started in that environment). The PIC32 chips are considerably more complicated to work with than little AVR chips.


body:
I’m trying to send a character message from an arduino uno to an esplora by connecting their usb ports together.  The esplora has a micro usb port, while the uno uses a usb B port.  To hooked them up, I connected a micro usb to usb A cable to a usb A to usb B cable using a female to female usb A connector.  I even hooked up the uno and esplora grounds together.  But the two boards just don’t seem to communicate.  Ordinarily when hooking up the esplora to my computer, the tx light flashes whenever sending the message and the message appears as expected on the serial monitor.  I’ve also tested sending character messages from the computer to the uno and they seem to be read as expected.  But when connecting the esplora to the uno without going through the computer, those tx lights on the esplora do not seem light up at all and the uno rx lights don’t flash either.

Any idea what could be the issue here?

title: Serial communication between an Uno and an Esplora by connecting their usb ports together

Answers: 1

body:
It will not work. USB communication is master/slave. There must be a 'host' and a 'device'. Uno and Esplora are two 'devices'.

Connect the boards over TTL Serial. Wire Rx and TX pins together, TX to RX and RX to TX. And ground of course.

`Serial` on Esplora is the USB interface. In 'core' I see the Esplora has a second serial interface called `Serial1`. According to schematics, the RX and TX pin of `Serial1` on Esplora are on LCD header as DC_LCD (RX) and RESET_LCD (TX). Use this `Serial1` to communicate with Uno.

On Uno side you should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.


body:
I currently have the following code

    server.on("/on", HTTP_POST, [](AsyncWebServerRequest *request) {
        Serial.println("ON hit.");
        String message;
        Serial.println(request->url());
        if (request->hasParam("device"))
        {
            message = request->getParam("device")->value();
        }
        else
        {
            message = " not specified";
        }
        request->send(200, "text/plain", "On, GET: " + message);
        Serial.print("Device ");
        Serial.println(message);
    ....

When sending in a request I get the out put, "Device not specified".

I take a look at the request-params() which gives me back a count of params that are in there and it's returning 1. I write this out:

    server.on("/off", HTTP_POST, [](AsyncWebServerRequest *request) {
        Serial.println("OFF hit.");
        String message;
        int params = request->params();
        Serial.printf("%d params sent in\n", params);
        for (int i = 0; i < params; i++)
        {
            AsyncWebParameter *p = request->getParam(i);
            if (p->isFile())
            {
                Serial.printf("_FILE[%s]: %s, size: %u", p->name().c_str(), p->value().c_str(), p->size());
            }
            else if (p->isPost())
            {
                Serial.printf("_POST[%s]: %s", p->name().c_str(), p->value().c_str());
            }
            else
            {
                Serial.printf("_GET[%s]: %s", p->name().c_str(), p->value().c_str());
            }
        }
        if (request->hasParam("device"))
        {
            message = request->getParam("device")->value();
        }
        else
        {
            message = "not specified";
        }
        request->send(200, "text/plain", "Off, GET: " + message);
        Serial.print("Device ");
        Serial.println(message);

and get the output now of

    1 params sent in
    _POST[device]: puddle
    Device not specified

If I try to do something like request->getParam(0)->value().c_str()
I get a stack dump of a bunch of hex values that I have no idea what it means: but it looks like a big fat error.

title: How do I get the request params from a ESPAsyncWebServer?

Answers: 1

body: For POST request the `hasParam` needs to know if you want to test the url parameters or `x-www-form-urlencoded` parameters in body of the POST request. The second parameter of the `hasParam` is `boolean post` and it has default value `false`. Use `hasParam("device", true)`.


body:
I have to make a school project involving an Arduino Uno with a 2.8" TFT LCD touch screen display. in my project, i have to connect it such that the display is linked to a LED push button that receive inputs and react accordingly, as well as a speaker. However, my TFT LCD display fits perfectly into my Arduino Uno meaning i have no more input slots to connect to my push buttons nor my speaker. initially i found a different TFT display that came with an Arduino Shield that made life simplier however those products were not being shipped to my country:(

i am unable to use an Arduino Mega either since the SD socker in my TFT LCD display does not support the Arduino Mega. i understand in order to have my tft lcd display and my LED buttons and speaker to work i can have 2 Arduino Unos and have them work in Master-Slave however i would still need to have a common ground for both arduinos first and connect them which i am unable to do so since there's simply no way i can fit a jumper cable in there once i place my tft lcd display on the arduino uno. Please help guys:(

title: How to connect 2 Arduino Unos when one has a TFT LCD display attached to it?

Answers: 1

body:
You can put a screw shield between the TFT shield and the Arduino to make access to the unused pins easier.  You can see an example of a board I offer at www.crossroadsfencing.com/BobuinoRev17/ We have been able to ship to any country to date.

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

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


body:
I'm working on a small project. I have 13 leds which need to be controlled individually (turn on or turn off);
Since I don't have 13 pwm pins I used a potentiometer to change the brightness.

This works fine for as long as all of the leds stay in the state they are. But once one led turns on or off it affects the brightness of all other leds.

In the picture below you can see how I did connect them.
I have the analog pins A0, A1, A2 and A3 occupied by some buttons.

Does anyone know how I can dim the leds in a way where the leds themselves don't affect the brightness?

(note: I am a programmer and not so much of an electrical engineer. Code-related answers are (usually) easy for me to understand. ones about the hardware are not.);

[![Current Setup][1]][1]

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

title: Dimming multiple leds with pot meter

Answers: 1

body:
Read the pot with analogRead(). Do not connect it to the LEDs at all, just 5v, Gnd and wiper to A5 (any of the analog input pins).
LEDs just go from resistor on one leg to Gnd on the other (or 5V, depends on whether anode or cathode is connected to the resistor).

Then use software PWM to control the LEDs.

For example:

    byte potPin = A5;
    int potValue;
    byte ledPin[] = {2,3,4,5,6,7,8,9,10,11,12,13,14};
    byte x;

    void setup(){
      for (x=0; x<13; x=x+1){
      pinMode (ledPin[x], OUTPUT);
      }
    }
    void loop(){
    potvalue = analogRead (potPin); // 0 to 1023 value
    for (x = 0; x<13; x=x+1){
      digitalWrite (ledPin[x], HIGH);
      delayMicroseconds(potValue);
      // 0 = max brightness, 1023 (1.023mS) will be dimmest
      // manipulate potValue if 1023 is not dim enough - double it, triple it, etc.
      digitalWrite (ledPin[x], LOW);
      delayMicroseconds(potValue);
      }
     }

From here, you can play with other setups for controlling the brightness.


body:
I know there's quite a few threads with similar answers already, but I hope you won't mind me asking anyways. One thread has what looks like a good solution but it's old and thought it may be better to ask fresh.

I have ten 12v rgb strips with 4 wires each, a 12v power supply and 30 mosfets. I want to control them individually with an Uno.

I'd like to make a wave effect where the strips increase and decrease in brightness at separate times. It's fine if they are all the same color during a wave. Then a wave of a different color.

(1) I'm thinking of trying the approach in [this thread][1] where AMADANON suggests using 3 pins for the color and then each strip gets its own common pin, 13 pins in my case. If I go this route, will I be able to set a color for all strips and a brightness for individual strips? This would let me make the wave effect I'd like.

(2) Alternately I'm thinking of upgrading to a Mega with 54 pins. I assume I could then control each strip individually using 3x10 = 30 pins?

(3) I've read lots of advice on chips to control the strips, but I'm a newbie and would like to keep it as simple as possible (plus delivery to my country takes 3 weeks or more, and I'd like to get started now)

Thanks for any advice!

  [1]: https://arduino.stackexchange.com/questions/8514/how-to-control-19-rgb-led-strips-with-one-arduino

**EDIT:**
(I replied to answers in comments, and I now see I should just instead edit this question. Thanks for your patience with a newbie!)

The mosfets are N-Channel MOSFET 60V 30A.

The led strips are rgb non-addressable with 4 wires, wired on both ends so they can be easily daisy-chained. But in my project the strips are snaking around some tracks and connected them in serial poses a problem. I'd prefer to wire each from only one end.

I think I'll try Gerben's and Andrew's advice about a chip and check out PCA9685 chip module as per Andrew's suggestion. Sounds inexpensive!

chrisl's suggestion for using WS2811 chips sounds easy too and maybe less wiring. In the same vein was an idea from this thread from gre_gor:

https://arduino.stackexchange.com/questions/52685/setting-10-rgb-strips-independently-from-single-arduino

... which talks about chainable STM32 rgb chips, only about 2 bucks on ebay, no mosfets, and pretty efficient.

Thanks for all the advice guys! I'm finishing the box and strips placement now and waiting for my Arduino to arrive which should be any day. This is my first venture into this domain (though I've done plenty of coding and have some experience with electronics).

title: Multiple RGB led strips with Uno - options?

Answers: 4

body:
>I have ten 12v rgb strips with 4 wires each, a 12v power supply and 30 mosfets. I want to control them individually with an Uno.

These sound like non-smart LED strips, where you supply 12V on one pin and then there is a control line for each color. Three resistors for each 3 LEDs, with the groups of 3 wired in parallel on the strip. In which case, 3 MOSFETs per strip to sink current to Gnd sounds good, and you can likely one MOSFET control the same color on multiple strips. Thus you can use the 18 IO of an UNO, leaving D0/D1 free for serial comms with your PC.

Uno has 6 hardware PWM pins for 256 levels of brightness via analogWrite(), and you can create software PWM for the other pins as well.

Which MOSFET do you have?

body:
It sounds to me that you have this kind of tape [leds][1].

If I'm right then your led strip has 4 pins:

1- Blue

2- Green

3- Red

4- GND

With this you can create up to (2^8)*(2^8)*(2^8) = 16,777,216 colors (using PWM or any other dimming technique with the Arduino), **BUT ALWAYS** having the same color in all the led strip. So, *at least as far as I know*, you can not do the effects you want with that strip.

What do you need? You need a "smart" tape, one like [this][2]

As you will see in the name says **addressable**, this means that, for example, you can put the green color on led No1 and the red color on led No2 and so on, and you can move those LEDs making very interesting and cute effects!

Hope you can find this fast explanation helpfull.

  [1]: https://www.amazon.com/LEDwholesalers-16-4ft-Color-Changing-Flexible-2034RGB-R2/dp/B00476B908
  [2]: https://www.amazon.com/ALITOVE-WS2812B-Individually-Addressable-Waterproof/dp/B00ZHB9M6A

body:
As stated before by other users, there are multiple ways to go, but you will have to make compromises.

 - When using an Arduino Mega, you will have to bitbang the PWM signal (directly or by using some timer interrupts), because only 15 of it's pins can be used as native PWM pins.
 - In my opinion it would be the cleanest solution, to use a single driver chip for each LED strip. You can use the WS2811 chip, which is used in most LED strips with individually addressable LEDs. It outputs 3 PWM signals (for red, green and blue) and gets controlled by shifting bits through it's input. Also these chips can be daisy-chained; meaning, that only the first is hooked up to the Arduino and all other chips will be chained together (serial output to serial input). In this solution each chip would controll one of the ten LED stripes (note, that you still have to use a capable MOSFET between WS2811 and strip, since the chip cannot provide enough power for a whole strip), and they would be chained together, effectively only using 1 pin on the Arduino. You can then use librarys like the `Adafruit_Neopixel` to control the strips. Each of your strips then corresponds to 1 LED in the library. You can buy the WS2811 chips at various sources. When googling I found them for 5$ at [Adafruit][1], but you may find them somewhere else for less (This was simply the first shop, where I found them. Didn't searched long). The datasheet (for example [here][2]) contains example applications, which show, how the chips have to be connected. For this solution, you would have to replace the depicted LEDs with MOSFETs, that drive the strips PWM lines.

  [1]: https://www.adafruit.com/product/1378
  [2]: https://cdn-shop.adafruit.com/datasheets/WS2811.pdf

body:
I know what you mean - LED strips with all the same colour at the same time. I've used these and I assume you can wire up the MOSFETs ok. If you don't need individually-addressable LEDs they can still produce some effects.

To control 30 PWM lines, at first I thought using the Mega would solve it, but as someone else reminded us, only 15 are full (hardware) PWM and some would have to be software PWM. This may be good enough, I don't know. More expensively, you could use two MEGAs with one acting as a slave to get 30 full PWM pins.

Another idea would be to use a PCA9685 chip module. I got a couple of these on ebay some while ago (dirt cheap, under £2/$2 ) and each board provides 16 PWM outputs, all controlled from I2C input. They aren't hard to use and have library code for Arduino. Two of these and an UNO would do it or one and a MEGA.


body:
I am wondering if anyone has ever flashed a ATMEGA2560 utilizing a WIZnet 5500? I have looked at [this bootloader package][1] but it only supports the 5100. I may have to do it myself but am a little worried as there doesn't seem to be any support/documentation online and I am not the best programmer. Any help would be greatly appreciated.

  [1]: https://github.com/per1234/Ariadne-Bootloader

title: How to flash an ATMEGA2560 using a WIZnet 5500?

Answers: 1

body:
The latest Ariadne bootloader from 'codebender' is in [his 'personal' GitHub repository][1]. It has W5500 support. Per created [his fork][2] with better documentation and a hardware package earlier. The loathingKernel's repo still lacks good documentation.

I installed Per's Ariadne package over Board Manager and then I replaced the files in Per's package with files from loathingKernel's repo. The I flashed the bootloader to Mega without problems and the Ariadne bootloader worked for me over W5500.

I configured the upload from IDE too.

  [1]: https://github.com/loathingKernel/ariadne-bootloader
  [2]: https://github.com/per1234/Ariadne-Bootloader


body:
This is my enhanced code for a daylight alarm on Arduino UNO with an added MP3-Player.
The device is supposed to sleep all the time except when I hit the play button (then it is supposed to play music) or when the RTC wakes it up, both via interrupt. When the RTC wakes it up it will start its actual daylight alarm routine.

I just implemented the sleep/power-down code and got it working so that I could wake it up and put it to sleep with pins 9 (sleep) and 2 (wake up via interrupt). There was a problem though and I had to change the code.

Apparently while trying to fix it I broke something. The current behiour upon startup is:
1. Go to sleep (correct)
2. When I bridge pin 2 and ground, it wakes up. (correct)
3. When I then bridge pin 9 and ground it goes to sleep. (correct).
4. When I bridge pin 2 and ground again it does not wake up again.

I have changed the code so that in addition to playing music the builtin LED will light up.

 #include <avr/sleep.h>
 /************ init mp3-player ***************/
 #include <SoftwareSerial.h>

 #define ARDUINO_RX 4  //should connect to TX of the Serial MP3 Player module
 #define ARDUINO_TX 5  //connect to RX of the module

 SoftwareSerial mp3(ARDUINO_RX, ARDUINO_TX);
 static int8_t Send_buf[8] = {0}; // Buffer for Send commands.  // BETTER LOCALLY
 String sbyte2hex(uint8_t b);

 #define CMD_SLEEP_MODE    0X0A
 #define CMD_WAKE_UP       0X0B
 #define CMD_SEL_DEV       0X09
 #define CMD_PLAY          0X0D
 #define CMD_STOP_PLAY     0X16  // Stop playing continuously.
 #define CMD_FOLDER_CYCLE  0X17
 #define CMD_SET_DAC       0X1A
 #define DAC_ON            0X00
 #define DAC_OFF           0X01
 #define DEV_TF            0X02

 /**************** init the real time clock ***************/
 #include <Rtc_Pcf8563.h>
 Rtc_Pcf8563 rtc;

 /**************** setup pins & buttons ***************/
 const byte led = 11; // Pin LED is connected to
 const byte sixAmPin = 6; // Pin for set-alarm-to-6am-button
 const byte sevenAmPin = 7; // Pin for set-alarm-to-7am-button
 const byte eightAmPin = 8; // Pin for set-alarm-to-8am-button
 const byte stopPin = 9; // Pin for stop button
 const byte timeResetPin = 10; // Pin for reset-clock-to-9am-button (useful e.g. after battery failure)
 const byte playPin = 2; // Pin for play-music-button (and interrupt!)
 const byte rtcIntPin = 3; // Pin for RTC interrupt

 byte sixAmButton = 1; // State of 6am-set-button
 byte sevenAmButton = 1; // State of 7am-set-button
 byte eightAmButton = 1; // State of 8am-set-button
 byte stopButton = 1; // State of stopButton
 byte timeResetButton = 1; // State of time-set-button
 byte playButton = 1; // State of play-music-button

 byte brightness = 0; // LED brightness
 bool wakeupMode = false;
 unsigned long prevStepTime = millis();
 unsigned long time;

 /*************** Changeable variables here **************/
 byte setHour = 6;
 byte setMin = 30;
 byte fadeDuration = 30; // Duration of fade in minutes (default: 30)
 byte afterBurn = 30; // Keep light on after alarm for this many minutes (default: 30)
 /********************************************************/

 unsigned long keepLight = afterBurn * 60000UL; // Calculate time to keep LED on after fade (in ms)
 int fadeStepLength = fadeDuration * 60000 / 255; // Calculate step duration for increasing LED brightness (in ms) (default: fadeDuration * 60000 / 255)

 void setup() {
   /*DEBUG*/
   pinMode(LED_BUILTIN, OUTPUT);
   digitalWrite(LED_BUILTIN, HIGH);
   /*DEBUG END*/

   // Serial.begin(9600); //uncomment after testing
   mp3.begin(9600);
   delay(500);

   sendCommand(CMD_SEL_DEV, 0, DEV_TF);
   delay(500);

   // declare LED pin to be an output:
   pinMode(led, OUTPUT);

   // declare button pins as inputs:
   pinMode(stopPin, INPUT_PULLUP);
   pinMode(sixAmPin, INPUT_PULLUP);
   pinMode(sevenAmPin, INPUT_PULLUP);
   pinMode(eightAmPin, INPUT_PULLUP);
   pinMode(timeResetPin, INPUT_PULLUP);
   pinMode(playPin, INPUT_PULLUP);
   pinMode(rtcIntPin, INPUT_PULLUP);

   attachInterrupt(digitalPinToInterrupt(playPin), wakeUpPlay, FALLING);
   attachInterrupt(digitalPinToInterrupt(rtcIntPin), wakeAlarm, FALLING);
 }

 void loop() {
   goToSleep();
 }

 void wakeup() {
   // If wake-up-mode is true and brightness < 255, add +1 to brightness every 7 seconds (256 steps)
   wakeupMode = true;
   while (wakeupMode == true) {
  //update clock
  time = millis();

  // If current time is wakeup-time, increase LED brightness slowly over the course of 30 minutes
  if (brightness < 255 ) {
    // Delay brightening in steps. Do only if interval has passed.
    if (time > prevStepTime + fadeStepLength) {
   brightness ++;
   prevStepTime = millis(); // Resets counter to restart interval
    }
   }
  // Turn off light and exit wakupMode x minutes after max brightness
  else if (brightness == 255 && time > prevStepTime + keepLight) {
    brightness = 0;
    wakeupMode = false; // Exit wakeupMode loop
  }
  readButtons(); // Check for button input
  analogWrite(led, brightness); // Set LED brightness accordingly
   }
   goToSleep;
 }

 void readButtons() {
   // Always run this:
   // Check if alarm gets set for 6, 7 or 8am
   sixAmButton = digitalRead(sixAmPin);
   if (sixAmButton == LOW) {
  rtc.setAlarm(5, 30, 99, 99);
   }
   sevenAmButton = digitalRead(sevenAmPin);
   if (sevenAmButton == LOW) {
  rtc.setAlarm(6, 30, 99, 99);
   }
   eightAmButton = digitalRead(eightAmPin);
   if (eightAmButton == LOW) {
  rtc.setAlarm(7, 30, 99, 99);
   }

   // If stopButton is pressed: stop playing music, turn off LED, sleep mp3-player, sleep arduino
   stopButton = digitalRead(stopPin);
   if (stopButton == LOW) {
  wakeupMode = false;
  brightness = 0; // uncomment after testing
  analogWrite(led, brightness); // Set LED brightness accordingly
  sendCommand(CMD_STOP_PLAY);
  sendCommand(CMD_SLEEP_MODE);
  delay(200);
  goToSleep();
   }

   // If timeResetButton is pressed, reset RTC to 9am
   if (timeResetButton == LOW) {
  rtc.setTime(9, 0, 0);
   }

   // If Play music button is pressed, start playing music
   playButton = digitalRead(playPin);
   if (playButton == LOW) {
  playMusic();
  }
 }

 void playMusic(){
   digitalWrite(LED_BUILTIN, HIGH);
   sendCommand(CMD_WAKE_UP);
   delay(200);
   sendCommand(CMD_FOLDER_CYCLE, 1, 0);
   while (1){
  readButtons();
   }
 }

 void wakeUpPlay(){
   sleep_disable();
   detachInterrupt(digitalPinToInterrupt(playPin));
   detachInterrupt(digitalPinToInterrupt(rtcIntPin));
   playMusic();
 }

 void wakeAlarm(){
   sleep_disable();
   detachInterrupt(digitalPinToInterrupt(playPin));
   detachInterrupt(digitalPinToInterrupt(rtcIntPin));
   wakeup();
 }

 void goToSleep() {
   sleep_enable();
   attachInterrupt(digitalPinToInterrupt(playPin), wakeUpPlay, FALLING);
   attachInterrupt(digitalPinToInterrupt(rtcIntPin), wakeAlarm, FALLING);
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);
   digitalWrite(LED_BUILTIN, LOW);
   delay(500);
   sleep_cpu();
 }

 /**************************/
 /** Stuff for MP3 player **/
 /**************************/

 /********************************************************************************/
 /*Function: Send command to the MP3                                             */
 /*Parameter: byte command                                                       */
 /*Parameter: byte dat1 parameter for the command                                */
 /*Parameter: byte dat2 parameter for the command                                */

 void sendCommand(byte command){
   sendCommand(command, 0, 0);
 }

 void sendCommand(byte command, byte dat1, byte dat2){
   delay(20);
   Send_buf[0] = 0x7E;    //
   Send_buf[1] = 0xFF;    //
   Send_buf[2] = 0x06;    // Len
   Send_buf[3] = command; //
   Send_buf[4] = 0x01;    // 0x00 NO, 0x01 feedback
   Send_buf[5] = dat1;    // datah
   Send_buf[6] = dat2;    // datal
   Send_buf[7] = 0xEF;    //
   Serial.print("Sending: ");
   for (uint8_t i = 0; i < 8; i++)
   {
  mp3.write(Send_buf[i]) ;
  Serial.print(sbyte2hex(Send_buf[i]));
   }
   Serial.println();
 }

 /********************************************************************************/
 /*Function: sbyte2hex. Returns a byte data in HEX format.                       */
 /*Parameter:- uint8_t b. Byte to convert to HEX.                                */
 /*Return: String                                                                */

 String sbyte2hex(uint8_t b)
 {
   String shex;

   shex = "0X";

   if (b < 16) shex += "0";
   shex += String(b, HEX);
   shex += " ";
   return shex;
 }

 /********************************************************************************/
 /*Function: shex2int. Returns a int from an HEX string.                         */
 /*Parameter: s. char *s to convert to HEX.                                      */
 /*Parameter: n. char *s' length.                                                */
 /*Return: int                                                                   */

 int shex2int(char *s, int n){
   int r = 0;
   for (int i=0; i<n; i++){
   if(s[i]>='0' && s[i]<='9'){
    r *= 16;
    r +=s[i]-'0';
   }else if(s[i]>='A' && s[i]<='F'){
    r *= 16;
    r += (s[i] - 'A') + 10;
   }
   }
   return r;
 }

I can only imagine that the problem lies in the way I send Arduino to sleep when playing music (i.e. the way I call goToSleep(); from the wakeUpPlay()-class). Waking up from sleep does work when sleep was induced from the main loop (apparently). Do you have any idea what is wrong?
(I thought about reducing my code to the bare minimum so it is less confusing for you - but then I'd probably change too much to find the bug).

title: Why can I wake Arduino only once with this code?

Answers: 1

body:
All your music playing code is inside a interrupt. While an interrupt is running all other interrupts are disabled. It's advised to keeps interrupt routines as short as possible.

You could have the interrupt routine set a boolean variable. Then in the `loop` function read that variable and call the play-music function.

    volatile boolean startPlayback = false;

    ...

    void wakeUpPlay(){
      startPlayback = true;
      sleep_disable();
      detachInterrupt(digitalPinToInterrupt(playPin));
      detachInterrupt(digitalPinToInterrupt(rtcIntPin));
    }

    ...

    void loop() {
      goToSleep();
      if( startPlayback )
      {
        startPlayback = false;
        playMusic();
      }
    }

Do something similar with wakeAlarm.


body:
I have three different devices, none of them gets recognized on my new Thinkpad L380 running Windows 10:

 - Arduino Nano Clone with CH340G chip (USB2Serial)
 - NodeMCU (Lolin V3) with CH 340G chip (USB2Serial)
 - NodeMCU (ESP-WROOM-32) with CP2102 chip (USB2UART)

All three of them are recognized properly both on my desktop computer running Windows 10 (on USB 2.0 ports) as well as on my other laptop (Acer Switch Alpha 12, Win10, USB 3.0 port).

But even after hours of trying I was not able to connect those devices to my Thinkpad.
Things I've tried so far:

 - Of course, simply installing the Arduino IDE and try plug'n'play
 - Downloading and installing the CH340G driver from the official website
 - Disabling Secure Boot, enabling testsigning mode and reinstalling the CH340G driver
 - For the CP2102 device I only tried installing the driver under "normal" Windows (e.g. no testsigning enabled) since it also worked that way on my desktop computer

I have to admit that it's been a while since I set up the drivers on my other laptop and desktop computer, but I cannot remember that there was anything unusual I had to do back then.

Does anybody else know about problems regarding Thinkpad laptops? At first I thought USB 3.0 might be the problem, but the Acer laptop works just fine with the USB 3.0 port.

**Update**

Somehow the laptop now at least recognizes the Arduino Nano clone in the device manager and I can choose the COM port in the Arduino IDE. I can't tell what made the difference. All I did was to plug in a dongle for a wireless mouse in the USB ports to verify that they are working with "normal" devices and afterwards the Nano was recognized at least with a yellow "!" in the device manager. I then was able to uninstall the CH340 drivers and reinstall them. The device manager now displays the Nano as correctly installed.

But uploading a sketch fails. It outputs the errors:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x0a
    avrdude: ser_send(): write error: sorry no info avail
    avrdude: ser_recv(): read error: Access denied

The RX LED is faintly blinking in red at the beginning of the process, then the upload seems to get stuck until the error messages are displayed.

The NodeMCU Lolin V3 with the same CH340 chip is still not recognized, though.

Serial communication (with the Serial monitor of the Arduino IDE) is now possible. I uploaded the "ASCIITable" example using my Desktop PC, connected the Arduino to the ThinkPad and could successfully read the output over the serial interface.

title: CH340G and CP2102 devices not recognized with Thinkpad L380

Answers: 1

body:
I recently bought a cheap USB 2.o hub.
Turns out that the CH340G devices are recognised if I plug them in the hub rather than in the laptop directly. Maybe this helps somebody else who is searching for a solution, even though I can't explain why the hub is making a difference.


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

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

It says that it is a pro micro, but I have searched the arduino website and i cannot find something that looks like this or is called this.

title: I do not know what the board is. Can someone please help

Answers: 1

body:
An Arduino compatible board don't have to look like one in Arduino web site.
There are many clones and custom boards are available.
Since it says pro micro, choose `Pro micro` from bard option and try uploading some code.


body:
I've noticed that when I'm sending serial data to my computer's serial monitor, the tx light only lights up when the serial monitor is open.  When I close the monitor, it seems to stop sending data.  Is this a normal thing?

The reason I ask is because I'm really trying to send data from my esplora to an uno, and I notice that despite (1) having the grounds of both arduinos connected and (2) connecting the esplora's tx pin (reset_lcd) to the uno's rx pin (pin 0) and the esplora's rx pin (dc_lcd) to the uno's tx pin (pin 1), the tx light on the esplora and the rx pin on the uno don't light up at all.

What could be the problem?

title: Why does my Esplora only send serial data when the serial monitor is on?

Answers: 1

body:
Esplora is based on a MCU with native USB. The native USB reports connected only when it really connects. You have in setup() a while loop until the USB Serial is valid. The skech waits there for connection. Comment out the while (Serial) loop.

The TX and RX LEDs of Esplora are connected to the native USB port Serial interface. They will not light for the Serial1 interface.

You should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.


body:
I'm working on a project that will essentially become an oscilloscope in the long run. I am following [this][1] guide. My code is uploaded [here][2] for more reference.

In my .ino file I have called functions to set up register such that I have a timer ISR called at a frequency of 100 KHz, and an ADC clock rate of 2 MHz. The ADC is also set so that the result is left shifted so ADCH contains an 8-bit result. In a separate .h file I have an ADC ISR that looks like this:

    ISR(ADC_vect)
    {
      // Read 8-bit conversion result from ADCH.
      uint8_t byte0 = ADCL;
      uint8_t byte1 = ADCH;

      data_byte = byte1;
      flag = true;
    }

The loop() function is the following:

    void loop()
    {
      if (flag == true)
      {
        //Serial.println("ISR HIT");
        Serial.println(data_byte);
        flag = false;
      }
    }

So, when the ISR is called the flag is set to true, and in the loop() function I am notified with an "ISR HIT" printed on the serial monitor, this operation is successful.

However, I also have a volatile global variable in my .ino function called **data_byte** (also declared as an extern in the .h file) that I set byte1 to. When byte1 is printed to the serial monitor the result is:

    255
    255
    255

**Any ideas on why the value of ADCH is stuck at 255?** My hardware is simply a light sensor connected to pin A0, 3.3 V, and GND.

  [1]: http://openlabtools.eng.cam.ac.uk/Resources/Datalog/RPi_Arduino/
  [2]: https://github.com/irfan-hossain/DAQ

title: Arduino Uno ADCH register stuck at 255 when read from ISR

Answers: 1

body:
It would seem the problem lies here:

    // Set Register to all zeros since Vref
    // will be set to internal voltge and
    // analog pin A0 is used.
    ADMUX = 0x00;

According to the datasheet, the bits `REFS[1:0]` of the `ADMUX` register
select the voltage reference as:

* 00: AREF, Internal V ref turned off
* 01: AVCC with external capacitor at AREF pin
* 10: Reserved
* 11: Internal 1.1V Voltage Reference with external capacitor at AREF pin

Settings those bits to zero means that you are now supposed to provide
your own reference through the AREF pin. If you want to use the 5 V
supply as a reference, you should set them to 01. This is confirmed by
the block schematic. Here is the part of that schematic relative to the
reference voltage:

[![partial schematic of the ADC][1]][1]

When `REFS0` is zero, the highlighted transistor does not conduct, hence
the only way to provide a voltage reference is through the AREF pin.

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


body:
    include SPI.h
    include Ethernet.h
    include Modbus.h
    include ModbusIP.h

    //Modbus Registers Offsets (0-9999)
    const int SENSOR_IREG = 100;
    //Used Pins
    const int sensorPin = A0;

    //ModbusIP object
    ModbusIP mb;

    long ts;

    // Set Port to 502
    EthernetServer server = EthernetServer(502);

    void setup() {
      //Assign the modbus device ID.
      regBank.setId(1);

        byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

        byte ip[] = { 192, 168, 1, 177 };

        mb.config(mac, ip);

        // Add SENSOR_IREG register - Use addIreg() for analog Inputs
        mb.addIreg(SENSOR_IREG);

        ts = millis();

    }

    void loop() {

       //Call once inside loop() - all magic here
       mb.task();

       if (millis() > ts + 2000) {
           ts = millis();

           mb.Ireg(SENSOR_IREG, analogRead(sensorPin));
       }
    }

I am trying to read data from the first analog pin through ModbusTCP using SimplyModbusTCP but I keep getting errors when I poll my Arduino. I am using an Arduino UNO with a Ethernet Shield W5100 and [Modbus Library][1]. I am request data from Ip address 192.168.1.177 Port:502 Slave:1 and Function Code:03. The error I get is "Error 66 occurred at TCP Read in SMT8.0.vi. LabVIEW: The network connection was closed by the peer."

  [1]: https://github.com/andresarmento/modbus-arduino

title: Modbus IP with Simply Modbus TCP

Answers: 2

body:
You should not create the Ethernet server. The library creates the server and your server takes the port first.

Modbus function code to read Input registers is 04.

body:
Looks like SimplyModbus was the problem, used [Modbus poll][1] and was able to read data.

  [1]: https://www.modbustools.com/download.html


body:
I have added static variables to this code and instead of getting repeated notes whilst dwelling on green, I get a single note instead. This is what I wanted. However, my loop isn't allowing for a new note to be fired either when the sensor returns to a green colour. I'm afraid I'm not getting the hang of this!

      /*
      // TCS230 color recognition sensor
      // Sensor connection pins to Arduino are shown in comments

      Color Sensor      Arduino
      -----------      --------
      VCC               5V
      GND               GND
      s0                8
      s1                9
      s2                12
      s3                11
      OUT               10
      OE                GND
    */
    #include <MIDI.h>

    const int s0 = 8;
    const int s1 = 9;
    const int s2 = 12;
    const int s3 = 11;
    const int out = 10;

    // LED pins connected to Arduino
    int redLed = 5;
    int greenLed = 6;
    int blueLed = 7;
    // Variables
    int red = 0;
    int green = 0;
    int blue = 0;
    int indeks = 0;
    const int rgbr = 7;
    const int rgbg = 6;
    const int rgbb = 5;

    MIDI_CREATE_DEFAULT_INSTANCE();

    void setup()
    {
      MIDI.begin();                      // Launch MIDI and listen to channel 4

      Serial.begin(9600);
      pinMode(s0, OUTPUT);
      pinMode(rgbr, OUTPUT);
      pinMode(rgbg, OUTPUT);
      pinMode(rgbb, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);
      pinMode(out, INPUT);
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(blueLed, OUTPUT);
      digitalWrite(s0, HIGH);
      digitalWrite(s1, HIGH);
    }

    void loop()
    {
      color();

      int tmpr = (((20 - red) - 10) * 30); //int tmpr=(((20-red)-10)*30);
      int tmpg = (((20 - green) - 10) * 30); //int tmpg=(((20-green)-10)*30);
      int tmpb = (((20 - blue) - 10) * 30); //  int tmpb=(((20-blue)-10)*30);

      if (tmpr < 0)
        tmpr = 0;

      if (tmpg < 0)
        tmpg = 0;

      if (tmpb < 0)
        tmpb = 0;

      if (tmpg > tmpb && tmpg > tmpr)
      { tmpb = 0;
        tmpr = 0;
      }
      analogWrite(rgbr, tmpr );
      analogWrite(rgbg, tmpg );
      analogWrite(rgbb, tmpb );

      static uint8_t noteOn;

      if (tmpg > 149 && tmpg < 151) {
        static uint8_t noteOn = 0;
        if (!noteOn) {
          noteOn = true;
          MIDI.sendNoteOn(79, 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
          MIDI.sendControlChange(64, 127, 1);

        }
      }
      else {
        static uint8_t noteOn = 1;
        if (noteOn) {
          noteOn = false;
          MIDI.sendNoteOff(79, 0, 1);     // Stop the note
          MIDI.sendControlChange(64, 0, 1);

        }
      }
    }

    void color()
    {
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
      //count OUT, pRed, RED

      red = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);

      digitalWrite(s3, HIGH);
      //count OUT, pBLUE, BLUE
      blue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);
      digitalWrite(s2, HIGH);
      //count OUT, pGreen, GREEN
      green = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);

    }

title: State change detection with a colour sensor

Answers: 1

body:
Because the MIDI library for Arduino does not keep track of which notes are on or off, you will have to do that yourself.

Add a `static` variable called `noteOn` that will hold a `0` or a `1`, keeping track of whether you have a note turned on or not.

Then, when your `loop()` determines that it should turn on a note, it first checks if a note is already on. If the note is not already on (`!noteOn`), then send note on command, and set `noteOn=true` (same as `noteOn=1`) so that next time around, you won't send the note on command again.

    void loop()
    {
      static uint8_t noteOn;

      [...]

      if (tmpg > 149 && tmpg < 151) {
        if (!noteOn) {
          noteOn = true;
          MIDI.sendNoteOn(79, 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
          MIDI.sendControlChange(64, 127, 1);
        }
      } else {
        if (noteOn) {
          noteOn = false;
          MIDI.sendNoteOff(79, 0, 1);     // Stop the note
          MIDI.sendControlChange(64, 0, 1);
        }
      }
    }


body:
I made a custom ATmega32u4 board for my project. Components came from clone of Arduino Pro Micro (with bootloader and code which I uploaded) from AliExpress. I soldered everything in to my board according to my schematic but the board doesn't work. I don't have any signal from that.

https://i.stack.imgur.com/qskHc.jpg

[![Schematic][1]][1]

  [1]: https://i.stack.imgur.com/OxT47.png "Schematic"

title: Atmega32u4 issue

Answers: 1

body:
You have an error in your schematic.

You have used the net name VCC for your main power circuit. However your USB incoming power is labelled as +5V.

That means you have two separate nets - +5V with power on it, and VCC isolated from it entirely.

You need to connect those two nets together - name them both VCC or both +5V so they form a single net (easiest is to adopt VCC since you use that on other connections too).

To "fix" your current PCB you could connect a small wire from the cathode of D2 to pin 44 AVCC on the main chip which will bridge the two nets together.


body:
I'm beginning in Arduino I do not understand what the error means. Please tell me where I can find the resources to understand it and allow the code to compile.

    #include <RCSwitch.h>
    #include <Ultrasonic.h>

    Ultrasonic ultrasonic(11,10);
    RCSwitch mySwitch = RCSwitch();

    int i;

    void setup() {
        mySwitch.enableTransmit(4);
    }

    void loop() {
        i = ultrasonic.Ranging(CM);
        mySwitch.send(i, 24);
        delay(100);
    }

> Arduino: 1.8.7 (Windows 7), Board: "Arduino/Genuino Uno"
>
> 433mhz-lcd-water-level-transmitter:2:24: error: Ultrasonic.h: No such
> file or directory
>
> compilation terminated.
>
> exit status 1 Ultrasonic.h: No such file or directory
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

title: (ultrasonic sensor code : No such file or directory)

Answers: 3

body:
It means what it says:

> Ultrasonic.h: No such file or directory

The file `Ultrasonic.h` can't be found.

Anything in your code that starts `#include...` is usually a *library*. These are third party pieces of software that you have to obtain and install into the relevant location (See [Installing Additional Arduino Libraries](https://www.arduino.cc/en/Guide/Libraries)).

Some libraries are bundled with the IDE, and some are available through the "library manager" in the IDE. However most aren't, and you will have to get used to finding those libraries and installing them.

The location you got your example code from will most likely link you to where to find the relevant libraries to get the code working.

body:
This kind of error means that the Arduino IDE (assuming that is what your are using) did not find 'Ultrasonic.h' in a folder named 'libraries' within your Arduino sketch folder. (Some libraries are contained in other places within the IDE's executable, but putting your additional libraries in '.../libraries' keeps everything easy to find and maintain).

Go to `File | Preferences` (in Windows or Linux) or `Arduino | Preferences` (Mac). The top box in that dialog is the path to your sketch folder. That folder should contain one called 'libraries'.

The libraries folder should have a folder for each library, so in this case, there should be a folder named 'Ultrasonic', containing files 'Ultrasonic.h' and 'Ultrasonic.cpp'. There may be other items in there as well, perhaps an Examples folder, a 'keywords.txt' file (helps the IDE with syntax coloring), a text file with release notes, etc., but the important structure is

    [path/to/your/sketch/folder]
         libraries
             Ultrasonic
                  Ultrasonic.h
                  Ultrasonic.cpp
             someotherlibrary
                  someotherlibrary.h

etc.

body:
i found another library ultrasonic solve my first problem(Ultrasonic.h: No such file or directory) but then have another error... it say(class Ultrasonic' has no member named 'Ranging')....
in this time i changed some of my code and now working good

my code after solve

    #include <RCSwitch.h>
    #include <Ultrasonic.h>

    Ultrasonic ultrasonic(11,10); // (Trig PIN,Echo PIN)
    RCSwitch mySwitch = RCSwitch();

    int i;

    void setup() {
      mySwitch.enableTransmit(4);
    }

    void loop() {
    Ultrasonic ultrasonic(11,10,3000); // (Trig PIN,Echo PIN, Max.TimeOut in µsec )
      mySwitch.send(3000 ,24);
      delay(100);
    }


body:
Problem with my arduino is when I check voltage of 3.3 volt pin using multimeter , voltage varries a lot from 1.5v upto 5v. Due to which esp8266 wifi module connected to this 3.3v pin gets very hot.

Is the arduino is faulty or can me made to produce steady 3.3 v . Kindly suggest .

Thank you.

title: Fluctuating voltage coming out of arduino uno 3.3 output pin

Answers: 2

body:
I am sure the voltage is stable without load. Voltage fluctuations are sign of not enough current available.

If you look into the Uno specs, you will find out that the 3.3 V pin can supply max 50 mA.

If you look into esp8266 datasheet in power section you will find out that it needs far more current than 50 mA.

Power the esp8266 from 5V pin over a voltage converter.

body:
The Arduino cannot power an ESP8266 directly.

A genuine Arduino has the LP2985 which can provide up to 150mA (about a quarter of what you need for an ESP8266) and will go into "thermal shutdown" when it gets overloaded.

However, a Chinese (or other cheap) clone could use something even less powerful, with or without thermal protection.  In this case overloading the 3.3V pin could irreversibly damage the 3.3V regulator (which may be internal to the USB chip, killing the USB connection in the process) and thus render it unable to regulate the voltage down to 3.3V properly.

If the latter is the case then it is also possible that the higher voltage passed through by the failed regulator could have also killed the ESP8266 chip.


body: If I use an Arduino board to bootload a new chip, is it still possible to use the microcontroller on the board for another project, or it will only be for bootloading new chips.

title: Need help on Arduino as ISP

Answers: 1

body:
There are more ways to flash a bootloader to new AVR chip. To which you refer? If you replace the chip on Uno to burn a bootloader to it with a programmer, then it is very unclear what you are asking, because the original chip is not involved in this process.

If you ask about ArduinoISP sketch, then simply it is a sketch. You upload it as any other sketch and replace it with any other sketch.


body:
My project has my Arduino controlling 10 led strips. I'm going with a plan by @gre_gor that is posted here: https://arduino.stackexchange.com/questions/52685/setting-10-rgb-strips-independently-from-single-arduino
...where each strip is controlled by an STM32 driver.

I'm packing all electronics into a tight space and will need to have the power adapter external with just the cable coming in.

I need power both to the arduino and directly to the stm32's.

Question: can I simply split the 12V power cable to send power to both the led strips and the arduino? Or is there something I should worry about?

title: Powering Arduino and LED strips from one adapter

Answers: 1

body:
Powering an Arduino and LED strips is no different to powering your TV, satellite receiver, DVD player, etc all from one socket in the wall.

Connect all the grounds (-) together, and connect all the powers (+) together.

All you need to worry about is that the total current draw of all the devices combined doesn't exceed the amount of current that the power supply can provide (oh, and that they all operate at the same voltage, of course).


body:
I have two MCP2515 stand-alone CAN controllers with SPI interface, two TJA1042 CAN transceivers and two Arduino Uno boards. As you may know TJA1042 have two operational modes:

1. Sleep mode

2. Normal mode.

If I want to change the mode of operation of one transceiver from sleep mode to normal mode(wake it up), I should send a wake up pattern waves from the other transceiver which is in normal mode. for example one of the wake up patterns is: 5.5 µS low, 5.5 µS high and again 5.5 µS low. Now I don't know how to send these patterns with Arduino because MCP2515 is SPI interface.

I use this library: [MCP_CAN][1]

  [1]: https://github.com/Seeed-Studio/CAN_BUS_Shield/commit/15c6bfb80a50c924a9c708117a66a66b54af5370

title: Change operational mode of CAN transceiver

Answers: 1

body:
Transmitting this "wake signal" does not "wake" the transceiver.  What it's actually doing is the transceiver, when in "standby" mode, only allows through signals that have a dominant or recessive state that is longer than the filter time (5.5µs). Any transitions in the bus after a stable period of 5.5µs or more will get passed through.

The transceiver does *not* enter "normal" mode at that point. It is down to the CAN device to activate the transceiver through setting the STB pin LOW.

> When pin RXD goes LOW to signal a wake-up request, a transition to Normal mode will not be triggered until STB is forced LOW.

Exactly *what* you send is of no consequence to the transceiver - only whether it has D and R states that are longer than 5.5µS.  It's up to the CAN device to interpret them and know if it should wake up the transceiver and place it in NORMAL mode.

And the MCP2515 also doesn't care what it receives.  When the WAKEIE bit is set it will cause the MCP2515 itself to wake from its sleep mode when *anything* is received - at which point it signals to the Arduino through its INT pin that it's woken up.

However your chosen library has no ability included in it to control the WAKEIE bit of MCP_CANINTF - only the TXxIF bits are supported.  So you will have to expand the library to provide that facility.

The general idea of operation is:

* The transceiver lets through a "slow" signal (like transmitting 0b00110011)
* The MCP2515 receives "something"
* INT pin goes LOW and the Arduino reacts to it
* The Arduino drives STB LOW and reception can proceed normally.

Note that it is the Arduino that will be controlling STB, not the MCP2515.