body:
So, I'm creating this project for school. It's a simple robot with Arduino MEGA 2560 and basically, I create a digital map, feed it into the Arduino program and then the robot can drive. However, I've run into some problems while trying to implement my idea. Parsing errors mostly. And I want to know if there is another and different approach.

So, basically at the moment, this is how my digital map works:

Using C# and Visual Studio IDE I've created a program with which I can create the map. Basically, I create connections(lines/roads) and the connection has a starting and end point, a median point and a label(what it is). So, each connection info token is something like this:

`"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"
`
`"Connection[x1: 13, y1: 0|x2: 13, y2: 28|xm: 13, ym: 14|label: library]"`

Now, I have figured out a way to import this information into Arduino, and I've stored the information into a class object I created. Now, the difficulty I'm experiencing is how am I going to drive the robot from one point to another, store the robot's position and go to any point in the map when asked to.

**Edit:**

As for the implementation and storage of the map, it's like this:

So, I have a class Vertex. It basically the equivalent of a point and store (x, y) values.
<!-- language-all: lang-cpp -->

    class Vertex {
      public:
        int x;
        int y;

        Vertex(int _x, int _y) {
           x = _x;
           y = _y;
        }
    };

Then there's the connection class. It stores the starting vertex, the end vertex, the median vertex and the label(string). It's like this:

    class Connection {
      Vertex v1();
      Vertex v2();
      Vertex median();
      String label;

      public:
        Connection(Vertex _v1, Vertex _v2, Vertex _median, String _label) {
            v1() =  Vertex(_v1.x, _v1.y);
            v2() =  Vertex(_v2.x, _v2.y);
            median() = Vertex(_median.x, _median.y);
            String label = _label;
      }
    };

And, finally, there's the map class where the user passes in the info tokens produced by my map creating application made in Visual Studio and it works like this:

    #include "Connection.h"

    class Map {
      public:
        Map(string infoTokens[]) {
          //I import the info tokens here.
        }

        void drawMap(MCUFRIEND_kbv tft, String ) {
          //This is a totally different function, it is just for drawing the map
            on top of the TFT screen that I have on my robot.
        }

        void driveTo(Vertex rP, String destinationLabel) {
          //This is where I drive my robot when the user requests to go to a
            destination and provides the label.
        }
    };

As for the importing of the info tokens(the map information) I just do some `String Manipulation` on, for example, this
`"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"`
and get back all the info in the required data types. As for the importing it doesn't really change anything because I have tested my function(not present here) a lot of times and it works brilliantly. My question is how to use that information to hopefully drive the robot.

title: Built-In Digital Map for Robot Driving

Answers: 1

body:
You were able to create a custom data structure from your string, but it seems, that the connections, that are stored in the `Map` class, are not connected. So the map does not really represent the structure of the "street" net. I would propose a different approach:

Instead of defining connections you can define the nodes of your net (where 2 or more streets meet). For each node you save the position (x, y) (or an instance of your vertex class), a label (like "library") and an array of pointers to other node objects. In code this may look like this (I left the methods out):

    class Node {
        Vertex pos;
        char label[25];
        Node *connections[6];
    }

---

Excursion: If you don't know, what pointers are in C/C++, here a short introduction. You should definitely read more about it on the web.

A pointer variable contains the address of another variable in the RAM. You can change this address and let the pointer point to another variable. A variable is marked as pointer with a `*` at the declaration. You can get the address of a variable (to set the pointer to this variable) through the `&` operator: `pointer = &variable` . If you dereference a pointer (by writing a `*` before the pointer name), you can work with the value, that the pointer points to. Each pointer variable has a type. It is the type of the object, that it points to. The pointer declaration `int *var` let's `var` point to `int` variables. If the type is a `class` or `struct` and you want to access members of the target (where it points to), you can use the shortened version `pointer->member`.

---

You define each node and add pointers to other nodes to represent connections. To traverse through the map, you need a start node. You save the address of the current node in a pointer. Then you can use it to access the connections of the current node. To actually go to the next node, you would set your pointer to the value saved in one of the `connections` elements, because that are pointers to the connected nodes.

The robot can then be moved along the straight lines between 2 nodes. When you want to also have non-straight, you can also do that by defining a middle point. You just to define the geometrical form, that the line should take.

The `Map` class can contain an array of `Nodes`. You can loop through all nodes in the array, if you need to, or you can traverse through the net by using the pointers.

---

The actual algorithm to find the path with the smallest travel distance is a big out of scope here. Doing that efficiently can be a complex task. You can research these algorithms on the web. The easiest way is to test all different paths in your program (without actually moving the robot), save the needed distance for each path and then choose the path based on that. You would need to write a termination condition, so that no connected will be taken twice on the same path (which would mean some kind of loop). Also keep in mind, that this will need more and more computation time, as your net grows. If it stays small and you don't need very fast computation, it might stay sufficient. If your implementation is recursive, you also have to consider, that each recursion takes up memory on the stack. You don't want to get out of memory.

Speaking of memory: In your implementation you use `String` for the label and you might want to use dynamic memory allocation for your map. That is not a good idea, because it can make swiss cheese out of your heap memory (heap fragmentation). It is better to define a fixed array, that can hold the maximal number of elements (as I have done with the connection of a node). The not needed elements can be set to something meaningless (for the connections you can use the null pointer and for unused nodes simply only null pointer connections).


body:
I'm making an ESP32 development board and I'm thinking about putting an Arduino Leonardo chip between the USB port and the ESP32's USART pins to act as a USB/USART converter instead of the FTDI chip so that I can program the ESP32 through a USB serial port like any other Arduino board.

Is there a library/sketch licensed under a permissive license (MIT, BSD, Apache, etc.) which can make the Leonardo chip act as a HID Serial Port device which has a device name I want for easy identification in Device Manager and which requires no special driver installation in Windows and Linux once plugged into the computer?

Thank you for your time.

title: Is there a simple (permissive license) Leonardo driver for a USB-to-USART bridge to substitute an FTDI chip?

Answers: 1

body:
Why not write your own?

First off, you'll want to create your own custom board definition. To do that, find the `boards.txt` file in the AVR core of your installation. Then find the block of entries that starts `leonardo.` and copy the whole block. Change the `leonardo` to a name of your choosing.

Then change the `.name` entry to give your board a new name in the IDE.

Finally look for the (renamed) entries:

    leonardo.build.vid=0x2341
    leonardo.build.pid=0x8036
    leonardo.build.usb_product="Arduino Leonardo"

Of course the `leonardo` will be whatever you changed them to.  You can now give your board a new VID and PID to uniquely identify them - and also change the `usb_product` to name your board.

You can also add a `myboard.build.usb_manufacturer="..."` entry to change the manufacturer from the default of Arduino.

Now you have a board definition that identifies your board as what you want it to be.  So now just write a sketch that passes through the serial between USB and UART, and also handles the DTR and RTS signals to be able to enter flash mode on the ESP32 (hint: use `Serial.dtr()` and `Serial.rts()` to check the status of those signals).


body:
Greeting, first time Arduino user here.

So I am using the Arduino Micro as an HID keyboard device. It accepts arbitrary input from a Node-JavaScript program I am running (so I have full freedom in in the data transferred to the micro).

The goal is for the data transmitted to the micro to include information about a keypress: whether it was pressed or released and which key it is. The serial connections are all fine and dandy - I just have questions regarding the key pressing logic.

As far as the JavaScript program goes, a key down is detected based on the keyCode, not the character code so when tapping “a”, character code  97, the Arduino micro is receiving “A”, character code 65 since the JavaScript detected keyCode is 65. So that all sounds like problems with JavaScript (which it is), but remember that I have freedom in portraying the information sent to the micro.

That being said, instead of detecting by keyCodes and character codes in JavaScript, I could just transmit the letter e.g. “a” with some identifier for press/release such as “+a” for release and “-a” for press. My problem here is how would I handle modifier keys using the Keyboard library.

Should I handle character keys and modifiers keys separately i.e. `Keyboard.write` for characters and `Keyboard.press/release` for modifiers or are there cases where it would make sense to press and hold “a” (which would also be different than pressing and holding “A”)?

Below is my original code using keyCodes and “u/d” identifiers to denote up or down (which I am thinking now that “u/d” could be easily confused as a letter if I decide to transmit characters as characters:

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

    /*
      Receives from the hardware serial, sends to software serial.
      Receives from software serial, sends to hardware serial.

      The circuit:
       RX is digital pin 10 (connect to TX of other device)
       TX is digital pin 11 (connect to RX of other device)

      Not all pins on the Leonardo and Micro support change interrupts,
      so only the following can be used for RX:
      8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
    */

    #include <SoftwareSerial.h>
    #include <Keyboard.h>

    SoftwareSerial rpiSerial(10, 11); // RX, TX

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      // Set the data rate for the SoftwareSerial port
      rpiSerial.begin(115200);
      // initialize control over the keyboard:
      Keyboard.begin();
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Keyboard Serial Connection Established");
    }

    String keyCode = "";
    char state;

    void loop() {
      while (rpiSerial.available() > 0) {
        // "Type" via keyCodes (recommended for modifiers)
        // https://www.arduino.cc/en/Reference/KeyboardWrite not behaving as expected

        int data = rpiSerial.read();
        if (isDigit(data)) {
          keyCode += (char)data;
        }

        if (isAlpha(data)) {
          state = (char)data;
        }

        if (data == '\n') {
          Serial.print(state);
          Serial.println(keyCode.toInt());

          if (state == 'd') {
            Keyboard.press(keyCode.toInt());
          }

          if (state == 'u') {
            Keyboard.release(keyCode.toInt());
          }

          keyCode = "";
          char state;
        }
      }
    }

I have also noticed that the data from the serial connection parsed by the micro is sometimes incorrect i.e. a keyCode will be misidentified. For instance, by repeatedly pressing “a” through my JavaScript program, the JavaScript program will consistently identify keyCode 65 yet Arduino will identify the received data as keyCode 65 most of the time and then randomly keyCode 64. This happens with other keys as well and the keyCode doesn’t always happen to be just one less nor does it always occur after “n” presses.

title: Help with Arduino Micro Keypress Algorithm

Answers: 1

body:
Modifier keys are treated no different to normal keys.

The Arduino Keyboard library contains code to map different keys from the internal list of macros to specific keypresses:

* If the key value is >= 138 it's a non-printing special key (subtract 138)
* If the key value is >= 128 it is a modifier key (1 << (k - 128))
* Otherwise look the code up in a mapping table.

That means you can use:

    Keyboard.press(KEY_LEFT_SHIFT);

or

    Keyboard.release(KEY_RIGHT_GUI);

The full list of modifier keys is:

    #define KEY_LEFT_CTRL   0x80
    #define KEY_LEFT_SHIFT    0x81
    #define KEY_LEFT_ALT    0x82
    #define KEY_LEFT_GUI    0x83
    #define KEY_RIGHT_CTRL    0x84
    #define KEY_RIGHT_SHIFT   0x85
    #define KEY_RIGHT_ALT   0x86
    #define KEY_RIGHT_GUI   0x87

So to do a capital A you can use:

    Keyboard.press(KEY_LEFT_SHIFT);
    Keyboard.press('a');
    Keyboard.release('a');
    Keyboard.release(KEY_LEFT_SHIFT);

There is also a shortcut, and that is:

    Keyboard.press('A');
    Keyboard.release('A');

The character 'A' is the same in the lookup table as character 'a' except the high bit of the result is set, which triggers a "Press or release the shift key" addition in the mapping code.

A USB keyboard report consists of 8 bytes:

* Up to 8 modifier keys (bitmap)
* One reserved byte
* 6 bytes to indicate pressed keys

This means that you can have up to 6 keys pressed at once, plus modifier keys. Never any more than that. So you don't need to handle any more than that in your code.

The current list of pressed keys is maintained by the keyboard and is sent in every report. There's no concept as such of "pressed" or "released" - only the list of what is currently pressed. If a key is released it's just removed from that list of pressed keys.

So what you need is some way of transferring that data in such a way that the Arduino can interpret it properly.

Since the data is not high throughput you can afford to be quite wasteful in your protocol.  I would suggest using a fairly verbose ASCII based protocol.

* All the protocol data is using ASCII characters between 32 and 127 inclusive
* This frees up control characters (<32) for controlling the protocol.

The simplest thing is to use a single control character (such as `\n`) to act as a line ending to break your data up into packets.  Each packet can then contain a list of instructions.

For example, you might choose to have a protocol that looks like:

    P,129\n
    P,97\n
    R,97\n
    R,129\n

By treating each line as a complete entity you know that you want to **P**ress key 129 (`#define KEY_LEFT_SHIFT    0x81`), press key 97 ('a'), release 97, then release 129.

There's no confusion, since commands are all a single upper-case character, and keys are all a decimal number.

For your application, though, a "raw" access interface would be of more use, since you don't really want the Arduino interpreting things for you. However, the API doesn't provide that kind of thing.  So you just have to make the best of what you have and work around it.


body: I want to read out data from a load cell, for this I seem to need 2 analog input pins, the Wemos doesn't have this. In the Arduino I was also able to use the digital pint with PWM, there are also Wemos pins who have that. Is it possible to use them to read the data from the load cell?

title: For Arduino Uno it is possible to use the digital pins with PWM to read analog data, is this also possible with the Wemos D1 Mini?

Answers: 3

body:
PWM is quasi-analog **output**, and they have no symmetric analog read function.

The ESP8266 that is the heart of the Wemos D1 Mini has only 1 analog input.

If you need to read 2 analog signals, you can use an analog switch/multiplexer to read one value, and then the other value in quick succession. Or you can purchase an external ADC with multiple inputs -- these often communicate with a host by SPI or I2C connection, which the Wemos supports.

body:
There is one way you *could* measure analogue voltages using a PWM output: Use it as a DAC to build your own Successive Approximation ADC:

* The PWM is filtered through a low-pass filter to create an analogue voltage
* That is compared to an incoming voltage using a comparator
* The output of the comparator is recorded for different reference voltages using a "divide and conquer" method.

You can read more about how Successive Approximation works [here](https://en.wikipedia.org/wiki/Successive_approximation_ADC).

However, doing that would be overly complex and needlessly expensive. It is far better to just add an ADC chip using I2C or SPI. It's cheaper, easier, and the results will be far superior.

But as a learning exercise to discover how ADCs work, it could be kind of fun.

body:
You can use a capacitor and resistor to build a simple circuit to turn a voltage into a time duration, then precisely measure the timing to get a voltage. This isn't as fast as a direct read, but it can be more precise in some cases, and the sampling might be fast enough for your needs. The cost is great compared with external or home-brew ADCs.  I once used this method to build an ohmmeter with an ESP-01, which had a much greater range than a naive voltage divider would have provided.

You feed your voltage through a resistor into a capacitor, and have a digital input pin watching the resistor-cap voltage. You'll need to be generous with the timing because you want the cap to fully drain, and you can't tell from the MCU when that's completed, but a few preliminary DMM measurements will give you that info.

To measure voltage, you switch the GPIO from OUTPUT/low to to INPUT-PULLUP and wait for it to go HIGH. By measuring the time it takes before the pin goes high, you can calculate the voltage expected to fill the cap to the trigger threshold in that amount of time. You will need to do some manual measurements to calibrate it up-front, as different pins have different pull-up values and slightly different schmitt trigger voltage thresholds. Once setup, it can be repeatable to about +/- 5%, maybe more with slower sampling.

ascii schematic:
```(vSensor) --- [R1] --- (GPIO) --- [C1]  --- GND```


body:
[![My circuit table schematic][1]][1]

I wanted to control speed of my four coreless DC motors using Arduino Nano. Then I realised my 3.7V 380mAh 25C and 720mAh (110mAh on picture is just to hold my battery's place) 25C LiPo batteries won't meet the voltage requirement of a Nano. Then I came up with the idea of using Pro Mini instead of Nano; however I couldn't find a 3.3V pin on Pro Mini to feed NRF24. On Nano, I was using a 3.3V pin and 10uF capacitors between Vin and Gnd legs of NRF24.

So my question is: can I feed NRF24 directly from Vcc pin? Or as an alternative what would happen if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via another TIP122 transistor?

Note: I am using 4 of TIP122 transistors whose gate legs are connected to Pro Mini's 5, 6, 9 and 10 pwm pins (I forgot to add base-resistors). Do you also think it is a reliable way of controlling the motors' speed?

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

title: How do I feed NRF24L01 from Arduino Pro Mini?

Answers: 1

body:
> can I feed NRF24 directly from Vcc pin?

NO: the pro mini is either 5V or not strong enough to power the RF24.
EDIT: the 3V3 pro mini "could" power the RF24 via VCC, if you use the cap and if it's not the PA&LNA model (or in full power mode). Best practise is to use an external regulator.

> if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via
> another TIP122 transistor?

NO: lipos are 4.2V when fully charged, and they can be used until 3V (I mean 3V sag voltage, when the load is powered, not when disconnected): External 3V3 regulators is the way to go.

> Do you also think it is a reliable way of controlling the motors'
> speed?

These are PWM output, so yes, why not? Also, add flyback/freewheeling diodes (and -maybe- 100nF polyester caps should help) between the motors terminals.


body:
I am trying to send a WebSocket message to a server. The example for the ArduinoHttpClient library uses WiFi101 but that will not work for the MKR 1010. So I am trying to use WifiNINA instead. The WiFi part works fine but is seems the WebSocket cannot "begin".

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

```
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoHttpClient.h> /*Need to implement*/
//https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/examples/SimpleWebSocket/SimpleWebSocket.ino
//https://www.arduino.cc/en/Tutorial/WiFiNINAConnectWithWPA

char ssid[] = "SSID_NAME";        // your network SSID (name)
char pass[] = "WPA2_Password";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status
char serverAddress[] = "192.168.0.195";  // server address
int port = 3652;

WiFiClient wifi;

WebSocketClient client = WebSocketClient(wifi, serverAddress, port);

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();

}

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  //printCurrentNet();

    Serial.println("starting WebSocket client");
    client.begin();
    Serial.print("Is client connected? -> ");
    Serial.println(client.connected());

      client.beginMessage(TYPE_TEXT);
      client.print("Fire alarm from arduino mkr1010 - sensor1 ");
      client.endMessage();

    while (client.connected()) {
      Serial.print("Sending fire alarm ");
      // send fire alarm
      client.beginMessage(TYPE_TEXT);
      client.print("Fire alarm from arduino mkr1010 - sensor1 ");
      client.endMessage();
    }
    /*
      // check if a message is available to be received
      int messageSize = client.parseMessage();

      if (messageSize > 0) {
        Serial.println("Received a message:");
        Serial.println(client.readString());
      }*/

}

void printWifiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  Serial.println(ip);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}
```

Could it be that there are compatibility issues between the ArduinoHttpClient library and the Arduino MKR1010? I am thinking of getting an ESP32 instead since there seem to be more WebSocket libraries built around it.

title: WebSocket message with Arduino MKR 1010 using WiFiNINA and ArduinoHttpClient libraries

Answers: 1

body:
I needed to use port 80.

I got a hint from wikipedia:

>The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections), which is of benefit for those environments which block non-web Internet connections using a firewall.

https://en.wikipedia.org/wiki/WebSocket

Switched to port 80 and it works!


body:
I have a NodeMCU (ESP8266) board that I want to control over the internet. I am trying to find a solution where I don't have to set up any configurations on my router like port forwarding. I came up with the following solution:

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

I have a website where the user changes the device status (with status I mean for example GPIO5 pin value HIGH or LOW) which is then saved to a database on a shared hosting server. The NodeMCU sends periodically (for example every 5 seconds) a HTTP GET request to the database. According to the value that is received from the database the NodeMCU board changes the pin value to HIGH or LOW. If NodeMCU changes it's status (for example a pin value from HIGH to LOW) the new device status is sent to the database with a HTTP POST request. The device also sends a HTTP POST request periodically (for example every 60 seconds) so the user can monitor the device status on the website.

There are a few problems with this configuration:

 1. There is no real-time connection between NodeMCU and the user (there
    is always a delay in the device response)
 2. The device sends thousand of queries every day that are a load to
    the shared hosting server. For example if the GET request is sent
    every 5 seconds, that gives 17280 queries per day for one device.

So my question is how practical is this configuration on shared hosting or any kind of hosting, what are the alternatives or improvements to this configuration and how to establish a connection with the NodeMCU so that the device sends a GET request to the database only when the device status is changed in the database by the user.

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

title: NodeMCU (ESP8266) board controlled over shared hosting database

Answers: 1

body:
Use MQTT.

You need:

1. The PubSubClient.h library
2. An MQTT server

For MQTT there are some free ones around on the internet (ask Google). Or if you have a Linux server available for use (e.g., a cheap VPS server from one of many many providers online) then you can run your own with `mosquitto`.

MQTT works kind of how you describe, but it's not making constant GET requests - it opens a single connection to the MQTT server and realtime requests are sent down it to the client, and back from the client to the server.

Near realtime communication.


body:
I have been looking through StackExchange, and searching on the web and cannot find an answer to my issue.

Setup:
Arduino Nano 168
HC-05 VERSION:3.0-20170601

I am trying to connect my Android phone to my Nano to control an output. I have found tons of varying examples, but they all basically boil down to MIT App Inventor to create app to connect via BT and send data to the Nano to control.

After many attempts with no results, I attempted the following:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>

    int light=8;
    int Received=0;
    int light_state =0;

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup(){

      Serial.begin(38400);
      pinMode(light,OUTPUT);
      BTSerial.begin(38400);

    }

    void loop(){
      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available()) {
        Serial.write(BTSerial.read());
     }

     if(BTSerial.available()>0) {
        Received = BTSerial.read();
     }

    if (light_state == 0 && Received == '1') {
        digitalWrite(light,HIGH);
        light_state=1;
        Received=0;
      }
    if (light_state ==1 && Received == '1') {
        digitalWrite(light,LOW);
        light_state=0;
        Received=0;
      }
    }

So, when I run the MIT app on my phone to connect to the HC-05 the status LED on the HC-05 changes.  Before I connect, the status LED flashes fast.  After I connect, it flashes slow.

I have the serial monitor open on my laptop monitoring the Nano.  The HC-05 connects via pins 10 & 11.  When the phone connects to the HC-05, the data printed on the serial monitor is garbage.

⸮x⸮x⸮⸮x⸮x⸮x⸮⸮xxxxxx⸮x⸮⸮xx⸮⸮xxx⸮⸮

That is what I get.

The app is set to transmit a "1" via BT to the Nano.  When I press the button to send the 1, no data comes across.  But every time I pick the HC-05 and tell the app to connect to the unit, I get that same string of data above.

Thank you in advance for your help.

title: HC-05 connecting to Arduino

Answers: 1

body:
This issue has been resolved.  There was an issue with the parity and stop bits.

When setting up for arduino comms, remember, baud rate, 1 stop bit, 0 parity bits.


body:
I have a project that (in part) will drive 3 LEDs where the LED
anodes are at 12V.  The thought is to drive each LED by connecting
each cathode to a 650 ohm resistor, and connect that to an Arduino DIO pin which, when needed, is set to output LOW.  Arduino VIN = same 12V with
common ground.  Am I going to have an Arduino problem of any sort?

title: Output pin low used to complete 12V LED circuit?

Answers: 1

body:
No, what you propose will not work. And it risks damaging your Arduino.

Normally you would include a single transistor which the Arduino uses to control the power through the LEDs. This removes the 12V from the Arduino and turns the output into an actual switch.

The problem is that the Arduino's GPIO isn't just a single transistor.  It is (amomgst other things):

* Two complimentary transistors (that's the C in CMOS) for HIGH and LOW switches
* ESD Diodes
* Input buffer

By just adding the one transistor like this:

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

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

<!-- End schematic -->

the 12V is kept well away from the Arduino. Setting the output HIGH will turn on the transistor, allowing the current to flow to ground. Setting it LOW with turn it off, blocking the flow of current and switching the LEDs off.

Further: the Arduino's GPIO has a maximum sustained current of 25mA. Ideally you don't want to even come anywhere near this. By adding the transistor it acts as a buffer and allows you to deal with much higher currents - and hence more, and brighter, LEDs.

Incidentally, R1 in that schematic is there solely to keep the transistor *off* when the Arduino is not actively driving the output - e.g., when it's either unpowered or is running the bootloader - or you happen to have the GPIO in INPUT mode (as it defaults to).


body:
I'm trying to use timer3 on an Arduino Mega 2560 in CTC mode. However, enabling CTC disables the code entirely.

Here is the function I call in setup() to setup the times.

```cpp
void SetupInterrerupt() {
  cli(); // Disable interrupts

  // Setup timer
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // Setup compare match register
  OCR3B =  CMP_FAST; // CMP_FAST = 40

  // turn on CTC mode:
  TCCR3B |= (1 << WGM32); // Commenting out this line makes the code work
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  sei(); // Enable interrupts

  Serial.println("Timers enabled");
}
```

And the interrupt vector.

```cpp
// Timer 3 Interrupt
ISR(TIMER3_COMPB_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
  // do stuff...
}
```

As is, the interrupt doesn't execute at all. As noted in the code, commenting out "TCCR3B |= (1 << WGM32);" actually executes the interrupt, except the frequency is more like 1Hz instead of 720.

I'm using the [arduino-lmic library][1], as well as some other data structure libraries. I don't think they use any timers, but since lmic is designed for Uno's, I figured that using timers 3 and up would be fine.

I'm a little rusty on my timers unfortunately. Is anyone able to spot my mistake?

Thanks.

  [1]: https://github.com/matthijskooijman/arduino-lmic

title: Arduino Mega - Enabling CTC mode disables timer

Answers: 1

body:
I think your problem is that you are using the wrong "TOP" counter value register.

    OCR3B =  CMP_FAST; // CMP_FAST = 40

should be:

    OCR3A =  CMP_FAST; // CMP_FAST = 40

I am not too familiar with the workings of the AVR times, but according to the datasheet:

> In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution.

(Note: it only mentions the register for timer 2, but the same holds true for all the timers in the same class, including timer 3).

Since OCR3A is zero it never triggers a match.  And since there is only one counter (TCNT3) which gets reset to 0 on a match, there can only be one register to compare to, and that is the "A" register. The "B" register appears to be redundant in CTC mode.

You may also need to switch to the COMPA vector (I am not sure on this one TBH)


body:
I am trying to make the value of PIR sensor value HIGH for certain time using code. SR505 have a default time delay of 8 seconds. But I want to increase it to 20 seconds.

I am thinking of increasing it using `TICKER` library. I have tried and tested a basic code and seems to be working fine. But I want to implement it with Ticker which will keep the value HIGH for 20 seconds as soon as the timer goes above 20 seconds and PIR is not detecting the motion then it will go set again the timer to 0.

Here is how my code looks like:

    #include <Ticker.h>

    #define SIGNAL_PIN D2

    Ticker flipper;

    void setup()
    {
      Serial.begin(9600);
      pinMode(SIGNAL_PIN, INPUT);
      digitalWrite (SIGNAL_PIN, LOW);

    }

    void flip(){
      Serial.println("From callback");
      digitalWrite (SIGNAL_PIN, HIGH);
    }

    void loop() {
      if(digitalRead(SIGNAL_PIN)==HIGH) {
        Serial.println("Movement detected.");
        flipper.attach(1, flip);
      } else {
        Serial.println("Did not detect movement.");
        flipper.detach();
      }
      delay(1000);
    }

Thank you!

title: SR505 PIR sensor Time Delay Using Ticker Library NodeMCU

Answers: 1

body:
You really don't need the Ticker library. Just maintain a timestamp of the last time the PIR was seen to be HIGH:

    void loop() {
        static uint32_t lastSeenHigh = millis();
        static bool pirState = false;

        // If it's active then record that fact along with the time
        if (digitalRead(SIGNAL_PIN) == HIGH) {
            lastSeenHigh = millis();
            pirState = true;
        } else {
            // otherwise, if it's been 12 seconds since last seen
            // active, record that it's inactive.
            // 20 seconds, minus the 8 second active time, times 1000 is
            // 12000 milliseconds to extend the time by
            if ((millis() - lastSeenHigh) > 12000) {
                pirState = false;
            }
        }

        if (pirState == true) {
            // Do whatever you want in here when the PIR is active
        }
    }

With that (untested) code:

* Any time the PIR is active the current time is recorded and the state is set true
* When the PIR is LOW and at least 12 seconds have passed since the last activation, set the state to false.


body:
I've set up an ESP8266 (Wemos D1 Mini) to get IP-information via DHCP.
Everything works fine and I can print the information :

Serial.print(WiFi.macAddress());
Serial.print(WiFI.localIP());
Serial.print(WiFi.subnetMask());
Serial.print(WiFi.gateway.IP());

But how do I print the DNS-address ??

I cant find a function for this ???

/Kind regards : Gurra

title: ESP8266 print DNS address (obtained via DHCP)

Answers: 1

body:
    Serial.println(WiFi.dnsIP());

If you have more than one DNS server you can specify the index:

    Serial.println(WiFi.dnsIP(1));


body:
I'm playing with my first Arduino device (Arduino Leonardo). It worked fine but at some point it failed. **I'm getting this error**:

> avrdude: ser_open(): can't set com-state for "\\.\COM6"

> An error occurred while uploading the sketch

The error came out of nowhere because I didn't change the port or cable or anything. Everything seems to be in order: the port, the driver, the IDE, the cable. And everything worked just an hour ago.

1) I've tried to change the port
2) I've reinstalled IDE
3) I've tried different cable

What else can I do?

And another thing: after manual reset of Arduino (with button) device disappears.

title: Arduino stopped working: avrdude: ser_open(): can't set com-state

Answers: 1

body:
The thing to remember with the Leonardo and other ATMega32U4 based boards is that there is no actual serial connection.

What there is, is a USB connection which is controlled by the sketch (and independently by the bootloader) to provide a "CDC/ACM" connection over USB.  This emulates a serial connection, but it's not a *real* serial connection.

This actually has a huge number of benefits, because you can be other things besides a serial port, such as a keyboard or a mouse. However, it comes at a cost:  the serial port is at the mercy of the sketch that's running at the time.

If your sketch crashes for any reason then the serial port can no longer be used. That's bad. It can cripple your Arduino. Since it's the sketch that is providing the driving force for the CDC/ACM serial emulation, if that sketch dies, so does the control of the USB and thus the CDC/ACM.

So while the port may be created initially by the sketch, if it then subsequently crashes the port is still there, but unresponsive.  Or the port can vanish completely.

So how do you fix it?  Well, there's a couple of strategies:

1. Some people have had success by pressing the RESET button twice in quick succession. This depends on the version of the bootloader in use though, and it's not something I have ever tried.
2. Pressing RESET at just the right moment to get the bootloader to run *just before* `avrdude` runs and catch it at the right time to accept a new sketch, or
3. Using a hardware programmer (e.g., USBASP) or another Arduino to wipe the chip and reinstall the bootloader

My preferred method is 3, since it is certain to always work - however it requires either a hardware programmer or another Arduino. However you can pick up a USBASP on eBay / AliExpress / Amazon etc for next to nothing, and when you're working with AVR chips they're always good to have to get you out of tight spots like this.


body:
I am trying to convert `byte*` value to `int` here is how I have it.

    void mqttCallback(char* topic, byte* payload, unsigned int length) {

      String topicStr = topic;
      int* payload_value;
      int updates_cal;

        payload_value = (int*)payload;
        //updates_cal = *payload_value;

        Serial.print((int)payload_value);

      delay(1);

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

    }

I am getting MQTT payload as Integer value. Which I want to receive in my NodeMCU (ESP8266).

Is there any way to do this?

Thank you!

title: Convert byte* to int in Arduino

Answers: 3

body:
`byte*` means "pointer to byte(s). It is usually used to point to a byte buffer, and usually will also have a length value so you know how many bytes are in the buffer. It looks like your function does have a length value.

If you're certain that the data in the `payload` parameter is a single int, and the length is correct for an int (2 bytes on Arduino I believe) then you should be able to cast the pointer to `int*` type and then fetch the value from the buffer:

    void mqttCallback(char* topic, byte* payload, unsigned int length) {
      String topicStr = topic;
      int payload_value;
      int updates_cal;

      if (length >= 2) {
        //Cast payload to an int pointer and fetch the value
        intValue = *((int*)payload);
      }
    }

body:
Judging by the comments, you are actually receiving your integer data as text, as a sequence of ASCII characters. This is what you send yourself using `mosquitto_pub`. The buffer is apparently not zero-terminated.

If these characters represent an integer value, then the way to retrieve it as an integer value would be

    char buffer[128];

    // Make sure here that `length` is smaller than the above buffer size.
    // Otherwise, you'd need a bigger buffer

    // Form a C-string from the payload
    memcpy(buffer, payload, length);
    buffer[length] = '\0';

    // Convert it to integer
    char *end = nullptr;
    long value = strtol(buffer, &end, 10);

    // Check for conversion errors
    if (end == buffer || errno == ERANGE)
      ; // Conversion error occurred
    else
      Sterial.println(value);

---

Another approach, which avoids using a separate large[ish] buffer just for the purposes of zero-termination, would be

    // Build a `scanf` format string that will read no more than `length`
    // characters without relying on zero-termination of the payload
    char format[16];
    snprintf(format, sizeof format, "%%%ud", length);

    // Convert the payload
    int payload_value = 0;
    if (sscanf((const char *) payload, format, &payload_value) == 1)
      Serial.println(payload_value);
    else
      ; // Conversion error occurred

However, this approach is less protected from integer overflow than the previous one.

---

Note that most of the above "jumping through the hoops" is dedicated to adding a zero-terminator to the input buffer. If instead you opt for ensuring zero-termination on the sender's side, then it would all reduce to a simple

    // Convert C-string to integer
    char *end = nullptr;
    long value = strtol((const char *) payload, &end, 10);

    // Check for conversion errors
    if (end == buffer || errno == ERANGE)
      ; // Conversion error occurred
    else
      Sterial.println(value);

No extra buffers required.

body:
Don't know if you found an answer yet, but I had the exact same issue and eventually came up with this:
```
   payload[length] = '\0'; // Add a NULL to the end of the char* to make it a string.
   int aNumber = atoi((char *)payload);
```

Pretty simple in the end!


body:
I'm trying to create a class that uses `attachInterrupt`, but get this error msg:

     In member function 'void ledDoor::attach()':
    ClosetLedStrip:31:82: error: invalid use of non-static member function
             attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
                                                                                ^
    exit status 1
    invalid use of non-static member function

I found few [answers][1] regarding `static member`, but it was not clear for my needs.

Appreciate help,

    #define USE_SLEEP true

    #if USE_SLEEP
    #include <avr/sleep.h>
    #endif

    #define sensorPin_1 2
    #define sensorPin_2 3
    #define RelayON HIGH
    #define doorOpen HIGH

    #define pwrdown_timeOut 10*(1000*60) // mins to powerdown

    // volatile boolean detectDoor_1_Open = false;
    //volatile boolean detectDoor_2_Open = false;
    const int relayPin1 = 4;
    const int relayPin2 = 5;

    class ledDoor {

    private:
    int _sensorPin;
    int _interruptPin;
    int _relPin;

    void  attach(){
            attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
    }

    void detection_door(){
        #if USE_SLEEP
            sleep_disable();
        #endif

            detachInterrupt(digitalPinToInterrupt(_sensorPin));
            if (digitalRead(_sensorPin) == doorOpen) {
                    _doorOpen = true;
            }
            else {// trun off
                    _doorOpen = false;
            }
            attach();
    }

    public:
    bool volatile _doorOpen;
    ledDoor(int sensorPin, int relPin){
            _sensorPin=sensorPin;
            _relPin=relPin;

            pinMode(_relPin, OUTPUT);
            pinMode(_sensorPin, INPUT); // sensor io
            attach();
    }
    void go2sleep() {
      #if USE_SLEEP
            sleep_enable();
            set_sleep_mode(SLEEP_MODE_PWR_DOWN);
            sleep_cpu();
      #endif

    }
    void switchLeds(){
            if (_doorOpen == true) {
                    digitalWrite(_relPin, RelayON);
            }
            else{
                    digitalWrite(_relPin, !RelayON);
            }
    }

    };

    ledDoor door1(sensorPin_1, relayPin1);
    ledDoor door2(sensorPin_2, relayPin2);

    void setup() {
            Serial.begin(9600);
            Serial.println("UP");
    }

    void loop() {
            door1.switchLeds();
            door2.switchLeds();

      #if USE_SLEEP
            door1.go2sleep();
            door2.go2sleep();
      #endif
    }

  [1]: https://stackoverflow.com/questions/41443720/how-to-create-an-isr-in-an-arduino-class

title: AttachInterrupt - fail to initiate inside a class

Answers: 1

body:
Firstly, if `detection_door` is a non-static member function, then C++ simply has no such expression syntax as just `detection_door`. Such functions have to either be called (with `()` operator) or be taken address of (with `&` operator). You can't just say `detection_door`. That's meaningless, which is what the compiler is telling you.

Secondly, as you already realized, regardless of the syntax a non-static class member function cannot be used as an interrupt handler. You need a freestanding ("ordinary") function as a handler or a static class member. Non-static class methods are beasts of completely different and incompatible nature.

I see that you have multiple `ledDoor` objects that you want to attach to interrupts independently.

At the level of `attachInterrupt` and `void (void)` handlers you will not be able to use a single interrupt handler function and then properly dispatch the handling to multiple individual objects. The high-level `attachInterrupt` mechanism is insufficient to work around this limitation in a proper way. (At ISR level you can do that, the same way `Servo.h` handles multiple servos, but it is more complicated.)

For this reason, in your case, as long as you want to stay at `attachInterrupt` level, it is better to just implement two separate interrupt handlers as external functions that will call your class methods for your existing global objects

```cpp
ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void handler_door1()
{
  door1.detection_door();
}

void handler_door2()
{
  door2.detection_door();
}
```

and then just attach these handlers to your desired pins in a regular way.

`static` in this case can only change things in a purely cosmetic way.

---

On the second thought one can wrap the above into a quasi-elegant implementation that might look as follows
```cpp
constexpr unsigned N_PINS = 16; // Range of attachable pin numbers

class ledDoor
{
  // ...

  static ledDoor *self[N_PINS];
  static void (*const HANDLERS[N_PINS])();

  template <unsigned PIN> static void handler()
  { // This is the actual interrupt handler that will dispatch the call to
    // the `detection_door` method of the proper class object
    self[PIN]->detection_door();
  }

  // ...

  void attach()
  {
    self[_sensorPin] = this;
    attachInterrupt(digitalPinToInterrupt(_sensorPin), HANDLERS[_sensorPin], CHANGE);
  }

  void detection_door()
  {
    // Your code
  }
};
```
And somewhere in one of the `.cpp` files
```cpp
// Definitions and initializers for static members

ledDoor *ledDoor::self[N_PINS] = {};

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  ledDoor::handler<0>,
  ledDoor::handler<1>,
  // ...and so on...
  ledDoor::handler<15>
};
```
This uses a dedicated callback for each pin. Maybe a better idea would be to use interrupt number (i.e. the result of `digitalPinToInterrupt`) for indexing instead of pin number.

The same thing can be rewritten through lambdas instead of a template. I.e. one can get rid of `ledDoor::handler<>` template and instead initialize the `HANDLERS` array as
```cpp
void (*const ledDoor::HANDLERS[N_PINS])() =
{
  [](){ ledDoor::self[0]->detection_door(); },
  [](){ ledDoor::self[1]->detection_door(); },
  // ...and so on...
  [](){ ledDoor::self[15]->detection_door(); }
};
```
Note that this approach is a bit more memory wasteful that it could have been, since it uses a number of static tables of pre-determined size. In essense this is a slightly different implementation of the same "gluing" approach as described [here][1].

  [1]: https://arduino.stackexchange.com/questions/20608/pass-classs-public-function-as-an-argument-to-external-command


body: I am very new to arduino and I've been scratching my brain on how to make one button print out three different sentences. When I press it the first time, a " I am " is suppose to appear, when I press it the second time " very" and then the third time " late". I can't have three different buttons because a tone follows this button as well.

title: Make one button print different sentences on LCD

Answers: 1

body:
Consider using what is commonly called in programming as a [Finite-state machine][1].  Advance to the next state each time the button is pressed.  Start out with 3 states and advance to the next after pressing the button.  You many need to double the number of states after adding your message to the program.  This is because you will want to press the button and only print the message once then advance to a new state where all you do is wait for the next button press.

Note, a mechanical device such as a button will need to be de-bounced either in [hardware][2] or in [software][3].  This is because the processor may see individual makes and breaks as the button is closed and opened causing it to advance to the next state in unexpected ways.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: http://www.labbookpages.co.uk/electronics/debounce.html
  [3]: https://www.arduino.cc/en/tutorial/debounce


body:
I have a Question regarding Arduino IDE:

Many old Arduino setup examples states that the Serial.begin() function always should begin with :

    Serial.begin(9600); // (or 115200)

    while (!Serial)
     {
       ; // Wait for serial to connect
     }

Now I have read a lot of comments saying that this "Wait-function" is no longer necessary ??

Is this an old routine, that's no longer necessary, or is it still important ???

title: Arduino-IDE "while (!Serial)"

Answers: 3

body:
Microcontrolers with native USB interface create an USB connection. It takes a little time. The serial prints right after begin() would be lost without waiting or the connection.

For Uno, Mega, Nano, esp8266/32 boards and other boards with a MCU without native USB support, an external USB-to-TTL-Serial converter chip handles the USB connection.

Leonardo, Micro, MKR have an MCU with built-in USB port. Some boards with Zero or M0 in name have only the native USB port, some have a debugger chip which can serve as USB-to-TTL-Serial converter too.

`!Serial` is a C++ construct using bool() operator. Then implementation is a function which checks if the USB connection is ready.

The waiting for native USB Serial (called SerialUSB for some boards) is used in examples to see the debug prints from setup(). But if USB is not connected, it waits and the sketch doesn't continue. It can be very confusing. So I rather use a `delay(500)` after `Serial.begin()` on boards with native USB.

body:
This is for the Arduino boards that have native USB to ensure that the serial port is ready before progressing. The while loop is not needed for Arduino boards where the USB is not native to the processor (such as the Arduino Uno).

> Indicates if the specified Serial port is ready.
>
> On the boards with native USB, if (Serial) (or if(SerialUSB) on the Due) indicates whether or not the USB CDC serial connection is open. For all other boards, and the non-USB CDC ports, this will always return true.
>
> Ref: [Arduino Reference > communication > serial > if(serial)][1]

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/

body:
That function is not obsolete. However, there is gratuitous use of it where it's not really needed.

The usage of the function that you alude to grew from the desire to make ATMega32U4-based boards (such as the Leonardo) which have a *native* USB interface act similar to the ATMega328P etc boards.

When you open the serial port on an Uno, for example, the main MCU is reset and the sketch runs from the start.  When you do the same on a Leonardo that doesn't happen. So by adding that code snippet to the beginning the sketch is paused until the serial port is opened.  This makes it appear that the board has been reset and the sketch is running afresh, like an Uno - but it isn't.

Placing that `while` loop at the start of your sketch without thinking about the consequences means that your sketch may never run. If a serial connection is *required* for your program then that's not such a problem. However, if all you're using the serial for is debugging, then as soon as you try and use your sketch *without* the computer opening the serial port it will fail.

So I would recommend *not* using that `while` loop unless you know that you want the effects that it provides.  That is, stalling the sketch until the serial port is opened by the computer.


body:
When I disassemble an Arduino IDE created pjoject I see in the created code ("disassembled code actually"), the it uses IN / OUT instruction on port 0X6F.

Like this (part of disassembled list):

    00E3     4FFF                SBCI      R31,0XFF                 ; .O
    00E4     91A5                LPM       R26,Z+                   ; ..
    00E5     91B4                LPM       R27,Z                    ; ..
    00E6     B79F                IN        R25,0X6F                 ; ..
    00E7     94F8                CLI                                ; ..
    00E8     1161                CPSE      R22,R1                   ; a.
    00E9     C004                RJMP      L00EE                    ; ..

    00EA     918C                LD        R24,X                    ; ..
    00EB     9530                COM       R19                      ; 0.
    00EC     2338                AND       R19,R24                  ; 8#
    00ED     C002                RJMP      L00F0                    ; ..

    00EE     91EC      L00EE:    LD        R30,X                    ; ..
    00EF     2B3E                OR        R19,R30                  ; >+
    00F0     933C      L00F0:    ST        X,R19                    ; <.
    00F1     BF9F                OUT       0X6F,R25                 ; ..
    00F2     9508      L00F2:    RET

Anyway the ATMEGA328 Datasheet says that port 0x6F is memorymapped and as such should be accessed through LDS/STS instructions.  This problem really confuses me.  Can anyone give me an explanation ??  Thanks !

title: Port 0x6F problem

Answers: 1

body:
The AVR operation code for the IN instruction is:

    Loads data from the I/O Space (Ports, Timers, Configuration Registers, etc.) into register Rd in the Register File.

    Operation:
    (i) Rd ← I/O(A)
    Syntax: Operands: Program Counter:
    (i) IN Rd,A 0 ≤ d ≤ 31, 0 ≤ A ≤ 63, PC ← PC + 1
    16-bit Opcode: 1011 0AAd dddd AAAA

The disassemble of the operation code `B79F (hex) = 1011 0111 1001 1111 (bin)` is `IN R25,$3F` which is actually `SREG`.

The block of code with the `IN, CLI` and `OUT` instruction is a critical section where the flags in `SREG` are saved, interrupts are turned off, and later the `SREG` is restored.

Cheers!


body:
I am attempting to use this code to receive data from 2 ports, alternating between them:

    /*
      Software serial multple serial test

      Receives from the two software serial ports,
      sends to the hardware serial port.

      In order to listen on a software port, you call port.listen().
      When using two software serial ports, you have to switch ports
      by listen()ing on each one in turn. Pick a logical time to switch
      ports, like the end of an expected transmission, or when the
      buffer is empty. This example switches ports when there is nothing
      more to read from a port

      The circuit:
      Two devices which communicate serially are needed.
       First serial device's TX attached to digital pin 10(RX), RX to pin 11(TX)
       Second serial device's TX attached to digital pin 8(RX), RX to pin 9(TX)

      Note:
      Not all pins on the Mega and Mega 2560 support change interrupts,
      so only the following can be used for RX:
      10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

      Not all pins on the Leonardo support change interrupts,
      so only the following can be used for RX:
      8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

      created 18 Apr. 2011
      modified 19 March 2016
      by Tom Igoe
      based on Mikal Hart's twoPortRXExample

      This example code is in the public domain.

    */

    #include <SoftwareSerial.h>
    // software serial #1: RX = digital pin 10, TX = digital pin 11
    SoftwareSerial portOne(10, 11);

    // software serial #2: RX = digital pin 8, TX = digital pin 9
    // on the Mega, use other pins instead, since 8 and 9 don't work on the Mega
    SoftwareSerial portTwo(50, 51);

    int RFIDResetPin = 13;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      pinMode(RFIDResetPin, OUTPUT);
      digitalWrite(RFIDResetPin, HIGH);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // Start each software serial port
      portOne.begin(9600);
      portTwo.begin(9600);
    }

    void loop() {
      // By default, the last intialized port is listening.
      // when you want to listen on a port, explicitly select it:
      portOne.listen();
      Serial.println("Data from port one:");
      // while there is data coming in, read it
      // and send to the hardware serial port:
      while (portOne.available() > 0) {
        char inByte = portOne.read();
        Serial.write(inByte);
      }

      // blank line to separate data from the two ports:
      Serial.println();

      // Now listen on the second port
      portTwo.listen();
      // while there is data coming in, read it
      // and send to the hardware serial port:
      Serial.println("Data from port two:");
      while (portTwo.available() > 0) {
        char inByte = portTwo.read();
        Serial.write(inByte);
      }

      // blank line to separate data from the two ports:
      Serial.println();
    }

I am using a mega2560, and have the pins placed in the 10 and 51 port. any help is appreciated.

title: Scanned RFID data is not appearing in the serial monitor

Answers: 0


body:
I'am a NEW-B with an ELEGOO mega 2560 starter kit.The program code came from their disc.The verifying error message for the declaration: RTCDateTime dt; is

RTCDateTime' does mot name a type

exit status 1

'RTCDateTime'does not name a type

I can not determine what this means or how to correct.
HELP,Dick

title: code error- Real Time Clock program-DS3231 RTC module

Answers: 0


body:
I want to read the value of the register (8-bit). In particular I want to read the values of:

 1. The Timer/Counter - TCNT0 ( **Adress** 0x26 (0x46) )
 2. The output compare registers - OCR0A and OCR0B.

Is there a way to read them with the Arduino program?

title: Read the value of a register in arduino

Answers: 1

body:
To convert my comments to an answer:

You can use the register names directly. They are defined in the boards/chips core. To read them, simply use the names in your calculations. Write to the registers by setting the value of the registers name (like a variable: `TCNT0 = 0;`). Be sure to look into the datasheet, to check the behavior of that register.


body:
I have an Arduino with few sensors, and I want to send all of data to my API over ESP8285 what is connected to the wifi.

Its almost working fine, except one thing.

I have these AT commands:

    String postRequest =
        "POST /hello HTTP/1.1" + String("\r\n") +
        "Host: 192.168.88.186" + "\r\n" +
        "Cache-Control: no-cache" + "\r\n" +
        "Content-Type: application/x-www-form-urlencoded" + "\r\n" +
        "Content-Length: " + String(data.length()) + "\r\n\r\n" +
        String(data) + "\r\n";

    void connectWifi()
    {
      espclient.println("AT+CWMODE=1");
      String connectcmd = "AT+CWJAP=\"" + ssid + "\",\"" + w_password + "\"";
      espclient.println(connectcmd);

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

    void espStatus()
    {
        String tmpResp = espclient.readString();
        Serial.print("ESPLOG:");
        Serial.println(tmpResp);
    }

    void httppost()
    {
      espclient.println("AT+CIPMUX=0");
      espclient.println("AT+CIPSTART=\"TCP\",\"" + server + "\",5000"); //start a TCP connection.
      if (espclient.find("OK"))
      {
        Serial.println("TCP connection ready");
      } else {
        espStatus();
      }
      espclient.println("AT+CIPSTATUS");
      espStatus();

      Serial.println("PRINT REQUEST ==================================");
      Serial.println(postRequest);
      Serial.println("PRINT REQUEST ==================================");

      espclient.println("AT+CIPSEND="+String(postRequest.length()));
      do {
        delay(1000);
        if (espclient.find(">"))
        {
          break;
        }
      }
      while(true);
      espclient.print(postRequest);
      delay(500);
      espStatus();
      espclient.println("AT+CIPCLOSE");
    }

**SETUP:**

    void setup() {
      Serial.begin(9600);
      Serial.println("Starting the modules....");

      espclient.begin(9600);
      connectWifi();
      Serial.println("ESP Module is ready");
    }

**LOOP:**

    void loop() {
        httppost();
        delay(5000);
    }

And I get this error(?) message:

    TCP connection ready
    ESPLOG:
    AT+CIPSTATUS

    STATUS:2

    OK

    PRINT REQUEST ==================================
    POST /hello HTTP/1.1
    Host: 192.168.88.186
    Cache-Control: no-cache
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 13
    name=ESPModul

    PRINT REQUEST ==================================
    ESPLOG: Q�J5U�S�!*HZYlo QQA��HV�^\��
    H��銒)  �&�C��y \�R
    �r�+����H�

    TCP connection ready
    ESPLOG:
    AT+CIPSTATUS

    STATUS:2

    OK

    PRINT REQUEST ==================================
    POST /hello HTTP/1.1
    Host: 192.168.88.186
    Cache-Control: no-cache
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 13
    name=ESPModul

    PRINT REQUEST ==================================
    ESPLOG: Q�J5U�S�!*HZYlo QQA��HV�^\��
    H����)  �&AC��y \�R
    �r�+����H�

**UPDATE** The new /error/ message:

    ESPLOG:Q�J5U�SS�CT��he���EE))���H��
    ���� )�H��HK�
    Ca����E�K�V,YCCb

**UPDATE2** I restarted the arduino, and now I am getting this:

    TCP connection ready
    PRINT REQUEST ==================================
    POST /hello HTTP/1.1
    Host: 192.168.88.186
    Cache-Control: no-cache
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 13

    name=ESPModul

    PRINT REQUEST ==================================
    ESPLOG:
    AT+CIPSTATUS

    STATUS:2

    OK
    AT+CIPSEND=155

    link is not vAT+CIPCLOSE

    ERROR

**UPDATE3**: This method is working

    void testHTTP()
    {
      Serial.println("Establishing TCP connection");
      espclient.println("AT+CIPSTART=\"TCP\",\"" + server + "\",5000");
      delay(1000);
      Serial.println("Sending out data…");
      espclient.println("AT+CIPSEND=16");
      espclient.println("GET / HTTP/1.1");
      espclient.println();
      espclient.println("AT+CIPCLOSE");
    }

If I connect the ESP to my PC with TTL adapter, and I write the commends manually, then its working fine. And yes, the ESP is connecting correctly to the wifi, I tested it.

The main solution was to put "`delay(1000);`" after "`CIPSEND=`".

I hope my fumbling can help to someone in the future.

title: Send data to API from Arduino with ESP8285 Strange Error

Answers: 0


body:
0

I wrote a code in the Arduino IDE. With this code, i can control 4 leds on and off from the web page. In the web page 9 buttons.

2 buttons for led-1 on and off. 2 buttons for led-2 on and off. 2 buttons for led-3 on and off. 2 buttons for led-4 on and off. 1 button for toggle all leds on and off.

I want also add a real button to the circuit. When i press this button, i want to run that toggle code. How can i do that?

This is my code;

    #include <ESP8266WiFi.h>

    const char* ssid = "UnderSpeed";
    const char* password = "q1w2e3r4t5__";
    const char* host = "192.168.1.185"; //it will tell you the IP once it starts up
                                            //just write it here afterwards and upload
    int r0 = D0;
    int r1 = D1;
    int r2 = D2;
    int r3 = D3;
    int btn0 = D5;

    WiFiServer server(301); //just pick any port number you like

    void setup() {
      Serial.begin(115200);
      delay(10);
    Serial.println(WiFi.localIP());
      // prepare GPIO2
      pinMode(r0, OUTPUT);
      pinMode(r1, OUTPUT);
      pinMode(r2, OUTPUT);
      pinMode(r3, OUTPUT);
      pinMode(btn0, INPUT_PULLUP);
      digitalWrite(r0, HIGH);
      digitalWrite(r1, HIGH);
      digitalWrite(r2, HIGH);
      digitalWrite(r3, HIGH);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a client has connected

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

      // Wait until the client sends some data
      while (!client.available()) {
        delay(1);
      }

      // Read the first line of the request
      String req = client.readStringUntil('\r');
      client.flush();

      // Match the request
      if (req.indexOf("") != -10) {  //checks if you're on the main page

        if (req.indexOf("/r0-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r0, HIGH);
          Serial.println("Relay-0 OFF");
        }
        if (req.indexOf("/r0-ON") != -1) { //checks if you clicked ON
          digitalWrite(r0, LOW);
          Serial.println("Relay-0 ON");
        }

        if (req.indexOf("/r1-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r1, HIGH);
          Serial.println("Relay-1 OFF");
        }
        if (req.indexOf("/r1-ON") != -1) { //checks if you clicked ON
          digitalWrite(r1, LOW);
          Serial.println("Relay-1 ON");
        }

        if (req.indexOf("/r2-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r2, HIGH);
          Serial.println("Relay-2 OFF");
        }
        if (req.indexOf("/r2-ON") != -1) { //checks if you clicked ON
          digitalWrite(r2, LOW);
          Serial.println("Relay-2 ON");
        }

        if (req.indexOf("/r3-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r3, HIGH);
          Serial.println("Relay-3 OFF");
        }
        if (req.indexOf("/r3-ON") != -1) { //checks if you clicked ON
          digitalWrite(r3, LOW);
          Serial.println("Relay-3 ON");
        }

        if (req.indexOf("/btn0") != -1) { //checks if you clicked OFF
          buton_islemi();
        }

      }

      else {
        Serial.println("invalid request");
       client.stop();
        return;
      }

      // Prepare the response
      String s = "HTTP/1.1 200 OK\r\n";
      s += "Content-Type: text/html\r\n\r\n";
      s += "<!DOCTYPE HTML>\r\n\r\n";

      s += "
<input type=\"button\" name=\"rly0-on\" value=\"Relay-0 ON \" onclick=\"location.href='/r0-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly0-off\" value=\"Relay-0 OFF\" onclick=\"location.href='/r0-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"rly1-on\" value=\"Relay-1 ON \" onclick=\"location.href='/r1-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly1-off\" value=\"Relay-1 OFF\" onclick=\"location.href='/r1-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"rly2-on\" value=\"Relay-2 ON \" onclick=\"location.href='/r2-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly2-off\" value=\"Relay-2 OFF\" onclick=\"location.href='/r2-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"rly3-on\" value=\"Relay-3 ON \" onclick=\"location.href='/r3-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly3-off\" value=\"Relay-3 OFF\" onclick=\"location.href='/r3-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"btn0\" value=\"Button-0 \" onclick=\"location.href='/btn0'\">";
      s += "
";

      s += "\n";

      client.flush();

      // Send the response to the client
      client.print(s);
      delay(1);
    }

    void buton_islemi() {
      digitalWrite(r0, !digitalRead(r0));
      delay(500);
      digitalWrite(r1, !digitalRead(r1));
      delay(500);
      digitalWrite(r2, !digitalRead(r2));
      delay(500);
      digitalWrite(r3, !digitalRead(r3));
      Serial.println("Button Pressed");
    }

title: Esp8266 Web based code and real button

Answers: 1

body:
Just add your button check into the section where you're not handling a client. For example:

    static uint8_t buttonState = LOW;
    if (!client) {

      uint8_t bs = digitalRead(BUTTON_PIN);
      if (bs != buttonState) {
        buttonState = bs;
        if (buttonState == HIGH) {
          buton_islemi();
        }
      }

      return;
    }


body:
I am doing a school project and wanted to implement HMAC on a arduino UNO like board. I have been testing the Cryptosuite, but none of the examples work for me. Such as this one: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde

This one https://github.com/simonratner/Arduino-SHA-256, a trimmed-down version, which sounds good but there's none working example.

Can any one point me to the right direction? Thanks a lot!!

title: HMAC SHA256 in Arduino use case?

Answers: 2

body:
When you are asking a question, here or on a forum, then please tell what you did and what the result was. When you say that it is not working, then we have not enough information and your question might not get answered.

I have tested the first link that you gave to [Cryptosuite][1]. It is outdated and needs to be fixed.
I renamed "hmacsha256test.**pde**" to "hmacsha256test.**ino**".
The compiler errors and warnings are in the lower part of the Arduino IDE. Scroll up to find the first problem and fix that. Repeat it until it works.

The `PROGMEM` requires that the 'const' keyword is used. For example in "sha256.cpp":

    const uint32_t sha256K[] PROGMEM = {

The 'write' function should return a `size_t` value.

In sha256.h:

    // virtual void write(uint8_t);
    virtual size_t write(uint8_t);

In sha256.cpp:

    size_t Sha256Class::write(uint8_t data) {
      ++byteCount;
      addUncounted(data);
      return 1;
    }

Then it compiles and runs on a Arduino Uno, although there is a warning for low memory because 75% of the sram is used.

The [second link][2] is a changed version of the same Cryptosuite. It should be able to use the examples of the Cryptosuite, but it does not.
I can make that work as well.

Using the same example of the Cryptosuite "hmacsha256test.**pde**" (I renamed it to "hmacsha256test.**ino**"), create a object 'sha' after including the "sha256.h":

    #include "sha256.h"
    Sha256 sha;

In the example, replace all "Sha256" function calls with "sha" function calls:

    sha.initHmac(hmacKey1,20);
    sha.print("Hi There");

Then it works as well.

  [1]: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde
  [2]: https://github.com/simonratner/Arduino-SHA-256

body:
I have used the [https://github.com/Cathedrow/Cryptosuite/][1] on ESP8266. For that in addition to the changes desribed by Jot it is enough to remove

    #include <avr/io.h>
    #include <avr/pgmspace.h>

from the header files. Then it is working fine.

  [1]: https://github.com/Cathedrow/Cryptosuite/


body:
I have recently purchased a ESP-8266 HUZZAH by adafruit. I'm kind of new to the whole arduino concept. I would like to know how I would be able to utilise this breakout board with my Arduino to do anything. I have searched on the internet and I know about flashing the board. However, I have no idea how to flash this device. Some help would be appreciated.

I also have no idea where to put my pins. I know that there are RX and TX pins on the UNO, but those are at 0 and 1. Most online guides are using something like 11/12 or 2/3.

[Here][1] is the link to the product website

Thanks,
Vraj

  [1]: https://www.adafruit.com/product/2471

title: HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3

Answers: 1

body:
Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.

    Arduino | HUZZAH ESP8266
    RX | RX (In the front)
    TX | TX (In the front)
    5V | V+ (In the front)
    GND | GND (In the front)

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. [This][1] is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.

To use NODEMCU LUA which it comes preloaded with, you need to refer to [this][2] guide.

The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github ([this][3] one).

The next step was to get the pin layout (from [here][4]). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page ([here][5]) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.

  [1]: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
  [2]: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-nodemcu-lua
  [3]: https://github.com/miguelbalboa/rfid
  [4]: https://github.com/miguelbalboa/rfid#pin-layout
  [5]: https://wiki.wemos.cc/products:d1:d1_mini


body:
Let's imagine I create this cool little Arduino-based (replace Arduino with any embedded system that's not a Raspberry Pi) object that does some interesting things but it needs an internet connection to retrieve some information. The object doesn't have an input interface for the user because it would be meaningless if not for the WiFi credentials insertion procedure. In my testing instance, I can just hardcode the credentials before flashing the firmware, but what if I wanted to make it a product and have every user set it up on his own network?

How was such a task handled in some commercial products with similar challenges? Or what would the best way of handling it be?

title: How would I give an Arduino-based product WiFi credentials?

Answers: 1

body:
Most WiFi chips/modules these days worth paying for can function both as a WiFi client or as an AP.

So, what you would do is when the device is unconfigured, put your WiFi module into AP mode, and serve up a lightweight webpage hosted from your device. The owner connects to the devices WiFi network, and accessing the device through that webpage, they can setup their wifi information. Once configured, you switch the WiFi back to client mode, and connect to the provided Wi-Fi network.


body:
The board is the RoMeo BLE V 1.0 and I have set the board to Arduino UNO on the board part of the arduino IDE, as I cannot find the RoMeo Board.

This is the code for the motors.

    ``int speedPin_M1 = 5;     //M1 Speed Control
    int speedPin_M2 = 6;     //M2 Speed Control
    int directionPin_M1 = 4;     //M1 Direction Control
    int directionPin_M2 = 7;     //M1 Direction Control

    void setup(){

    }

    void loop(){
        carAdvance(150,150);
        delay(1000);
        carBack(150,150);
        delay(1000);
        carTurnLeft(150,150);
        delay(1000);
        carTurnRight(150,150);
        delay(1000);
    }

    void carStop(){                 //  Motor Stop
      digitalWrite(speedPin_M2,0);
      digitalWrite(directionPin_M1,LOW);
      digitalWrite(speedPin_M1,0);
      digitalWrite(directionPin_M2,LOW);
    }

    void carTurnLeft(int leftSpeed,int rightSpeed){         //Turn Left
      analogWrite (speedPin_M2,leftSpeed);              //PWM Speed Control
      digitalWrite(directionPin_M1,LOW);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,HIGH);
    }

    void carTurnRight(int leftSpeed,int rightSpeed){        //Turn Right
      analogWrite (speedPin_M2,leftSpeed);
      digitalWrite(directionPin_M1,HIGH);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,LOW);
    }

    void carBack(int leftSpeed,int rightSpeed){             //Move backward
      analogWrite (speedPin_M2,leftSpeed);
      digitalWrite(directionPin_M1,LOW);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,LOW);
    }
    void carAdvance(int leftSpeed,int rightSpeed){          //Move forward
      analogWrite (speedPin_M2,leftSpeed);
      digitalWrite(directionPin_M1,HIGH);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,HIGH);
    }

After I upload the code, nothing happens. The boards light blinks and then after that nothing occurs. How do I get the Motors moving according to the code in the loop?

title: Motor code for the "Pirate: 4WD Arduino Mobile Robot Kit with Bluetooth 4.0", will not work

Answers: 1

body:
To formulate my comments as answer:

Your board has some features involving the motors/servos:

1. Since the PCs USB port cannot provide enough current for the motors, they can be switched off wit the Motor Power Switch. It has to be set to OFF, when you connect the board to an USB port. For operating the motors the board needs it's own power supply (a battery in your case), which can provide enough current. So in this case, you have to switch the Motor Power Switch to ON, to enable the motor drivers. **Attention:** If you turn on the motors while being connected to the USB port, you can damage your board and also your USB port.

2. The motors are connected to the pins 4, 5, 6 and 7. If you don't need the motors, you can use these pins for other purposes. For this, the board let's you disconnect the motor driver from these pins. If the jumpers, that are marked with "Motor Control Terminal Jumpers" in the image on [this documentation page][1], are inserted onto the jumper pin pairs (in the image they are already inserted), the motor drivers will be connected to the mentioned pins. If the jumpers are not inserted there, the motors will not work, since they are not connected to the controlling pins.

---

Note, that you need to use `pinMode(pin_number, OUTPUT);` in the `setup()` function for all pins, that you want to use `digitalWrite()` on, because only this way, the corresponding pin will be set to an output (can only then output a digital signal on `digitalWrite()`). `analogWrite()` will configure the corresponding pin for you, but it is a good practice to set it as OUTPUT in setup anyway, to make it clear for readers, that this pin is an output.

  [1]: https://wiki.dfrobot.com/RoMeo_BLE__SKU_DFR0305_


body: It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.  If that firmware is corrupted, the ESP8266 is dead.  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.  Does anybody know how to do that?  Thank you.

title: ESP8266 Bootloader Firmware (on the ESP8266)

Answers: 1

body:
> It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.

Indeed there is.

> If that firmware is corrupted, the ESP8266 is dead.

Well, if that firmware gets corrupted, then yes indeed the chip is dead. That's because the firmware is in ROM, not flash - and the only way it can get corrupted is for the chip to be physically damaged internally.

> I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.

No. They are SPI. SPI has nothing to do with flashing firmware. It just *happens* that AVR chips share the same pins as SPI for their debug protocol.

You cannot replace the bootloader on an ESP8266. It is in ROM. It's unchangeable - except as mentioned earlier by physical trauma to the silicon itself.


body:
I should mention that I didn't write this code but got it from [HERE][1].
```
#include<Servo.h>
Servo myservo; // create a servo object
int redled=13; // declare the pins
int greenled=12;

int servopin=9;
int trigpin=6;
int echopin=5;
float distance;
float duration;
int datapin=7;
int clockpin=8;
int latchpin=3;

void setup(){
  Serial.begin(9600);
  pinMode(redled,OUTPUT); // declare the pinmode
  pinMode(greenled,OUTPUT);

  pinMode(servopin,OUTPUT);
  pinMode(trigpin,OUTPUT);
  pinMode(echopin,INPUT);
  pinMode(datapin,OUTPUT);
  pinMode(clockpin,OUTPUT);
  pinMode(latchpin,OUTPUT);
  myservo.attach(servopin); // declare servo object is connected to servo pin

}

int ping() // create a function {
  digitalWrite(trigpin,LOW);
  delayMicroseconds(10);

  digitalWrite(trigpin,HIGH);
  delayMicroseconds(20);
  digitalWrite(trigpin,LOW);

  duration= pulseIn(echopin,HIGH);
  distance= duration*0.034/2; // distance is in cm
  return(distance);
  }

void loop() {
  myservo.write(90); // set servo at 90 degree angle
  float value;
  value=ping(); // call the ping function
  Serial.println(value);
  delay(100);
  if(value>20) {
      digitalWrite(redled,LOW);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000); // move the car in forward direction
      digitalWrite(latchpin,HIGH);
  }
  if(value<20&& value>15) {
      digitalWrite(redled,HIGH);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000);
      digitalWrite(latchpin,HIGH);
  }
    if(value<15) {
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // stop the car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // then again stop
      digitalWrite(latchpin,HIGH);
      delay(100);

      go(); // call go function
      delay(2000);
  }

  myservo.write(90);

}

void go() {
  int a;
  int b;
  myservo.write(0);
  delay(1000);
  a=ping();
  myservo.write(180);
  delay(1000);
  b=ping();

  if(a>b) {
   digitalWrite(redled,HIGH);
   digitalWrite(greenled,LOW);

   digitalWrite(latchpin,LOW);
   shiftOut(datapin,clockpin,LSBFIRST,B00010000); // move to the right side
   digitalWrite(latchpin,HIGH);
} else if(a<b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // move to the left side
    digitalWrite(latchpin,HIGH);
} else if(a=b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
    digitalWrite(latchpin,HIGH);
    delay(4000); // wait for 4 seconds
    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // then move to right direction
    digitalWrite(latchpin,HIGH);
    delay(2000);
  }
}
```
The error in full is:
```
sketch_may02a:31:3: error: expected initializer before 'digitalWrite'

   digitalWrite(trigpin,LOW);

   ^

sketch_may02a:32:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(10);

                    ^

sketch_may02a:34:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,HIGH);

               ^

sketch_may02a:35:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(20);

                    ^

sketch_may02a:36:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,LOW);

               ^

sketch_may02a:38:3: error: 'duration' does not name a type

   duration= pulseIn(echopin,HIGH);

   ^

sketch_may02a:39:3: error: 'distance' does not name a type

   distance= duration*0.034/2; // distance is in cm

   ^

sketch_may02a:40:3: error: expected unqualified-id before 'return'

   return(distance);

   ^

sketch_may02a:41:3: error: expected declaration before '}' token

   }

   ^

exit status 1
expected initializer before 'digitalWrite'
```

  [1]: https://create.arduino.cc/projecthub/Aritra_B/obstacle-avoiding-robot-car-b38334?ref=search&ref_id=robot car&offset=23

title: I've gotten an error telling me, "expected initializer before 'digitalWrite'"

Answers: 1

body:
Your function definition starts:

    int ping() // create a function {

Notice that the comment is inserted **before** the open curly brace. That means the curly brace is commented out. Move the comment to the end of the line, or move the curly brace to a line on it's own.


body:
I tried to test out this MD5 library (https://github.com/tzikis/ArduinoMD5 ) as a hash function on arduino uno.

What I have done is that I placed the MD5.cpp and MD5.h to the folder below:
C:\Program Files (x86)\Arduino\libraries\MD5

And launched arduino IDE 1.8.9 to test the example provided (https://github.com/tzikis/ArduinoMD5/blob/master/examples/MD5_Hash/MD5_Hash.ino):

```
#include <MD5.h>
/*
This is en example of how to use my MD5 library. It provides two
easy-to-use methods, one for generating the MD5 hash, and the second
one to generate the hex encoding of the hash, which is frequently used.
*/
void setup()
{
  //initialize serial
  Serial.begin(9600);
  //give it a second
  delay(1000);
  //generate the MD5 hash for our string
  unsigned char* hash=MD5::make_hash("hello world");
  //generate the digest (hex encoding) of our hash
  char *md5str = MD5::make_digest(hash, 16);
  free(hash);
  //print it on our serial monitor
  Serial.println(md5str);
  //Give the Memory back to the System if you run the md5 Hash generation in a loop
  free(md5str);
}

void loop()
{
}

```
However when run verify and compile, it works but got the warnings below:

```
...\sketch_may02a_MD5_test.ino.ino: In function 'void setup()':

sketch_may02a_MD5_test.ino.ino:15:51:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   unsigned char* hash=MD5::make_hash("hello world");

                                                   ^

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:
In static member function 'static void MD5::MD5Update(void*, const void*, size_t)':

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21:
warning: right shift count >= width of type [-Wshift-count-overflow]

  ctx->hi += size >> 29;

                     ^
```

I know little of c++, can anyone help to fix this? Thanks a lot!!

title: MD5 hash for Arduino Uno [-Wshift-count-overflow]?

Answers: 1

body:
> ....\sketch_may02a_MD5_test.ino\sketch_may02a_MD5_test.ino.ino:15:51: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

That is a flaw in the library. The author defined the function as taking a `char *` instead of a `const char *`.  You can ignore it, it's just a warning - however maybe raising the issue with the author could be a good idea.

> C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21: warning: right shift count >= width of type [-Wshift-count-overflow]

This one is a little more awkward.  The `size` variable is defined as type `size_t`.  That varies in length depending on the architecture the software is compiled on.  On the 8-bit Arduinos that's a 16 bit variable. On 32-bit Arduinos, like the Due, it's a 32-bit variable.

It is probable that the author developed the library using a 32-bit Arudino (or Arduino-compatible) device - in which case he would never see that warning (since 29 is less than 32).  However anyone that then uses an 8-bit Arduino gets the warning, and probably a corrupt hash.

However, it looks like it should only be a problem if `size` is too big - and it can't be on an 8-bit Arduino. So again you can ignore it, but the author should really be made aware of the issue.


body:
I have an array of numbers that will be subtracted from the ADC readings
of a 50 Hz sine wave. Using `Serial.begin(57600);`, I can only
output 25 samples per sine wave cycle, or about 1,250 samples per
second. my questions are:

 1. how fast the increent of array number moves with y++ in my int sinus[]? because when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)
 2. how to increase the speed the increment of y++ in my array?

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

    int sinus[] = {
        70, 72, 83, 92, 108, 132, 157, 182, 207, 230, 243, 255, 255,
        255, 250, 238, 217, 193, 169, 143, 118, 98, 88, 77, 72, 80
    };
    int dataSensor;
    int hasil[26];
    int datasensor2;
    int dataBaru;
    int x;
    int y;
    int intPin = 2;
    int output;
    int output2;
    int toggle;
    int toggle2;
    int z;

    void setup() {
        TCCR1A = 0b00000010;
        TCCR1B = 0b00011100;
        TCCR0A = 0;  //disable millis, delay and mciros
        TCCR0B = 0;
        ICR1 = 3200;

        Serial.begin(57600);

        pinMode(A1, INPUT);
        pinMode(A0, INPUT);
        pinMode(A2, INPUT);
        pinMode(intPin, INPUT);
        pinMode(9, OUTPUT);
        pinMode(10, OUTPUT);

        attachInterrupt(0, genJeah, RISING);
    }

    void genJeah() {  //intrupsi rising
        y = 5;
    }

    void loop() {
        dataSensor = analogRead(A0);
        toggle     = digitalRead(A1);
        toggle2    = digitalRead(A2);
        dataBaru = map(dataSensor, 0, 1023, 0, 255);

        for (x = 0; x < 25; x++) {
            hasil[x] = sinus[x];
        }
        // for (x=0; x<100; x++){

        output = sinus[y] - dataBaru;
        Serial.println(output);
        y++;
        if (y > hasil[26]) {
            y = 0;
        }
    }

title: How to increase the serial port's data throughput

Answers: 2

body:
If you are looking for throughput then stop sending the ASCII conversion of numbers and just send the numbers.
In other words, use `Serial.write()` rather than `Serial.print()`: you can send ~25k integers per second with a 52k baudrate.

As you are actually remapping the ADC output to a single byte, that means you can easily achieve a 48k/s throughput with this simple change.

If you are also looking for low latency please consider the USB connection is actually packet based, not stream based, which means you will receive the data in chunks, no matter how frequently you write. You can speed it up a bit flushing the channel, at the cost of throughput.

body:
> how fast the increment of array number moves with y++ in my int
> sinus[]?

Incrementing an `int` is fast enough. Even on a slowish Uno, `y++` will
take less than one microsecond to execute, so you can do it a million
times per second if you want...

> when i see on serial monitor with 52700 baudrate it can only show
> about 25 numbers per cycle (50Hz)

Your `loop()` is doing _more_ than `y++`, no it's no wonder it takes
more time!

There are two slow functions there:

* `analogRead()` takes about 110 µs

* `Serial.println()` is initially fast, but once the output buffer is
  full, it runs at the speed of the serial port.

The limiting factor here is `Serial.println()`. You are printing
4.6 bytes on average per sample (2.6 printable characters,
plus CR and LF). Each byte is worth 10 bits on the wire (one start
bit, 8 data bits and one stop bit). That is 46 bits per sample
at 57,600 bits per second. The ratio of these numbers gives the
1,250 samples per second you experienced.

> how to increase the speed the increment of y++ in my array?

It's very hard to answer this question because you did not explain what
you are actually trying to achieve. If I naively take the question at
face value, the simplest option is to just repeat `y++` several times
per loop iteration:

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

    y++;
    y++;
    y++;
    y++;

This can obviously be optimized into

    y += 4;

and the compiler may even be able to figure out this optimization by
itself.

But maybe what you don't care so much about speeding up `y++`, and
instead you want to process more data samples per second? If this is the
case, then you can speed up the loop by speeding up the serial port:

    Serial.begin(115200);

by printing only every other sample (or one sample every _N_):

    static bool print_this_sample;
    if (print_this_sample) {
        Serial.println(output);
    }
    print_this_sample = !print_this_sample;

by printing one sample every so often:

    static uint32_t last_print_time;
    if (millis() - last_print_time >= PRINT_PERIOD) {
        last_print_time += PRINT_PERIOD;
        Serial.println(output);
    }

by printing the samples in binary (first make sure they fit in a byte):

    Serial.write((byte) output);

Now, what _I_ suspect, is that you actually want to get your processing
synchronized with the 50 Hz mains. If this is the case, you will
have to completely rethink your program, and reason about the timings:
at what specific time do you want to take each sample? The Arduino
timing functions (`millis()` and `micros()`) should help.

As you see, half of this answer is me making guesses about what you may
want to achieve. This is a sign of a _very badly_ written question.
Normally it is your job to explain that in detail. Please, rewrite the
question and provide all the necessary background to help us understand
your project, and the difficulties you are facing.