text:
Using Youtube API with ESP8266 = redirection problems
I am using ESP8266 programmed from Arduino to get data from the Google Youtube API. API, of course, works great in a browser using URL:
https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

The problem is that "gooogleapis.com" is not the location where from I would receive the answer to my HTTPS request, it comes from a different location. When above URL is entered, it is being redirected and request answer comes from another location.
So what happens on ESP8266 when I try to open that address(of course, with added proper channel ID and google key) is following:
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Content-Length: 1580
Date: Sun, 12 Mar 2017 14:40:18 GMT
Alt-Svc: quic=":443"; ma=2592000; v="36,35,34"
Connection: close

<!DOCTYPE html>

  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>

404. That’s an error.

The requested URL /youtube/v3/channels was not found on this server.  That���s all we know.
Done.

Which is the Google error page(you seen it!). This is my Arduino code:
#include "ESP8266WiFi.h"
#include <WiFiClientSecure.h>

const char* ssid     = "SSID";  // WiFi network name
const char* password = "pass"; // WiFi pass

const char* host = "googleapis.com"; // page I am trying to load
const char* fingerprint = "22 37 4D 58 43 F4 A1 24 12 71 2B 74 7A FC 36 FC 24 A0 F0 9D";

String ch_id = "CHANNEL ID";
String api_key = "API KEY";

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

  WiFi.begin(ssid, password);

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

  Serial.println("Connected to WiFi! Local IP address is: ");
  Serial.println(WiFi.localIP());

  WiFiClientSecure client;
  if (!client.connect(host, 443))
  {
    Serial.println("I am unable to connect to that page.");
    return;
  }

  if (client.verify(fingerprint, host)) {
    Serial.println("certificate OK");
  } else {
    Serial.println("certificate NOT OK");
  }

  String url = "/youtube/v3/channels?part=statistics&id=" + ch_id + "&key=" + api_key;

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  while (client.available()) {
    String linija = client.readStringUntil('\r');
    Serial.print(linija);
  }

  Serial.println("Done.");
}

void loop() {
}

How to find out to which site I am redirected?
How to read that from ESP8266 and redirect the same data to new site?

404 is not a redirect. You should get a 302 or 301. In that case there will also be a Location: header that contains the new URL.

In your browser you used www.googleapis.com, but in your code you used googleapis.com.
https://googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

returns a 404 page.
Add www. to your host in code.

Perfect! Can't believe I missed something so trivial. Thank you very much - works now.


text:
Don't Print After decimal point in
In my code, I have  float Hz = 0.00; I want to display values to my user in RPM as
Serial.print("Speed = ");
Serial.print(round(Hz*60);
Serial.println(" RPM);

The only hangup is that this displays as Speed = XX.00 RPM is there an easy way to get the Arduino to only print out Speed = XX RPM?

From the documentation:
Serial.print(round(Hz*60), 0);

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
SdFat library Change output style of sd.ls(LS_R)
I'm using the SdFat Library's sd.ls(LS_R) function to give me a serial output stream of all files on an SD card. My issue is that I would like to have it use a different character than '\n' at the end of each line as I'm using it as a termchar for my overall comms protocol. How can I get it to print a : or (another symbol that doesn't appear in file names) instead of a \ln

I am currently trying to have fun Modding my own sd.ls().
Worst way, modifying the library:
Go into FatFilePrint.cpp
(Suggestion: Create yourself a new 'flag' like LS_COMMA)
Find the line
void FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { ...

add your flag
if (flag & !LS_COMMA) {
   pr-->write(':');
} else {
    //original library set of
    // pr->write(stuff);
}

--> SuperClass version # (prefered )
this will override the original ls() method by creating a new Class inheriting from the original one.
rather then invoking it from "volume",
    sd.ls( your params);
invoke it from a directory file instead.
superFatFile rootDir;
rootDir.open("/");
rootDir.ls( __your_params__);

Place this superClass declaration in your .h
don't hesitate to remove any of the "flags" related code if YOUR requirement never calls for them.
class superFatFile : public FatFile {
    public:
    void ls(print_t* pr, uint8_t flags /* = 0 */, uint8_t indent /* = 0 */){
        superFile file;
        rewind();
        while (file.openNext(this, O_READ)) {
            if (!file.isHidden() || (flags & LS_A)) {
                // adds 'spaces' indent for dir level
                for (uint8_t i = 0; i < indent; i++) {
                    pr->write(' ');
                }

                if (flags & LS_DATE) {
                    file.printModifyDateTime(pr);
                    pr->write(' ');
                }

                if (flags & LS_SIZE) {
                    file.printFileSize(pr);
                    pr->write(' ');
                }

                // prints filename
                if (!file.isDir()) {
                    file.printName(pr);
                    pr->write('\r');
                    pr->write('\n');    // HERE IS YOUR SEPARATOR CARACTERS !!!
                }

                // execute recursivly if LS_R flag was set
                if ((flags & LS_R) && file.isDir()) file.ls(pr, flags, indent + 2);

            }

        }
        file.close();
    } // end of new LS method
}; // end of superClass

Nice,
I ended up changing my termchar

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
SD Library Print Full File/Folder name
Right now I have the following code for the Arduino SD Library
#include <SPI.h>
#include <SD.h>

void printDirectory(File dir, int numTabs)
{
  while (true)
  {
    File entry =  dir.openNextFile();
    if (! entry)
    {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++)
    {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory())
    {
      Serial.println(':');
      printDirectory(entry, numTabs + 1);
    }
    else
    {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.print(entry.size(), DEC);
      Serial.println(":");
    }
    entry.close();
  }
}

My hangup is that for file or folder names of 9 or more characters I get back char56~1.TXT How can I get the full name of the files and folders?
Also, What is the best way to, instead of printing to the serial port, only print trees that have a .TXT (or .CSV ) extension?

8.3 filenames and the FAT file system are the only type of filenames supported by the SD library.
https://en.wikipedia.org/wiki/8.3_filename
You can use the SdFat library. It supports long filenames.

Ok! I'll use it. Are there any examples of how to do a recursive file/folder list with the SdFat library? Or would this code still work?

Just see the github page...


text:
Attiny85 not recognized at windows startup
I'm using an Attiny85 to interact with a computer using an USB connection, and everything works fine except when I restart my computer and the Attiny85 is connected. When Windows end to boot up the Attiny85 isnt't recognized, and on Device Manager it's listed like this:

If I unplug the Attiny85 and then plug it back in, everything works just fine.
Is there any to make it detectable at boot time without having to always unplug/plug it?
EDIT:
More details:
I'm using this board

and libusb-win32 as the USB driver

The ATTiny doesn't really do USB. Making it interface with a USB port using something like V-USB is a hack at best. You shouldn't expect it to work properly in all respects.

You could use an oscilloscope and/or a USB protocol analyzer to find out what exactly V-USB does wrong, but in any case such a hacky software emulation cannot be fixed. Better use a microcontroller that actually supports USB (e.g., a Teensy).

Added more details (board and USB driver) to help in problem analyis

I don't have enough reputations to make a comment so I will drop my 2 cents here.
There should be more elegant way to do this but as a fast solution I would recommend two things:

If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.
You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.

I can't use the button idea because the board will be inside a case, and it wouldn't be practical.
The idea about the watchdog timer won't work because the board is always connected, so when the PC is off I would be executing the reset procedure at every 10 seconds, and I don't know if it would "like it".

@GonçaloCardoso Regarding watchdog timer, you can use watchdog timer just one time. You can handle this in your code.

But at what time would that be?

@GonçaloCardoso The time completely depends on your application. To perform a software reset one time look at this link.

The problem is that I need to make the restart when Windows boots up, and I haven't managed to find a way for the board to detect it.

@GonçaloCardoso When PC is off there should be no supply at USB port. After powering up the PC your board is going to be supplied and here where you start the timer to get the MCU reset. The time should not be too long because if you plug in your board while the PC is running the board is going to start working after the time you had already set. As I told you in my answer, it is not a perfect solution and I don't know if you can manage to place a push button on your board case. Otherwise you have to dig into the V-USB code and hope that you find a way to get the job done.

@GonçaloCardoso By the way I have an idea that should work for you. Try to disable the power saving options for USB devices and then reboot and see whether it works or not. Look at this link.


text:
ESP8266 Websocket issue
I realize it might be dumb question, but I've been at it for a few hours and I'm going nowhere. I am trying to figure out the standard Websocket library, however I have an issue casting the uint8_t to a String, so I can work with it easily, how do I do that and is it even possible? What I want to do is, get the payload from the main function as shown in the standard library and give it as a parameter to a function I have. This is the part I need, this is part of the switch statements in the standard library.
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

   switch(type) {
     case WStype_DISCONNECTED:
     Serial.printf("[%u] Disconnected!\n", num);
   break;
   case WStype_CONNECTED:
    {
      IPAddress ip = webSocket.remoteIP(num);
      Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

      // send message to client
      webSocket.sendTXT(num, "Connected");
    }
   break;
   case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\n", num, payload);
      move(payload);

Yes, I have. I have tried with.
String text = String((char *) &payload[0]); and just String text = String(payload);  and other ways of trying, this wasn't the first place I stopped at.

you can't cast it. payload is an array of received bytes and length is the size of received data in that array. if the bytes are characters and you would know that there is one more position allocated in that array, you could put a 0 to payload[length] and by cast to char* it would become a zero terminated string. but you can't know if there is that one byte allocated, so you must copy the payload to your buffer of chars and set a zero at the end.

Thanks, ended up doing this:
char clientCommand[length];             for (uint8_t i = 0; i < length; i++) {                 clientCommand[i] = payload[i];             }             clientCommand[length] = '\0';             Serial.print(clientCommand);


text:
LED and MOTOR "ON" when A BLE DEVICE APPROACH ESP32 MICROCONTROLLER DFR0575
I have this code that is working perfectly but I want my device to start vibrating too (right now only the led is working)
On a Wemos Battery Module I have simply connected the vibration motor on the same PIN of the LED and it works perfectly.
Now I want to do the same on an Beetle ESP32 Microcontroller DFR0575. I used the same code But I can't make the module vibrating (The led light is working perfectly)
this is the code:
 #include <BLEAdvertisedDevice.h>
   #include <BLEDevice.h>
   #include <BLEScan.h>

   const int PIN = 2;
   const int CUTOFF = -50;

   void setup() {
     pinMode(PIN, OUTPUT);
     BLEDevice::init("tkr");
   }

   void loop() {
     BLEScan *scan = BLEDevice::getScan();
     scan->setActiveScan(true);
     BLEScanResults results = scan->start(1);
     int best = CUTOFF;
     for (int i = 0; i < results.getCount(); i++) {
       BLEAdvertisedDevice device = results.getDevice(i);
       int rssi = device.getRSSI();
       if (rssi > best) {
         best = rssi;
       }
     }
     digitalWrite(PIN, best > CUTOFF ? HIGH : LOW);
   }

Are you connecting the vibration motor directly to a digital output pin? Or are you using some kind of driver (for example a transistor)?

In Wemos Battery Module I connect the vibration in the digital output pin. But the same things does not work on the Beetle ESP32 Microcontroller DFR0575 I don't know why..

What type of Battery Module do you have? Can you provide a link? Googling, I found different battery shields for the Wemos. Please also say, to which pin you connected the vibration motor exactly on both boards.

Wemos Battery Module (https://www.amazon.com/gp/product/B07M9X7HS6/ref=ppx_yo_dt_b_asin_title_o08_s00?ie=UTF8&psc=1) connected on PIN 16 Working ---- Beetle ESP32 Microcontroller DFR0575 connected on PIN 2 NOT WORKING

why are you asking this question again? .... edit your original question with additional information instead of reposting ... https://arduino.stackexchange.com/questions/68964/vibration-and-led-light-on-ble-approach

It is generally very dangerous to drive any motor directly from a digital output pin. Motors often need way more current, than the digital pin can provide. Based on the answer to this question, an ESP8266 can provide 20mA or 12mA depending on current direction (may be a bit different for an ESP32, but not substantially). Drawing more current, than the pin can provide, can lead to the destruction of the output hardware of the pin. It is not easy to say, when this will happen, because it depends not only on the current draw, but also on time and fabrication variation.
Also a motor is an inductive load, which means, that fast changes (for example turning on and off) will induce a reverse voltage in the motor coils. These can easily be very high relative to the supply voltage and thus destroy you output pin or even the complete microcontroller.
I cannot give you a full reasoning, why it works with the first board, but not with the second. I think, it has to do with the above.
You should always do 2 things, when driving motors with a microcontroller:

Use a motor driver circuit: You can either buy a ready to use motor driver or you can build one yourself. If you only want to turn the motor in one direction (as with a vibration motor), all you need is a MOSFET, which will act as a switch between the motor and the power supply. This switch get's controlled by the Arduino's output pin (which only needs to supply a very low current for switching). You can google "MOSFET as a switch". Be sure to use a MOSFET, that can provide the needed current and that is good in saturation for the used gate voltage (the working voltage of the microcontroller).
Use a flyback diode: The reverse induction voltage can also hurt MOSFETs. You want to let these voltage spikes quickly plenish by letting the current flow to ground. You can do this with a flyback diode. That is a diode, that bridges drain and source of the MOSFET. It is oriented so that block for normal operation (the normal positive supply voltage). When the MOSFET get's turned off, a great negative voltage will build up in the motor, but since the diode is conducting in this way, the voltage will safely flow to ground, so that the induction voltage cannot hurt the other electronic parts.

Thank you very much i'll try. the only problem I have is that I found a lot of Mosfet on amazon but i don't know what to buy.

I need something very small...

You already have to categories, where the MOSFET has to fit in: You search a MOSFET which can conduct some hundred mA (depending on your motor, you may just measure the real value) without a headsink (which means the maximum current has to be clearly above this value). Also it's threshold voltage should be clearly less than 3.3V (which is the voltage of ESP boards). And it should be small, so a SMD part is the best fit. Just use one with these conditions.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Multiple definition of "..." Compiler Error
I am creating a simple library to test how multiple files in an Arduino program works. I have three files. MotorController.ino:
#include <motor.h>

void setup() {
   motorInitialize();
}

void loop() {

}

motor.cpp:
#include "motor.h"

void motorInitialize() {

  for (int i = 0; i < 4; i++) {
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
  }
  delay(1000);

}

and motor.h:
#ifndef _motor_h_
#define _motor_h_

#include "Arduino.h"
#include <Servo.h>

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

void motorInitialize();
#endif

When I try to compile the program, I get the error:
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor1'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor2'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor3'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor4'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motorArray'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

I have read similar posts on this issue, but none of the solutions seem to work for me. I've followed the instructions on the Arduino website on how to create a library, and that doesn't seem to resolve this issue.

Although the motor (global) variables are defined in a header files, they are included in both cpp files, thus defined twice.
Make them extern, and than define them in the motor.cpp file.
In motor.h, change
Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

to
extern Servo motor1, motor2, motor3, motor4;
extern Servo motorArray[4];

In motor.cpp, add:
Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

As a side note, use consts for values 4 and 2000.

Isn't #ifndef _motor_h_, #endif wrapping suppose to help you with double definitions?

@machineaddict It helps to prevent including a header file twice when compiling a c or cpp file, but it does not help when compiling two different c or cpp files. What is happened: file a.cpp is compiled (to e.g. a.o), and b.cpp is compiled to b.o. Than in the linker a.o and b.o both contains the same variable if defined in the .h file included by both and an error is shown.

I see. Thanks for the explanation!

@machineaddict You're welcome

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Sampling/transmission limits for USB and Arduino UNO R3
I'm very new at this and I need some help. This is a college project that I must do and not even the professor knows for certain if it is possible.
I have to sample two signals at a fixed sampling rate so there is no aliasing effect and it must be done at the same time (switching the ADC from one analog input to another)..
The signal would be then transmitted via USB to my computer. I guess that the transmission rate would be too slow to do this in real time. I will have to store this somewhere in the Arduino board so it can be transmitted afterwards.
Requirements:

It could be done with 8 bit resolution.
Sampling rate of at least 4.8kHz.
Record both signals for at least 0.1 second.

Is this even possible to do with my Arduino UNO R3? If it isn't, it would be with a sampling rate of 1.2kHz?
PS: I could try to lower the sampling frequency necessary by changing the aliasing filter that I built. The theoretical limit would be at about 1.2kHz for the best filter possible.

You can make the arduino sample faster and use a fast enough serial link. For instance setting the prescaler to the value like in the linked post will give you 16us per analog read. You call the two analogread one after the other (32us), then send both data through the serial interface at 512kbps. For instance, if you send 3 bytes (one to sync, the other with the data) you will spend around 58us in the sending. Total: 90us. To achieve a 4.8kHz sampling rate you need to repeat sampling every 208us, so you have time for calculations too

While this probably can be done on an ATmega328p + serial converter classic arduino, it may in practice be simpler with an ARM-based board having a faster ADC, more speed and resources, and native USB.  The advantage of the ATmega solutions is their ubiquity and wide collection of code that works "well enough" for many needs.  There's no actual cost advantage when considering comparable suppliers.

It is not possible to sample two signals at the exact same time with an
Arduino Uno. The Arduino has only one ADC, so you have to sample one
signal, switch channels, sample the other, switch channels again, etc.
If this is acceptable for your project, then yes, it is perfectly
feasible with an Arduino Uno. But you will have to dig into the
datasheet and program the ATmega328P low-level.
Regarding the sampling rate, you want the ADC to take 9600 samples
per second (4.8 kS/s × 2 channels). This means one sample
every 104 µs. You are lucky: in the default Arduino configuration,
the ADC conversions take exactly 104 µs. frarugi87 and Jot suggest
you reconfigure the ADC for faster sampling. This is useless: the
default sampling speed is already optimal for you application. Leave it
as is.
You also require a fixed sampling rate. This is not possible to do
with software. Configuring the ADC in auto trigger mode is the only
way to get a really steady rate. The ADC can be triggered by a timer,
but in your particular case, it is just simpler to have it trigger
itself. This is called free running mode and it gives a sampling rate
of exactly one sample every 104 µs. Perfect for your application.
Jot also suggests disabling interrupts. Do not do that! Interrupts are
harmless because the ADC manages its own timing. And they are actually
useful: I would use the ADC interrupt to retrieve the conversion result,
send it through the serial port and switch channels in the multiplexer.
If you are happy with 8-bit resolution, I recommend you enable the left
adjust result mode. This way you can retrieve the 8-bit result from the
ADCH register and you won't need to do bit shifts.

I guess that the transmission rate would be too slow to do this in
  real time. I will have to store this somewhere in the Arduino board so
  it can be transmitted afterwards.

Both options are possible. If you send the data in binary, you will need
a baud rate of at least 9600 bytes/s × 10 bits/byte
= 96 kb/s. You can opt for 115.2 kb/s, which is standard
and widely supported. If you want to store the data, then you will need
9600 bytes/s × 0.1 s = 960 bytes, or about half
the Arduino RAM. This is fine, as the program can be quite simple, so it
won't need more than half the available RAM.
Just to give you some inspiration, I suggest you take a look at this
sound-meter
sketch of
mine. It configures the ADC in free-running mode at 9.6 kS/s and
retrieves the result using the ADC interrupt. I would use the same ADC
configuration for your project, only with left-adjust and with channel
switching performed by the interrupt handler.

Edit: I just wrote a “dual channel oscilloscope” program along the
lines of this answer: dual-scope.c. It's written in plain C, but it
can also be compiled as a regular .ino file. I only tested it with
constant voltage inputs though.
The program ended up being tiny: it uses about 1% of the flash, 1.4% of
the RAM and 3.4% of the CPU power on an Arduino Uno. Meaning you could
add stuff to it if you feel so inclined.

Are you sure that you can achieve this rate with the stock software when switching channels and never be delayed in switching by a timer interrupt being in progress at the key time?  If the ADC block can handle the channel switching automatically, the answer may be yes, if not, the answer is no, and those ideas you are dismissing as "useless" may actually be required.

@ChrisStratton: Yes, I tested it, it works. When the ADC finishes the (n)-th conversion, it triggers ISR(ADC_vect) and immediately starts the (n+1)-st. In the ISR, you process that (n)-th reading, and you set the MUX for the (n+2)-nd conversion. The trick is: the ADC ignores the new MUX setting until it is ready to start a new conversion. I will shortly upload a program demonstrating the approach.

Could ISR_NAKED be used ? Perhaps asm code is needed to prevent that unknown local/register variables are used.

@Jot: Yes, you could use ISR_NAKED, and that would save a few bytes of flash and RAM, and about 1.9% of CPU power. But then the ISR would clobber some CPU registers. That would be OK with the program as it is, since outside the ISR it does nothing but sleep, but it would be problematic as soon as you add code to the main loop. And no, you cannot avoid clobbering registers: it's a load/store architecture.

The Arduino Uno uses a slow 8-bit microcontroller ATmega328P. The Due, Zero, M0 boards use a faster processor.
However, the ATmega328P microcontroller has many option for sampling analog data. It can easily do what you want. It's all in the datasheet.
The Arduino functions are often slow. For example the analogRead uses 112µs. For two channels you might get near the 4kHz with some luck.
I suggest to write a sketch that reads two channels and stores the data, and see how fast it will be. Note that the Timer0 interrupt will happen during that time. Arduino uses Timer0 for millis. You could disable the interrupts with noInterrupts.
After that, try the prescaler option as mentioned by @frurigi87. It seems to be an easy way to get a higher sample rate.
The next option is to write your own code and use the registers directly. There is code to make a simple oscilloscope with a high sample rate that you can use as an example. For example at avrfreaks.net, click on "projects" and search for "oscilloscope".


text:
Function pointer or abstract class?
I need to implement callback in my C++ library. The "proper" C++ way of doing it would be to create an interface (or pure abstract class) and pass it to interested party. I'm wondering though, would that be optimal?
My analysis:

Function pointer - occupies 2 bytes in memory (+code of function)
Class derived from abstract one - occupies 2 bytes in memory PLUS 2 bytes for VMT (since we have derived method) PLUS size of VMT table (if any) (+code of method).

Is optimizer smart enough to compile abstract class with single method as method pointer? Which solution is more optimal in regard of memory and speed? Is my analysis correct?

You have to choose between size optimization and usability/readability. With a virtual method, you can encapsulate data with the actual code, at the size cost you mentioned. The response will actually depend on how much size you have for your project?

Regarding your optimizer question, it would be better to ask this to GCC people as it is certainly not specific to Arduino.

Sometimes you want your callback to be fed some data that you provide
when you register that callback. Here is a very common callback pattern
in plain C that does that:
// The API:

typedef void (*callback_t)(void *data);
void register_callback(callback_t callback, void* data);

// Usage:

typedef struct {
    // stuff only the user of the API knows about.
} my_data_t;

void my_callback(void *in_data)
{
    my_data_t *data = (my_data_t *) in_data;
    // do something with data->foo, data->bar...
}

// ...somewhere else:
my_data_t my_data = { stuff... };
register_callback(my_callback, (void *)&my_data);

The problem is: it's clumsy. C++ classes allow you to pack together the
code (the callback function) and the data it needs. Thus, if in your use
case you need to pass data to the callback, by all means use a C++
class. It will make your life easier and you are unlikely to even notice
the memory overhead.
However, if you only need to pass a function, with no attached data,
then a plain function pointer would be both easier for the API user and
optimal memory-wise.

The best way is to find out yourself, there are memory 'debug'  functions to show the amount of free memory, so if you do some tests you know for sure what the compiler optimizes.
See e.g. AvailableMemory library.
It might be quite hard to exactly calculate and predict the optimizer. However, is it really needed to optimize? Mostly it is best to not optimize before knowing it is really necessary.


text:
Wifi module is not sending the data properly
I wrote a programm in c++ for Arduino Uno which is connected to a wifi module (ESP8266) and sends the calculated data to a server through wifi-Module with a http post request.
The problem is that the programm sends the data only 2 times throuth http and then it stops. I mean it goes to the loop but the http-send-request is not successful.
here is my program:
#include <MySignals.h>
#include "Wire.h"
#include "SPI.h"

unsigned long currentMillis;

const unsigned long period = 10000;

int a=1;

void setup()  {

Serial.begin(115200);

MySignals.begin();
 void httpBase(int); //Enable WiFi ESP8266 Power -> bit1:1           >      bitSet(MySignals.expanderState, EXP_ESP8266_POWER);
 MySignals.expanderWrite(MySignals.expanderState);

 MySignals.initSensorUART();

 MySignals.enableSensorUART(WIFI_ESP8266);   delay(1000);

// Checks if the WiFi module is started   int8_t answer =
sendATcommand("AT", "OK", 6000);   if (answer == 0)   {
MySignals.println("Error");
// waits for an answer from the module
while (answer == 0)
{
  // Send AT every two seconds and wait for the answer
  answer = sendATcommand("AT", "OK", 6000);
}   }   else if (answer == 1)   {

MySignals.println("WiFi succesfully working!");

if (sendATcommand("AT+CWMODE=1", "OK", 6000))
{
  MySignals.println("CWMODE OK");
}
else
{
  MySignals.println("CWMODE Error");

}

//Change here your WIFI_SSID and WIFI_PASSWORD
if (sendATcommand("AT+CWJAP=\"********\",\"****\"",
"OK", 20000))
{
  MySignals.println("Connected!");
}
else
{
  MySignals.println("Error");

}   }

 }

void loop()  {

delay(10);  // wait for a second

a=a+1;

httpBase(a);

 }

 void httpBase(int gsr) {

 String data="value1="+String(gsr); //String
 data="a="+String(gsr);
 String postString="POST /ardu.php HTTP/1.1\r\nHost:
 192.168.178.36\r\nContent-Type: application/x-www-form-
 urlencoded\r\nContent-Length:
 "+String(data.length())+"\r\n\r\n"+data+"\r\n"; char* post = new
 char[postString.length()+1]; strcpy(post,postString.c_str());

 String inf = "AT+CIPSEND="+String(strlen(post)); char *info = new
 char[inf.length() + 1]; strcpy(info, inf.c_str());

 delay(1500); sendATcommand("AT+CIPMUX=0", "OK", 3000);

 //sendATcommand("AT+CIPSERVER=1","OK",1000);

 sendATcommand("AT+CIPSTART=\"TCP\",\"192.168.178.36\",80", "OK",
 2000);

 sendATcommand(info, "OK", 2000); sendATcommand(post, "OK", 2000);

 sendATcommand("AT+CIPCLOSE", "OK", 3000);

 delay(10000); }

int8_t sendATcommand(char* ATcommand, char* expected_answer1,
unsigned
int timeout) {

uint8_t x = 0,  answer = 0;   char response[500];   unsigned long
previous;

memset(response, '\0', sizeof(response));    // Initialize the
string

delay(100);

while ( Serial.available() > 0) Serial.read();   // Clean the
input
buffer

delay(1000);   Serial.println(ATcommand);    // Send the AT   command

 x = 0;   previous = millis();

 // this loop waits for the answer   do   {

 if (Serial.available() != 0)
 {
  response[x] = Serial.read();
  x++;
  // check if the desired answer is in the response of the module
  if (strstr(response, expected_answer1) != NULL)
  {
    answer = 1;
    //MySignals.println(response);

  }
}
// Waits for the asnwer with time out   }   while ((answer == 0) && ((millis() - previous) < timeout));

 return answer; }

the output is:
AT
WiFi succesfully working!
AT+CWMODE=1
CWMODE OK
AT+CWJAP="*******","******"
Connected!
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=127
POST /ardu.php HTTP/1.1
Host: 192.168.178.36
Content-Type: application/x-www-form-urlencoded
Content-Length: 8

value1=2

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=127
POST /ardu.php HTTP/1.1
Host: 192.168.178.36
Content-Type: application/x-www-form-urlencoded
Content-Length: 8

value1=3

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=127
POST /ardu.php HTTP/1.1
Host: 192.168.1
⸮⸮6⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
AT+CIPSEND=1
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
2

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
2

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80
⸮
⸮
AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE
AT+CIPMUX=0
AT+CIPSTART="TCP","192.168.178.36",80

AT+CIPCLOSE

....

what is MySignals.h?

is a plattform which contains sensors.

reduce your code to send and receive a single byte ... was that successful?

don't use String class https://majenko.co.uk/blog/evils-arduino-strings

void httpBase(int); does not ake sense, it's a funcrion declaration instead of a function call.

Hello Navid and welcome to the community. Buddy your code is extremely hard to read.
Now let me see if I can help you archiving your goals. First of all try not to use AT commands at all, you have an ESP8266, that's not just a Wi-Fi module but also a really good micro controller you can actually use, code for it (even using Arduino IDE). I would HIGHLY suggest you to use it if you wanna do POST and GET methods. AT commands do work, but they are not as reliable as they should be, and with your code written in that format, its going to be difficult to help you buddy.
Now if you are calling it a Wi-Fi "Module" I can presume it's a ESP01 you are talking about (those ESP8266 with no usb connection), you can find on the internet a few tutorials on how to upload code to them using your arduino uno's FTDI chip (basicly grounding the reset pin of your Arduino).
With that been said, hopefully you can split your code into those 2 micro controllers if you really need to use the Arduino uno, and do a few functions to trigger based on Serial communication on both sides. I know it sounds a lot of work, but trust me, that's by far the easiest and more reliable solution you will find.
And let me give you an bonus tip, next time you wanna work with Wi-Fi applications, get yourself a Wemos D1, they are small easy to use, reliable, have GPIO's as well as ADC and PWM pins, you can pretty much put your Arduino on a shelf for 4 dollars.
And please remember Navid, code syntax is really important.


text:
arithmetic operation outcome differs from the expected outcome
I am writing a function
void Sound_Play(int frequency,int millisec)

A part of this function is:
  counting=(millisec*frequency/1000);  //counting is type int
  Serial.println((String)"millisec="+millisec+" frequency="+frequency+" (millisec*frequency/1000)="+(millisec*frequency/1000)+" counting set to="+counting);

But when I call the function with millisec=500 and frequency=220, the result on the Serial Monitor is:
millisec=500 frequency=220 (millisec*frequency/1000)=-21 counting set to=-21

Shouldn't counting should be 110 instead.I tried casting the result to int but in vain. What am I doing wrong and how to correct it?
Thanks!
Bhuvnesh

Once again an example to Why should I learn C/C++ first before learning Arduino.
The main point here is: know your data types.
Your calculation millisec*frequency/1000 would work if it was a compile time constant that is evaluated by the pre processor. In any other case this is a runtime value and so the limitations of the datatype apply.
Unless stated otherwise I assume your variables millisec, frequency and counting are of type int. int has a platform specific width. On Arduino this is 16-bit. (Other platforms have other widths)
It is also signed, that is why it can hold values between -32768 and 32767.
You calculation millisec*frequency evaluates to 500 * 220 = 110000 which is many times larger than the value that can be represented.
You can do two things:

Use long which is 32-bit on Arduino. But actually I'd prefer to use a type with an obvious width. As you don't seem to need negative values I'd prefer uint32_t.
If milliseconds is a constant, you can make it smarter by reducing your calculation to a division by two (or better a single right shift).

Thankyou for your Answer. I was a bit distracted could not see the fact that you mentioned. Changing millisec and frequency to type long solved the issue

You forgot the negative  sign in the range for int. Otherwise great answer. Upvote


text:
GSM+GPS modules
Say, I need to track a vehicle using Arduino and a (GPS+GSM) module.  Though GPS can be used to get Location of the Vehicle(and then sent using GSM), why would we even do it using GPS if we already have a GSM module. Can't GSM do both these tasks(getting location and sending it) . What's the use of using an extra module there?
I am new to network stuff, help me!

Only a few GSM modules also include a GPS module. Without that all you could possibly get is the cell ID, which is pretty pointless.

Did you mean that GSM technology alone cannot find out its location?

That is correct. GSM can only get you the cell ID (rough location) and signal strength (could be used to approximate distance from tower?) It certainly can't get you a lat/long. Only a "You're in the south west of Fort Worth"...

Well thanks! That answers my question!

The GSM module can estimate it's location based on cell tower triangulation but if you want a more accurate location then you need to use a GPS.


text:
Piezo buzzer not sounding well with ATmega328
I am using an ATmega328 to drive a 16x2 LCD, a LED, and a piezo buzzer. Piezo buzzer needs to buzz after every 5 seconds. But it doesn't make a nice sound it just gives out a faint buzz. Suspecting the buzzer to be faulty, I tested it separately from a 5V supply and it worked well. Then I put it back in the circuit and checked for the amount of current the whole circuit used. It was about 26mA when buzzer and LED were turned off, and 36mA with buzzer and LED ON. So no problem there. Additionally, the buzzer sometimes start sounding well too occasionally. This occurs after about half a minute the circuit is turned ON. This looks like that the buzzer is somewhat warming up before it can work properly. But this occurs occasionally.
I am using A0 Analog pin (or Pin no. 23 on ATmega328) for driving the Buzzer and giving 100Hz square wave to it.
What could possibly be the reason for this problem?

Re “I tested it separately from a 5V supply”: you mean with no square wave? Then you mus have a self-oscillating buzzer, right? You are trying to drive it with a software-generated square wave?

give the buzzer digitalWrite(HIGH)

even with a plain piezo 100 Hz is a very deep sound not played well on piezo

@Edgar Honey yes with no square wave...i used 5V using external supply... It worked well. But when 5V was supplied using microcontroller, it didn't work untill few seconds

why are you feeding 100 Hz signal? ... you said that it works with 5 V DC

@jsotola I want to play some notes

@jsotola then is there some name of this type of buzzer that I need

you need a speaker, not a buzzer

But i have seen notes being played on a piezo... How's that possible then?

piezo speaker versus piezo buzzer

if it doesn't work with digitalWrite(pin, HIGH) (and pinMode(pin, OUTPUT) in setup()) then show us your code

If it works well with direct 5v supply and not from an Arduino pin, you probably need a transistor to drive the buzzer.
Here is an example how to drive a buzzer using a transistor:
https://www.maxphi.com/piezo-buzzer-interfacing-arduino-tutorial

Some buzzers are active buzzers and will self oscillate when powered.
Other buzzers requires an oscillating signal on their pins in order to make a sound.  If the buzzer works on 5v then its an active buzzer and you only need to feed it a HIGH signal to make it work. Don't try to feed it a 100hz square wave.

It worked well with a constant 5V supply but not when this constant 5V was supplied using code(here I am not talking about the 100Hz wave, I modified the code to give a constant 5V)


text:
STM32 "Blue Pill" Serial.print freezes Serial Monitor
I am having difficulties when printing any type of variable using the Serial.print(ln) command.
The Serial Monitor becomes inactive after printing for approximately 7 - 15 times.
I currently have the STM32 Blue Pill Board, running Mac OS Mojave and Arduino IDE v 1.8.9
void setup() {
  Serial.begin(9600);
  pinMode(PC13, OUTPUT);

}

void loop() {
  float raw = analogRead(PA0);
  float voltage = (raw * 3.3) / 4096;
  Serial.println(voltage);
  delay(500);
}

isolate the area of the error .... start by changing the print command to Serial.println("voltage"); .... it will print the word "voltage" .... just let it run to see if it also hangs up

Have you made sure to modify the board before using it?
This page mentions at least one resistor that you have to replace for the USB to "work".

The USB standard requires a 1.5 kΩ pullup resistor on D+, but this board is known to have a wrong value (R10 on the board). It ships with either a 10 kΩ resistor or a 4.7 kΩ resistor, but it should be replaced with a 1.5 kΩ resistor, or put an appropriate resistor value (e.g 1.8 kΩ) in between PA12 and 3.3V.
It is also true that some PCs are tolerant of incorrect value so, before you change the resistance, you can try if it works in your case.

I have had issues with bluepill boards myself in the past, but never had an issue like yours after fixing the resistor. (before that, I couldn't even flash the bootloader)
Try printing other things with the board, and see if there's any pattern to it cutting out. e.g. a string over and over again, or the same float over and over again.
Try different baudrates, or even SoftwareSerial to another board.

Printing a float should work (at least with an Arduino), but to test if it cannot handle it correctly, I suggest you convert the float to a string (e.g., with the C function ftoa, and print the characters one by one or as a string.
Since this C function is not available on Arduino, use the function implementation of this article, credits to Martin Waller:
char *ftoa(char *buffer, double d, int precision) {

    long wholePart = (long) d;

    // Deposit the whole part of the number.

    itoa(wholePart,buffer,10);

    // Now work on the faction if we need one.

    if (precision > 0) {

        // We do, so locate the end of the string and insert
        // a decimal point.

        char *endOfString = buffer;
        while (*endOfString != '\0') endOfString++;
        *endOfString++ = '.';

        // Now work on the fraction, be sure to turn any negative
        // values positive.

        if (d < 0) {
            d *= -1;
            wholePart *= -1;
        }

        double fraction = d - wholePart;
        while (precision > 0) {

            // Multipleby ten and pull out the digit.

            fraction *= 10;
            wholePart = (long) fraction;
            *endOfString++ = '0' + wholePart;

            // Update the fraction and move on to the
            // next digit.

            fraction -= wholePart;
            precision--;
        }

        // Terminate the string.

        *endOfString = '\0';
    }

   return buffer;
}


text:
Esp8266 fatal timeout error
I recently got my esp8266-01 and for interfacing with Arduino I completed all the steps need for right form pins to board allotting from esp8266 community after everything I still get error of "connection failed fatal error : timeout ", so anyone just help out for
 soln ?
I am interfacing with empty code of loops only to check it's response at connectivity at first .

how did you wire it? is it the esp-01S version? did you put it in flashing mode for upload?

Rx to Rx and tx to tx , vcc 3.3, channel 5 , esp8266 - 01, no I had put it for blink mode for basic checking of module


text:
How to return Char Array Value in Arduino IDE Function?
Function
char* getConnectDetail(int starting){
  String data;
  for(int i=0;i< 1024 ;i++) {
    if(EEPROM.read(i+starting) != 0){
    data += char(EEPROM.read(i+starting));
    }
   }

   int str_len = data.length() + 1;
  char char_array[str_len];
  data.toCharArray(char_array, str_len);
  return char_array;
}

When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it.
I just want to know whats wrong with my returning method.

for future help with your internet searches, it is not an Arduino IDE function ... it is a C++ function

char char_array[str_len]; is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.
If the caller creates data and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make data a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.

Good answer. Another alternative is to have the function malloc memory for the array and return that. Then the caller would be responsible for freeing it when it was done with it.

Also note that the OPs function will have to return the length of the string array somehow.

Since it no longer has to return the array (caller owns it), the return value is available to return a count or error code.


text:
Remote Arduinos polling a master Ardrino over ethernet/wifi
I'm setting up a "Panic Button" for our Front Office. The concept is to have a master Arduino with the button and 4 other Arduinos with Strobes and/or alarms to alert the rest of the staff. The bells and whistles are fairly straight forward. My only block is how to have the remote Arduinos poll the master and receice a simple on/off value over the existing ethernet/wifi network (necessary because we are physically 2 different buildings so bluetooth or standard serial communicaitons would be prohibitive). Master will be hardwired to ethernet while the remotes will need to be wifi. Any and all suggestions would be greatly appreciated.

This sounds like a job for Multicast UDP to me...

after some research. that appears to be the solution, Thank you!


text:
FS100A works when Arduino connected to PC but not when connected to Raspberry Pi
I am building a simple circuit which monitors soil humidity in a flower pot. I was able to measure it and send it from one Arduino Nano to another Nano via FS100A transmitter and receiver and VirtualWire library.
As this is prototype so far I connected 1st (measuring) Nano to a powerbank and it works fine: I see the data is send and received by 2nd Arduino.
2nd Nano receives the data (it is less than 50 bytes) and send send it to PC via USB serial connection. All works fine as long as 2nd Arduino is connected to anything but Raspberry PI. Then it is not able to receive any data.
I modified source code of my program to blink built-in LED right after data is read. When 2nd Nano is powered by another powerbank it blinks (the data is read). The same happens using any other PC. But when I try to use it with RPi there is no blinking.
RPi is model B+ and I tried two different devices.
I suspect that Raspberries don’t provide stable power to usb or they cause a lot of noise preventing radio from reading the data. Is there any way to overcome this?

Try to power your Arduino with external power supply and use only RPi to receive/display your data. You will prove this way that the problem lays in the insufficient voltage. If you have a DMM you can check this by measuring voltage on RPi USB port.

After some attempts I finally made it work.
I tried to use a level shifter. It worked somehow but I could not find any library which would work with Arduino's VirtualWire.
I just put a 220µ capacitor on power lines to the radio receiver. It filtered all the noise and Arduino is able to interpret signals correctly.


text:
Arduino protecting analog input with internal voltage reference
Usually a common way to protect an analog input consists on reducing voltage and current in the following way:
Current limiting components, as Resistors or inductors and voltage limiting components as diodes, zener, tvs.
In this case for components availability I have used two resistors and a zener diode.
The circuits aims to accept a 0-10V input and read it with the internal reference voltage 1,1V.
The question is the following: Assuming I want to use a 2,2V zener diode as overvoltage protection and 1,1V internal voltage reference, can I consider it safe or the 2,2V of zener will be too much for the 1,1V reference?

simulate this circuit – Schematic created using CircuitLab
NOTES: I am using 2,2V zener diode because is the smallest size I can found.
I could use two normal diodes to reach 1,4V but maybe it will be too much for 1,1V reference and the result could be the same.
I could also add an external reference, but I would like to know if I can have problems with this configuration.

Yes, it is safe.  The reference voltage is only used as a comparison. The ADC is still powered by, and limited by, the chip's supply voltage (5V).
The AREF voltage has no bearing on what limits there are on voltages you can apply to a pin. All that will happen is that voltages above 1.1V will register as 1023. You can go right up to 5V safely.

As far as I know, no one uses a zener diode in a analog circuit that is used to measure a voltage. Well, at least no one who is serious and knows what he/she is doing.
The zener diode will start leaking at a lower voltage and it might introduce noise. I never use a zener diode in a analog input circuit that is used to measure something.
What is the maximum positive and negative voltage that you want to protect the Arduino against ?
Suppose using a 5V ATmega chip, with R1 = 100k, R2 = 10k, C1 = 10nF, with 1.1V as reference (and no extra ESD or clamping diodes and no zener diode). Then you are protected up to 160 V.
That is a constant voltage of 160 V that is allowed, as long as R1 can dissapate the heat.
That means without the zener and better choosen values of the resistors, it becomes more accurate and safer and more sturdy.
Calculation: A0 can be up to 5.5V. Then the internal diodes start to conduct, and it is allowed to push 1mA into the pin.
Current R2 = 5.5 / 10k.
Current into pin = 1mA.
Voltage over R1 = 100k * ((5.5/10k) + 1mA).
External signal = 5.5 + voltage over R1.
Suppose a leakage current for a 2.2V at 1V is 0.02mA. That seems a reasonable number from what I can find. That will influence your measurement by maybe 2 percent (I'm not sure, I didn't do the calculation). That would mean that of the 10-bit resolution you dropped to 6-bit resolution (I'm also not sure about this one).
To protect the analog input, instead of a 2.2V zener, a 5V zener would be more appropriate (that is: when going down the wrong path to use a zener). The 1N4733A has a leakage current of 10 µA at 1V, and that will still influence the analog signal and still cause a less accurate voltage measurement.

Nice to know that the leakage current can cause problems. For sure I can use a 5V zener diode, the 2,2V was for having something closer to 1,1V in the assumption that could cause a problem.
Zener diode was goot also for the reason that protects against reverse voltage. Finally I should use TVS or maybe two diodes (one from ground to analog line and the other from analog line to VCC?

@piertoni, the 5 V zener diode still leaks at 1V as I wrote, that still causes inaccuracy for the reading. Without a zener diode and with the right values for the resistors you are better protected !

@piertoni You are not going to use a zener diode, are you ? Why do it deliberately wrong, when it is easier to do it right ?

I think Zener will be sufficient for the following reasons:

Availability.
I only need to discriminate from 0-10V to 3 speed of a fancoil, so a minimum leakage will not be a problem neither the accuracy of readings.
DIP PCB.
When I will try to protect an ADC needing accuracy I will keep in mind your helpfull explanations. I will also keep it in mind for all the rest of my projects.

Without the zener diode (and with better values for the resistors) you are better protected.

Ok, I will choose different resistors/capacitor values and eliminate zener, thanks

It’s perfectly rational to use a zener to measure voltage. The leakage can be mitigated with a BC557 PNP + 2N7000 NFET, for example, so there is no current path unless it is first enabled on the MCU.

@Jot can you provide context as to how you are protected from 160V as you claim? Is this a property of the ATmega you use in your example? I'm not seeing how a circuit without a zener would protect "better" as well. How are you better protected?


text:
How to change partition scheme with arduino-cli
I'm using arduino-cli to program an ESP32-S2.  If I compile my sketch using the default partition scheme
> arduino-cli compile -b esp32:esp32:esp32s2 sketch

a lot of space is allocated for SPIFFS and OTA, which I don't use.
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.

Thus. I'd like to use the huge_app scheme, as defined in the boards.txt:
esp32s2.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32s2.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32s2.menu.PartitionScheme.huge_app.upload.maximum_size=3145728

However, selecting it doesn't have any effect:
> arduino-cli compile -b esp32:esp32:esp32s2 sketch --build-property build.partitions=huge_app
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.

Is my command line incorrect?  Why is arduino-cli not using the specified partition scheme?

according to platform.txt it is build.custom_partitions the value is the selected partitioning from boards.txt

Thanks for your suggestion, I've checked platform.txt and found custom_partitions as well.  Unfortunately, it didn't help: arduino-cli compile sketch --build-property build.custom_partitions=huge_app results in Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.

Are you uploading the bin file by arduino-cli?

So, it turns out I have to add another build property:
> arduino-cli compile --build-property build.partitions=huge_app --build-property upload.maximum_size=3145728 sketch

where the upload.maximum.size is from the boards.txt file.  Indeed, a maze of twisty little files, all alike.

Just like the original Adventure. :)


text:
ATtiny167 Device not recognized
I'm frustrated I feel like I am 90% there but my computer will not recognize the ATtiny167. Here i9s the list of things I have completed/tried using Windows 10 and Arduino 1.8.6;
                  1) Installed Driver USB Bootloader is complete
                  2) Device Management I see the device
                  3) Arduino Sketch select 16.5 MHz board in parameters
                  4) Led on the board flashes sound beeps and stops flashing
                  5) "Device not recognized"
                  6) I have rebooted many times. I deleted everything and started over again with same
                      results
                  7) Used a 3rd party software to look at my USB ports it see the device
                   I have tried more than one device as well

         I'm stuck at this point. I've tried running example programs however the device is not recognized.

Any suggestions?

Do you have some code on the chip that makes it appear to be a USB device? Otherwise, do you have some USB to UART hardware for communicating with the chip? Is this something you have built yourself, or some non-standard development board?

If Digispark Pro clone is not recognized, you can try to use/upload .ino programs via ArduinoISP.
note use in File -> Preferences -> Additional Boards Manager URLs:
http://drazzy.com/package_drazzy.com_index.json
instead:
http://digistump.com/package_digistump_index.json
(The first is AttinyCore by Spence Konde, the second is the normal Digistump AVR Boards)
Then selected Tools -> Boards Manager, and Find AttinyCore -> (Wait and Install).
Now you can upload File -> Example -> ArduinoISP on your Arduino connected in ISP mode with your ATtiny167.
Now select ATtiny167 Board, 16Mhz (External) and write bootloader with your Arduino connected in same manner ISP mode with your ATtiny167.
And now upload any .ino file for ATtiny167 in the same manner with your Arduino connected in ISP mode with your ATtiny167.


text:
How can I stop a loop when using a servo with a Key input?
How can I stop my following code using a key?
Basically the code should run the servo in a loop if "t" is pressed and stop the loop if "s" is pressed.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position
int servodata;

void setup() {
  myservo.attach(8);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

}

void loop() {
  if (Serial.available()>0){
    servodata = Serial.read();
    while (servodata == 't'){
           for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(3);                       // waits 15ms for the servo to reach the position
  }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(3);                       // waits 15ms for the servo to reach the position
    }
    }
  }
  while (servodata == 's'){
    break;
  }
}

thank you for help.

Basically: Don't use blocking for loops and delays. Delays are just busy waiting. Look into a non-blocking coding style like demontrated in the BlinkWithoutDelay example, that comes with the Arduino IDE. It has been explained throughout the internet.

separate the value of servodata and the servo motion ... use a flag variable ... for example, name the flag go ... if go is true then run the motor ( if (go) { ) ... read the value from serial and set go accordingly ... that way the servo code is not inside the if serial loop

could you post and example? thanks

why do you need a for loop to position the servo?

Here is a quick and dirty solution, where each loop() iteration
corresponds to one “start sweeping”/“stop sweeping” cycle:

wait for the “start” command
then sweep back and forth in an infinite loop
stop at any point if you receive the “stop” command

void loop() {
    // Wait for the 'start' command.
    while (Serial.read() != 't')
        continue;

    // Repeatedly sweep back and forth.
    for (;;) {
        for (int pos = 0; pos <= 180; pos += 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
        for (pos = 180; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
    }
}

Note that this approach has a couple of drawbacks:

As this is blocking code, you cannot easily extend the program to do
other things.
The sweeping runs always start at position 0, instead of resuming
from the position that was current on the last “stop” command.

If you need anything more sophisticated, you should go to a non-blocking
approach based on a Finite State Machine (c.f. jsotola's
comment). Note that you can get away with delay(3);, as it is a quite
short delay, but you would have to break the sweeps into one step per
loop() iteration.
I suggest you give the FSM approach a try: read the tutorial I linked
to, then try to implement it. If you cannot get it to work, you can
always post another question here.


text:
Simplifying code, getting invalid conversion from 'const char*' to 'char*'
I have a program that does 4 times the same thing with different parapmeters; and was trying to simplify my code to take one parameter as a variable.
Example (what was):
const char MQTT_PUB_IRRIGATION_TANK_VALVE[]      = "ArgyleCourt/Property/Hub/IrrigationTank/Valve";
const char MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE[] = "ArgyleCourt/Property/Hub/HouseBoreWaterTank/Valve";

publishTankValveStatusIrrigation(false);

void publishTankValveStatusIrrigation(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "OFF");
  }
}

publishTankValveStatusHouse(false);

void publishTankValveStatusHouse(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "OFF");
  }
}

to one function now passing the topic also inot the function, thus needing only one function:
publishTankValveStatus(false, MQTT_PUB_IRRIGATION_TANK_VALVE);
publishTankValveStatus(false, MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE);

void publishTankValveStatus(bool demandStatus, char topicToPublishTo) {
  if (demandStatus) {
    mqttClient.publish(topicToPublishTo, "ON");
  } else {
    mqttClient.publish(topicToPublishTo, "OFF");
  }
}

when I compile the simplified function, I get "warning: invalid conversion from 'const char*' to 'char' [-fpermissive]", but do neither understand why or how to fix it.

The function declaration
void publishTankValveStatus(bool demandStatus, char topicToPublishTo)

declares topicToPublishTo as a char, that is, as a single character instead of as an array of characters that is constant.
Change char to const char * to say that  topicToPublishTo is an array of characters that is constant.

Thanks! Works :) You wrote const char *; is it permissible or good practice or even the same to write const char* ? This C business with single char, many char, and pointer really trips me all the time :(

@MaxG, both forms are ok; which to use is mostly personal preference. I think const char*, with the star close to char,  is used much more commonly than with a space between.  But if you are declaring several variables on one line (which some may frown on) it makes sense to associate the star with the variable name.  Eg, in char *a, b, *c, d, e;, only a and c are pointers vs. single characters.  Also, for the parameter declaration, some would say const char topicToPublishTo[] instead of const char *topicToPublishTo

Also see answers to  const char * const versus const char *?, which cover examples like char* astring, const char* astring, char* const astring, and const char* const astring.  Note, answers to  What is the difference between char * const and const char *? might be more understandable.


text:
Drop alpha character from serial input
I receive strings over the serial port like so:
VLT=53.0, AMP=-30.2, AHR=-10, SOC=98, TMP=136, STS=192
I want to reduce the use of string functions with the idea of dropping all non-digits, keeping numbers dot and comma, to get this:
53.0,-30.2,-10,98,136,192
in an array and simple read [0], [1], etc.
Regular expressions would be idea, but do not exist like in PERL.
Any hint would be much appreciated.
Relevant code used:
    char inByte = SerialPortOne.read(); // read byte
    strRecordIn.concat(inByte);         // add byte to receive buffer
    for (int i = 0; i <= 3; i++) {    // VLT, AMP, AHR, SOC
    strWord = getValue(strRecordIn, ',', i);  // get data item from RecordIn array
      strWord.remove(0, 4);           // remove field identifier (1st 3 char plus =)
      strRecordOut += ',';            // add delimiter
      strRecordOut += strWord;        // add value
      strWord = "";                   // reset strWord
    }

Ideally:
    char inByte = SerialPortOne.read(); // read byte
    if (inByte = [%d.,]+) {
      strRecordIn.concat(inByte);       // add byte to receive buffer
    }

If you just want to remove the letters:
#include <ctype.h>

char inByte = SerialPortOne.read();  // read byte
if (!isalpha(inByte)) {              // not letter
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

Or you may test it for isdigit() and explicitly compare to ',' and
'.':
if (isdigit(inByte) || inByte == '.' || inByte == ',') {
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

C.f. the documentation of
<ctype.h>.

Brilliant! I got lots to learn in this Arduino environment. Thank you!

@MaxG: Well, in this case it's standard C, not specific to Arduino.


text:
Using Arduino project migrated to breadboard with 12 MHz crystal instead of 16 MHz
I am moving my Arduino Uno project from Uno to Bread and as we know, this requires two 22 pf capacitors and 16 MHz on the breadboard (and the other things too like the power-but my question is about the crystal frequency so I'll focus on that).
If I replace the 16 MHz crystal with a 12 MHz crystal then the project will work as expected on a breadboard-is that correct?
It seems that the fuse setting to use 16 MHz crystal is the same as for the 12 MHz crystal for Arduino Uno-so I guess a change to the fuse setting or bootloader is not required. Am I missing anything?
I guess it's as simple as replacing a 16 MHz crystal by a 12 MHz crystal.

You will need to change your compile settings so that baud rates and delays are calculated for 12 MHz.  This used to require a unique entry in the boards file but it can possibly now also be supported as a menu choice, you may have to do some research on your own to find the current state of things, but I bet a web search will find you an example boards file entry for 12 MHz, too.

You can also program the ATmega using ISP, and thus not needing a bootloader at all.

@Gerben So how would that differ (versus using a bootloader) for setting up a 12 Mhz crystal?

@yabbadabba you don't need to burn a 12MHz version of the arduino bootloader. Your code still needs to set the correct F_CPU so delay etc. work correctly.

Some of the code running on the microcontroller needs to know the clock speed it's running at for correct timing. For this reason the macro F_CPU is set with this value. In the Arduino IDE this value is commonly defined in the boards.txt build.f_cpu property. If you're using a bootloader(which is used for uploading sketches over serial) it also needs to know the clock speed so that it can get the baud rate of the upload correct. The bootloader is not compiled in the Arduino IDE so it is not affected by your setting in boards.txt. You can recompile the bootloader with the correct clock speed setting and then install the compiled file on your microcontroller using an ISP.
There is a much more simple solution. All the hard work has already been done for you in MiniCore:
https://github.com/MCUdude/MiniCore
You only need to:

Install MiniCore following the instructions at https://github.com/MCUdude/MiniCore
Tools > Board > ATmega328
Tools > Variant > 328P / 328PA
Tools > Clock > 12 MHz external
Tools > Burn Bootloader

Yes it will work correctly IF you change the compile setting so that everything is in sync. This is because when you select an Arduino UNO from the IDE, it will process that as if your Arduino has 16Mhz. Here is a link for more information..

Im going to leave in the 16 MHz crystal upon to the very last moment Ive got everything on breadboard working (so the baud rate isnt affected when downloading a sketch). And for the compiler setting-I looked up the code-I think you mean change FCPU then it will define the real world time correctly from the frequency. Is that all that required for the changes?

at the last moment ill plug out the 16mhz crystal and replace it with the 12mhz


text:
Unidentified constant value
im working on the following project kalman filter
and im working to implement in arduino.. i read the entire code and i succesfully implemented it into arduino but i couldnt implement the following function code line because arduino gives "not defined" error in PI_DIV_180
imu_MadgwickQuaternionUpdate(bUseAccel,elapsedTimeSecs,fax,fay,faz,fgx*PI_DIV_180,fgy*PI_DIV_180,fgz*PI_DIV_180,fmx,fmy,fmz);

it multiplies fgx with PI_DIV_180 but as i said arduino cant identify it
i looked into math.h to find the value of that define but there isnt anything in math.h related with this
the imu_MadgwickQuaternionUpdate function is in here IMU.cpp
can anyone help me please thanx..

Maybe it's pi (π) divided by 180?
Pi is roughly: 3.1415926535898
So:
3.1415926535898 / 180 = 0.017453292519943

So add this line:
#define PI_DIV_180 0.017453292519943

yeah it may be...will try it..thanx

authors: евгений иванов


text:
Matlab Arduino Multi Byte Read
I'm using Matlab to communicate with a custom AD7746 board through an Arduino UNO. The data sheet mentions that
"In continuous conversion mode, the address pointers’ autoincrementer should be used for reading a conversion result.
That means, the three data bytes should be read using one
multibyte read transaction rather than three separate single byte
transactions"
I'm not sure how I can go about implementing this using MATLAB's Arduino support package.
Would anyone have an Idea about this?

Show us what you've done so far. Have you read data from the sensor yet?

I think I figured it out.
Matlab's Arduino package has a "read" command which lets you read data from an I2C device and allows you to specify the number of bytes.
I'm just testing it to make sure that I got it right


text:
Connecting to WIFI using esp8266
This is my code. I am tring to make a connection to my wifi through esp8266.
#define DST_IP "192.168.1.5" // my IP
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);

void setup()
{
  Serial.begin(115200);
  mySerial.begin(115200);
  while (! Serial); // Wait until Serial is ready - Leonardo
  Serial.println("AT+RST");
  delay(4000);
  Serial.println("AT+CWJAP=\"Ahmed\",\"12341234Aass\"");
  delay(4000);
  if (Serial.find("OK") )
  {
    Serial.println("1");
  }
  else
  {
    Serial.println("0");
  }
}

void loop()
{

}

This is the result of my code.

SoftwareSerial mySerial(0, 1);

try changing pin0 and pin1 with some other pins. (lets say with pin2 & pin3)
pin0 and pin1 are used by default Serial.

but pin0 and pin1 are my RX and TX .. is it true to work with any pin ?

yeh,  pin0 and pin1 are your RX and TX. BUT they are so, only when you are using Serial. In above mentioned line of code you are initializing another serial, mySeial, to use same pins as Serial which is the cause of error.

Thanks for replying BUT actually I use mySeial in nothing. So I removed it and still same error!

The point is that these pins are already used for the connection to the USB serial device proxying for the host PC.  You need to connect the ESP8266 to different pins, not to these.

Okay. I have set SoftwareSerial mySerial(0, 1); To SoftwareSerial mySerial(2, 3); But it always return 0 in the result which means it can not connect to the network.


text:
How to set float to variable with 7 digits after the decimal point in arduino?
Example:
float x = 3154681.124 / 100000; //x = 31.54;

I want x to be:
x = 31.5468112;

When you write 3154681.124 / 100000, you are accumulating two rounding errors: first, in representing the numerator as a float, then in the division. Total error ≈ 1.09e-6. If you write instead 31.54681124 you have a single rounding error, and the total error is 25% lower.

An IEEE 32 bit float has only 23 bits for the fractional part, so you only get about log(2^23)/log(10)=6.9 decimal places total.  Maybe you want a double?

The float type has slightly over 7 digits of precision. See https://en.wikipedia.org/wiki/Floating_point.

I want x to be:
   x = 31.5468112;

Bad luck. That's 9 digits of precision. You can get around 7 digits by converting it appropriately, eg. as Majenko said:
  float x = 3154681.124 / 100000; //x = 31.54;
  Serial.println(x, 7);

However that printed:
31.5468101

It got 7 digits right, as advertised.

You can use the BigNumber Library that I wrote. Available from GitHub.
Using that, you can get all the precision you want, within reason:
#include "BigNumber.h"

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

  BigNumber::begin (7);  // 7 digits after the decimal place

  BigNumber x ("3154681.124");
  BigNumber y = x / BigNumber ("100000");

  Serial.println(y);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output:
31.5468112

float x = 3154681.124 / 100000; //x = 31.54;

x is now 31.5468112 (or close to).
Serial.println(x);

Output: 31.54
Why? Because Serial.println defaults to 2 decimal places for floats.

Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
val: the value to print - any data type
format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

So the solution: specift 7 decimal places when you print:
Serial.println(x, 7);

I don't want to print x , I want to send it as a parameter in URL to web service. when I send it as x its value became 31.54

Then whatever your code is that is doing the sending is truncating it. I can't see that code, so I can't advise on it. The simple fact, though, is a float doesn't have a fixed number of decimal places, that's not how floats work.

when I send it as x its value became 31.54 - you need to post that code. We can't answer questions about code we can't see.


text:
Digital output from one nano to digital input of another.
Can I connect the digital out of one arduino to a digital input of another? To detect a high/low state...
One powered in one room on USB. The other in another room separate psu (connecting the grounds).
I know I can use tx/rx serial. But if the other way would work, less programming and 1 wire less..

Do you only need unidirectional (A -> B) or bidirectional comm. (A <-> B)? Also, with common ground it's always at least two wires (GND + Signal). Or you use a differential signaling (signalPLUS, signalMINUS), like RS-485  which allows for longer cables due to higher noise immunity. How long is the cable?

Yes, you can. As you noted, you do need to connect the grounds of both Arduinos.
For some extra protection you could put a resistor between the output and the input. For example a 1kOhm. That way, if you accidentally set both pins as outputs, or plug the wire in the incorrect pin, you won’t get a dead-short.

Thanks guys... Its just A>B so that's great. I will dig out a resistor


text:
How to add additional millisecond delay to microsecond delay generator
I am trying to make a delay generator. I already found an excellent example in Generating a short pulse after a delay that works in the range from ~5-32767 microseconds (it is limited by a 16 bit microsecond counter divided by 2).
How would I go about extending that range into the millisecond range (say up to 1s or so)? Since this example is interrupt-based, adding delay() statements do not really seem to work.
I have also tried changing the timer prescaler, but then the jitter is also scaled up in an unacceptable way.
This is the code I have now. Send commands via the arduino serial console, D500 for 500µs delay, L100 for a 100µs long pulse. Letters M and N change the prescaler.
uint16_t pulse_delay = 10; //half-microseconds
uint16_t pulse_length = 10;
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
long read_value = 0;
long ms_delay = 0;

void printvals() {
  Serial.print(F("Delay: "));
  Serial.print(pulse_delay / 2);
  Serial.println(F(" µs"));
  Serial.print(F("Length: "));
  Serial.print(pulse_length / 2);
  Serial.println(F(" µs"));
}
long getcommandvalue(String inputstring) {
  inputString.remove(0,1);
  return inputString.toInt();
}
void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
  Serial.begin(9600);
  inputString.reserve(200);
  Serial.println(F("RDY"));
  printvals();
}
void loop(){
  if (stringComplete) {
      switch(inputString.charAt(0)) {
        case 10: //\n (Newline; Line Feed)
          // previous line ending was CRLF, so now LF was carried to the next string
          break;
        case 63: //?
          //print current vales
          printvals();
          break;
        case 68: //D (Delay)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_delay = 2 * read_value;
            printvals();
          }
          break;
        case 76: //L (Length)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_length = 2 * read_value;
            printvals();
          }
          break;
        case 77: //M (additional prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
            | _BV(CS10) // 64 prescaler
            | _BV(CS11); // /8 prescaler
          break;
        case 78: //N (8x prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
              | _BV(CS11); // /8 prescaler
          break;
        case 79: //O
          ms_delay = getcommandvalue(inputString);
          // I don't know where to execute this ms_delay
          break;
      }
      inputString = "";
      stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:Z
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if ((inChar == '\n') or (inChar == '\r')) {
      stringComplete = true;
    }
  }
}

ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIFR1 = _BV(OCF1A);  // clear interrutp flag
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match
  OCR1A = pulse_delay + pulse_length;
}

Put it in a loop and run it multiple times.  But also consider the loop overhead.

You could count timer compare matches.  The following illustrates the principle, maybe not accurate as written but I am sure the counter loop will be precise enough for your needs, considering you want to use an Arduino.  Depending on the time resolution you want, you may be able to run other code while the software counter is active.
The following can count to several seconds, depending on values of OCR1A and counter_target.
unsigned int state, pulse_delay;
byte counter[3]={0,0,0}; // 24 bit counter, you can make it longer in principle

byte counter_target[3]={0,0,0}; // defines length of delay you want

void setup(){
state=0;
TCCR1A=0;
TCCR1B=0;
}

void loop(){
switch (state){
case 0: // idle state machine // you other code here
counter_target[0]=0; // For example
counter_target[1]=0;
counter_target[2]=1; // corresponds to (1+65536)*pulse_delay/clock_scaler
// when you are ready to start counting
state=1;
break;

case 1: // setup timer
counter[0]=0; // Zero the 24-bit counter
counter[1]=0;
counter[2]=0;
OCR1A = pulse_delay; // number of pulses to count = 1+OCR1A
OCR1B = OCR1A+1;
ICR1  = OCR1A+1;    // Just to make sure these don't cause compare match
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
TCCR1A = B00000011; // Fast PWM mode 15 on UNO, OCR1A=TOP
TCCR1B = B00011001; // Clock prescaler 1
break;

case 2: // Counting up
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
counter[0]+=1; // Increment counter by 1
if(counter[0]==0x00){counter[1]+=1;
if(counter[1]==0x00){counter[2]+=1;}} // etc

if(counter[0]==counter_target[0] && counter[1]==counter_target[1] && counter[2]==counter_target[2]){state=0;}  // Check if we have reached the target delay
break;

}
}


text:
How to read from multiple multiplexers (CD74HC4067) with a library
I need to read alot of buttons and analog inputs for my project (60 buttons 15 faders) and there fore need to use multiplexers. But most mux libraries seems to only support one mux, am i wrong?

It seems to me a library is a bit overkill for that IC, since you have 4 pins to define which input pin/channel will be used. Seems to me to send 4 digital writes to define the channel, an one analog read for getting the signal. So since you do not a library, you can control them all the way you want.

Which library? You should be able to use multuple instances, and there are libraries that have support for cascaded muxes.


text:
Accelerometer IoT
I am not sure if I am in the right place. I would like to build a device (as small as possible) that has an accelerometer and can talk to my phone via bluetooth. Im not asking anyone to build this for me. I would just like some starting help. Can you tell me the parts that I would need to accomplish this?

For low power battery powered operation you want BLE not normal Bluetooth.

Only moments ago, I was perusing the Adafruit selection and found this BLE module for arduino and similar:
https://www.adafruit.com/products/1697

Find a tutorial, e.g. https://learn.adafruit.com/adafruit-analog-accelerometer-breakouts

you will need:

Arduino Mini (can also use Uno/Mega/Pro....)
Bluetooth Module (mostly used: HC-06/HC-05)
Accelerometer (mostly MPU-6050)
Few wires.

If you want to carry this device around, you will need a battery to power this circuit.

Your smallest solution would not involve a conventional "Arduino" at all, but rather something like an nRF51822 Bluetooth Low Energy chip/module, which in addition to being a radio is a processor in its own right capable of running custom software built in a variety of ways, including one that extends the Arduino IDE to support it.
Basically, you need the nRF51822 or similar chip, an accelerometer, and whatever solution for powering the two you decide upon.
In terms of conventional bluetooth vs. BLE the choice depends not only on technical merits, but also on which phone you want to connect to.  If you want to connect to an iphone, you are basically locked into BLE as the bluetooth stack there is restricted to approved devices.  On the other hand older/cheaper Android devices may not support BLE, or support it poorly, while their conventional bluetooth does not have the approval restrictions of iOS.

If you want Arduino programming AND you have physical size limitations, you may want to checkout RFDuino.
http://www.rfduino.com/
They have a variety of breakout boards that make rapid prototyping easier.
I should say however that while I have purchased one of these, I have yet to get around to using one. Others with more experience may want to chime in.


text:
Get MP3 play length
I'm creating a project where music gets played that is the same length or slightly shorter than the given time (minutes:seconds). For this I have a Sparkfun MP3 shield, which also has a microSD slot.
The issue is that I can't find a way to get the playtime of a given MP3 file. The only idea that I have is using the filesize and bitrate, but that would be horribly annoying for multiple bitrates.
Thanks in advance,
Michidez

You could try parsing the ID3 data of the MP3. Or just create a separate file containing the length. Or maybe encode the length in the filename (e.g. mozart-154s.mp3).


text:
Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer?
The closest thing I can find is if(Serial) but that only returns true if there's a serial port open.
The function I want, ideally, should:
Return true if plugged into a computer
Return false if plugged into a USB power bank
Return false if not plugged in at all(Running off of its own lithium cell)

ADDEN of UDADDR is set if the '32U4 has been assigned a USB address by the host and the firmware wants to enable USB connectivity.
UDADDR & _BV(ADDEN)

Is there something similar for VBUS detection to get the (not)plugged in?

@Majenko: VBUS in USBSTA.

Stupid question, but where do I go from here? Is it as easy as (UDADDR & _BV(ADDEN)) != B00000000 ?

if (UDADDR & _BV(ADDEN)) ...

Works but there is a problem with battery powered equipment when you disconnect the USB cable. This still returns true and after an restart it returns false. How to fix this?

Rewrite the firmware to deconfigure USB when disconnected.

This willl wait for serial monitor to be opened if usb connected before proceeding:
if (UDADDR & _BV(ADDEN)){ while (!Serial);}


text:
Error while receiving large amount bytes on loop using esp32 ( 541 bytes )
I am using an ESP32 (without arduino board and using arduino IDE ) with bluetooth and communicating with other hardware via serial communication.
Serial communication speed is high (1382400) but it works and I can read few bytes normally. I need to read a large number of bytes (541) in loop to be able to flush the memory of the hardware in question.
Using the following code I can read the bytes and can even perform a number of iterations but usually get the following error after a few iterations:
Guru Meditation Error: Core 1 panic'ed (InstrFetchProhibited). Exception was unhandled.
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

#define RXD2 16
#define TXD2 17

BluetoothSerial SerialBT;
HardwareSerial SerialPIC(2); // using esp32 port2

byte recebidoPIC[542];
byte recebidoBT[50];

bool conectado;
int pagina;
bool coletaftp;
bool enviar;

void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
  if (event == ESP_SPP_SRV_OPEN_EVT) {
    // pin set to high enable communication to other hardware
    digitalWrite(2, HIGH);
    digitalWrite(5, HIGH);
    conectado = true;
  }

  if (event == ESP_SPP_CLOSE_EVT) {
    digitalWrite(2, LOW);
    digitalWrite(5, LOW);
    conectado = false;
  }
}

void setup() {
  pinMode(5,OUTPUT); // Control pin to enable hardware
  Serial.begin(19200);
  SerialPIC.begin(1382400,SERIAL_8N1,RXD2,TXD2);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println(F("The device started, now you can pair it with bluetooth!"));
  SerialBT.register_callback(callback);
}

int leStringSerialBT()
{
     int cont=0;
     while ( SerialBT.available() > 0 ) {
       recebidoBT[cont++] = SerialBT.read();
       yield();
     }
  return cont;
}

int leStringSerialPIC()
{
  int cont = 0;
   while ( SerialPIC.available() > 0 ) {
     recebidoPIC[cont++] = SerialPIC.read();
    // delay(0);
     yield();
    }
    return cont;
}

void loopcoleta()
{
  if (SerialPIC.available()) {
     int cont=0;

    cont = leStringSerialPIC();

      if (cont < 541)
      {
        Serial.print(F("Nao completou - "));
        Serial.println(cont);

      }
      else{
        Serial.print(F("Completou - "));
        Serial.println(cont);
        Serial.print(F("Iteracao :"));
        Serial.print(pagina);
        pagina++;
      }

  }
}

void loop() {
 // digitalWrite(5,HIGH);

  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }

  if (SerialBT.available()) {
    int cont=-1;
    cont = leStringSerialBT();
    if ( conectado )
    {

       if ((recebidoBT[0]=='$') && (recebidoBT[1]=='f'))
       {
          coletaftp = true;
          enviar = true;
          //recebidoBT = "";
          pagina = 1;
       }
       else
       {

           SerialPIC.write(recebidoBT,cont);

       }

       if ( (coletaftp) && (enviar)  )
       {
          char comando[11];
          int looppagina = pagina;
          int contcoleta=0;
          unsigned int timeinit = millis();
          while ( pagina < 8191 )
          {
           sprintf(comando, "$rd 00%04x", pagina);
           SerialPIC.println(comando);

           loopcoleta();
           delay(0);
          }
          Serial.println(millis() - timeinit);

       }

    }

  }

  if (SerialPIC.available()) {
     int cont=0;

    unsigned int timeprevious = millis();
    cont = leStringSerialPIC();

    Serial.println(millis() - timeprevious);
    Serial.println("");
    Serial.write(recebidoPIC,cont);
    Serial.println("");
    Serial.println(cont);
    SerialBT.write(recebidoPIC,cont);

     cont=0;
 }

 // delay(20);
}

The above code is complete and after some iterations I get the following message (copied from serial monitor)
Iteracao :1 Completou - 541
Iteracao :2 Completou - 541
Iteracao :3 Completou - 541
Iteracao :4 Completou - 541
Iteracao :5 Completou - 541
Iteracao :6 Completou - 541
Iteracao :7 Completou - 541
Iteracao :8 Completou - 541
Iteracao :9 Completou - 541
Iteracao :10 Completou - 541
< list goes ok here >
Iteracao :67 Completou - 541
Iteracao :68 Completou - 541
Iteracao :69 Completou - 541
Iteracao :70 Nao completou - 4
Guru Meditation Error: Core  1 panic'ed (InstrFetchProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x17335c40  PS      : 0x00060330  A0      : 0x800d18bf  A1      : 0x3ffc89d0
A2      : 0x3ffc50f0  A3      : 0x3f40152f  A4      : 0x0000000a  A5      : 0x0000ff00
A6      : 0x00ff0000  A7      : 0xff000000  A8      : 0x800d240f  A9      : 0x3ffc89b0
A10     : 0x3ffc50f0  A11     : 0x00060320  A12     : 0x400908ef  A13     : 0x3ffc8990
A14     : 0x00050323  A15     : 0x3ffba470  SAR     : 0x0000001b  EXCCAUSE: 0x00000014
EXCVADDR: 0x17335c40  LBEG    : 0x4000c28c  LEND    : 0x4000c296  LCOUNT  : 0x00000000

Backtrace: 0x17335c40:0x3ffc89d0 0x400d18bc:0x3ffc89f0 0x400d18d8:0x3ffc8a10 0x400d1a26:0x3ffc8a30 0x400d2c05:0x3ffc8a60 0x4008e0bd:0x3ffc8a80

Rebooting...

Already tried to put a longer delay () between each iteration, reduce the size of the array and did not solve ...
What could cause this problem in the code I'm using? If you need more details just tell me.

Guessing, your program throws an exception after reading a short response.  So consider your count value to be incorrect.  For example, you use count then increment it.  So likely it is one too large after reading less than 541 bytes.  Or, your string (array of bytes) may not be terminated as expected by the library (BluetoothSerial) you are using.

You make a fundamental error in your serial reading assumptions. You should read this: https://majenko.co.uk/blog/reading-serial-arduino

@st2000 - i will investigate the code , maybe the line :
recebidoBT[cont++] = SerialBT.read(); could cause the problem.

@Majenko - i will read the article and look for what i made wrong.

@FabriciusLopes It's covered by the very first code example in the blog post.

@Majenko - i'm outside today but reading the article , the diference is the while loop. Maybe using for ( int i=0; i<Serial.available() ; i++ ) do the job or reading serial. available to int variable and later compare it.

@FabriciusLopes The point is: you must not try to read more bytes than are actually available. Just because some bytes are there doesn't mean all bytes are there.


text:
Baud rate above 115200 don't work for esp32
I have equipment transmitting data via uart with a baud rate of 1382400 and I would like to read this information through the Serial2 port of the ESP32.
I've tried to set this high baud rate using Serial2.begin(1382400) but I can't read anything.
Using the function below to detect the baud rate I can read a maximum of 922190 bauds.
Below is the sketch I used to check the baudrate:
void setup() {

     Serial.begin(115200);
     delay(100);
     Serial.println();
     // Passing 0 for baudrate to detect it, the last parameter is a timeout in ms
     Serial2.begin(0, SERIAL_8N1, -1, -1, true, 11000UL);

     unsigned long detectedBaudRate = Serial2.baudRate();
     if(detectedBaudRate) {
       Serial.printf("Detected baudrate is %lu\n", detectedBaudRate);
     } else {
       Serial.println("No baudrate detected, Serial2 will not work!");
     }
   }

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

}

The answer I get is as follows:
Detected baud rate is 922190
I managed to communicate between the equipment and the esp32 using a baud rate of 115200.
I changed the baud rate to 230400 and I couldn't communicate anymore. From 230400 no baud rate worked.
The transmitting equipment uses pic 18F4520 and engineering sent me the following information:
The crystal of the equipment is 11.0592 MHz
The PLL quadruples this frequency, so the pic's clock is 44.2368 MHz
I connect the tx with the rx , I interconnect the GND. As far as I understand it is not a connection problem because in 115200 it works.
Unfortunately I can't change it to 115200 definitively because it changes other functions of the equipment.
Is this a limitation of ESP32? Could I do something else to test?
Sorry for the long post and language mistakes as English is not my main language .

ESP32 can operate up to 922190 bps without any problem. I use it all the time. In fact, it is default upload speed every time you update code to the ESP32.  If there is any something that doesn't work, it is more likely that your PIC18F4520 can't support it.

@hcheung - I asked to set the speed of the pic to 922190 and even then I couldn't communicate. Using the code in the question I realized that the baudrate difference detected exceeds 3%, could this be the source of the problem?
Another curiosity, using Realterm for windows and setting it to 922190 I also can't read anything in esp.

Well, maybe you should ask whoever ask you to run PIC at 922190, why he/she think the PIC can run at that speed according to table 18-3 (page 196) of 18F4520 datasheet?

@hcheung - yes according to the manual 115200 would be the maximum but in the equipment the current speed is 1382400 bps. This equipment communicates at this high speed with an hc-06 module. So I believe it could be something with the ESP32.
The hardware developer makes it available via bluetooth , command to change the communication speed going up to 1382400.
If you want I can detail the calculation he explained to me to see it clarifies something.