# Question
Title: Run multiple function with different argument/return structure by one function pointer
**Edit:** I tried a simple code in Arduino IDE which should've done in the first place instead in doing it in a desktop compiler. Because the results are different by experiment. In the desktop C compiler, it's working and bypassing the code without much problems, just one or two warnings.

But in Arduino IDE, it's not acceptable and gives error.

This is the code:

```
// functions
void function1(uint8_t x, uint8_t y){
  int z = x + y;
  Serial.println("function1\n");
  Serial.println(z);
}
uint8_t function2(uint8_t x, uint8_t y){
    Serial.println("function2\n");
    return 1;
}

void (*fun_ptr)();

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

  Serial.begin(9600);
  fun_ptr = (void (*)())function2;
  int value;

  value = fun_ptr(1,2);

}

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

}

```

# Answer
> 1 votes
It looks to me like you are trying to find the right answer to the wrong question, typical of an XY problem. In the example you provide in your own answer, you call the function pointer right after having set its value. In this case, there is no use to the function pointer, as you could directly call either `read_chars()` or `write_chars()`.

Obviously, this is just because that example is excessively simplified. In a more realistic use case, you would set the function pointer in one part of the code, and call it in a completely different part. Assuming the functions and the pointer are defined like this:

```
void (*fun_ptr)();

void read_chars(uint8_t address) {
    printf("address of array is 0x%.2x\n", address);
}

void write_chars(uint8_t row, uint8_t col, const char *str) {
    printf("[%d, %d]: %s\n", row, col, str);
}

```

One section of the program sets the pointer:

```
// Here we learn what action should be performed.
if (should_read()) {
    fun_ptr = (void(*)()) read_chars;
} else {  // should write
    fun_ptr = (void(*)()) write_chars;
}

```

and a different section calls it:

```
// Here we have to perform the action.
if (fun_ptr == (void(*)()) read_chars) {
    ((void(*)(uint8_t)) fun_ptr)(1);
} else if (fun_ptr == (void(*)()) write_chars) {
    ((void(*)(uint8_t, uint8_t, const char *)) fun_ptr)(
            1, 1, "messaage0");
}

```

Note that this second section **must** know what function it is calling in order to pass the correct arguments. Hence the `if...then` test. Note also that, in order to have valid C++, you must explicitly cast the function pointer before calling it. This gets very clumsy, and it is a lot more convenient to store this information (what function should be called) in an `enum` rather than a function pointer:

```
enum {
    CALL_NONE, CALL_READ_CHARS, CALL_WRITE_CHARS
} what_to_call = CALL_NONE;

```

which would be used like this:

```
// Here we learn what action should be performed.
if (should_read()) {
    what_to_call = CALL_READ_CHARS;
} else {
    what_to_call = CALL_WRITE_CHARS;
}

// ...

// Here we have to perform the action.
if (what_to_call == CALL_READ_CHARS)
    read_chars(1);
else if (what_to_call == CALL_WRITE_CHARS)
    write_chars(1, 1, "messaage1");

```

That being said, it is often the case that when it is time to perform the action, the part of the code responsible of doing so does not know what arguments should be passed, and this information is more readily available at the time when when learn what action should be performed. This is a quite common situation, and a standard C idiom in this case is to give the function a `void *` parameter that it will cast to the appropriate type in order to retrieve the data it needs. For instance:

```
void (*fun_ptr)(void *);
void *fun_ptr_data;

void read_chars(void * data) {
    uint8_t address = * (uint8_t *) data;
    printf("address of array is 0x%.2x\n", address);
}

struct write_chars_data {
    uint8_t row;
    uint8_t col;
    const char *str;
};

void write_chars(void *data) {
    write_chars_data *d = (write_chars_data *) data;
    printf("[%d, %d]: %s\n", d->row, d->col, d->str);
}

```

Note that, since `write_chars()` needs to retrieve multiple parameters from a single pointer, it uses a pointer to a `struct`.

Now, the part of the code that learns what should be done has the responsibility of providing the data:

```
// Here we learn what action should be performed.
if (should_read()) {
    fun_ptr = read_chars;
    uint8_t *p = new uint8_t;
    *p = 1;
    fun_ptr_data = (void *) p;
} else {  // should write
    fun_ptr = write_chars;
    write_chars_data *p = new write_chars_data;
    p->row = 1;
    p->col = 1;
    p->str = "messaage2";
    fun_ptr_data = (void *) p;
}

```

The part of the code that has to perform the action now is very simple:

```
// Here we have to perform the action.
if (fun_ptr)
    fun_ptr(fun_ptr_data);

```

Note that this code snippet doesn't free the allocated memory. You will have to figure out who will be responsible for that.

This pattern is quite common in libraries, where the client (the user of the library) wants an action to be performed, but the library is responsible for performing that action at the right time. The client would then provide the library a pointer to a function that accomplishes the action (called a “callback”), together with a generic pointer to the data needed by the callback. The use of a generic `void *` pointer makes sense, because the library cannot know what kind of data the callback will need.

In your case, since you know what kind of data you may need, you could use a pointer to an `union` instead of a generic pointer:

```
union fun_data {
    uint8_t address;  // for read_chars
    struct {          // for write_chars
        uint8_t row;
        uint8_t col;
        const char *str;
    };
};

void (*fun_ptr)(fun_data *);
fun_data *fun_ptr_data;

```

A more idiomatic C++ style would be to pack together the callback function and its data into a “functor”, i.e. an object that can be called like a function, and can also store the data it needs. You would then use inheritance in order to create specific functor types while calling a generic one.

# Answer
> 2 votes
I assume, that the `fun_ptr` points to the different service functions to do some kind of animation other other long running tasks on your display, thus you want to repeatedly call them in a structured way.

What you are currently doing will not really work. When you call a function, you need to provide its arguments. That's the same for a function pointer. You cannot call a function, that demands parameters, without any parameters. While you can still set a function pointer of type `(void (*)(void*)` to a function of type (void (\*)(uint8\_t)), the compiler warns so, because you still cannot call the function without any parameter. If you are trying to do so, you will still get an error of `too few arguments to function ...`.

I see 2 ways to go from here:

* You could overload your functions, so that a version without any parameters exists. Like this:

```
  void foo(uint8_t i){Serial.println(i);}
  void foo(){foo(10);}

```

With 10 being the value, with which the function should be called, when you provide no parameters. You can of course also use variables or function calls here, to actually get that value for the parameter `i`. Then you can use the pointer to call that function:

```
  void (* p)(void);
  p = &foo;
  p();

```

The assignment of the pointer will choose the version of the function without any parameters out of the overloaded pool of this function, since that matches the type of the pointer. Note, that I removed the `*` from the `void` parameter definition. I don't understand, what that would mean anyway (pointer to void?). The function pointer `p()` can now be called without any parameters, since it points to a function without any parameters.
* You could ditch the function pointer and use a simple switch case statement with a state variable (which holds some identifier for the corresponding function), to call the correct service function. I won't go into detail here, since that is already basically, how an FSM can be programmed in C++, which is covered on this site and on the web numerous times.

If I were you, I probably would go with the first option, though that might also depend on the overall logic, that I currently don't really understand (too few information).

# Answer
> 0 votes
Here's my latest work around:

I was searching for a work around. I got back to copy a method of casting a function pointer.

And changed my data structure of having 2 nested structs to one that contain everything which should serve my project well.

Here's my work:

task\_manager.h

```
///////////////////////////////////////////////////////////////////////////
// enumerations
typedef enum {NOT_FINISHED,FINISHED,DONE}STATE;
// variables
typedef void (*f_ptr)(void *args);

// structs
typedef struct __attribute__((__packed__)) THREAD{
    uint8_t tsk_cnts, tsk_cntr;     // task information
    STATE   thrd_st;                  // thread flag states
    f_ptr   *tsk_fptr;
}THREAD;

```

main.c

```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "task_manager.h"

const unsigned char PIC[] = {9, 8, 7, 1, 2};

void function1(void){printf("function1\n");}
void function2(uint8_t i){printf("function2\nnumber = %d\n",i);}
void function3(uint8_t a, uint8_t b, const uint8_t *img){
    printf("function3\na#%d b#%d\narray[0] = %d\n",a,b,*(img+0));}
uint8_t function4(uint8_t i){printf("function4# return\n"); return i+=1;}

THREAD thread1;

uint8_t fn4_ret;

int main(){

    // set thread main info
    thread1.thrd_st = 0;
    thread1.tsk_cnts = 4;
    thread1.tsk_cntr = 0;

    // allocating memory for tasks
    thread1.tsk_fptr = malloc(4*sizeof(f_ptr));

    // store tasks addresses
    thread1.tsk_fptr[0] = (void(*)())function1;
    thread1.tsk_fptr[1] = (void(*)())function2;
    thread1.tsk_fptr[2] = (void(*)())function3;
    thread1.tsk_fptr[3] = (void(*)())function4;

    // call the functions
    ((void(*)())thread1.tsk_fptr[1])(9);
    ((void(*)())thread1.tsk_fptr[2])(1,2,PIC);
    fn4_ret = ((uint8_t(*)())thread1.tsk_fptr[3])(1);
    printf("\fn4_ret = %d\n",fn4_ret);

    return 0;
}

```

It compiled with me fine, passed what I want and returned the required data.

---
Tags: arduino-ide, c, pointer, functions
---


# Question
Title: ATTiny85 and DHT11 - Sensor always returning 0
Good day.

I am making a small weather station using ATTiny85, DHT11, and an OLED display.

There are many, many tutorials that explain how this works, and various libraries that show you how to get the DHT11 to work with the ATTiny85 and others that are dedicated to the SSD1306 Oled displays, some even show you how to combine them together. Well, for the better part of 2 days nothing worked for me.

My schematics is as follows:

And here is a picture of the actual thing, working with a CR2032 Coin Cell:

The Libraries I am using are:

My Code is as follows:

```
    //OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/

#include <font6x8.h>
#include <font8x16.h>
#include <num2str.h>
#include <ssd1306xled.h>
#include <ssd1306xled8x16.h>
#include <SSD1306_minimal.h>
#include <TinyWireM.h>
#include <USI_TWI_Master.h>

#define DEG "\xa7" "C"

SSD1306_Mini oled;

char strHum[4];
char strTemp[4];

#include <dht.h>
dht DHT;
#define DHT11_PIN 1

void setup()
{

  TinyWireM.begin(); // initialize I2C lib - comment this out to use with standard arduinos
  oled.init(0x3c);
  oled.clear();

}

void loop()
{

  //            DHT Code goes here                              //

  DHT.read11(DHT11_PIN); //Calling the read function

  float hu  = (DHT.humidity, 1);
  float te  = (DHT.temperature, 1);

  //            OLED Start -- DO NOT CHANGE ANYTHING            //

  //oled.clear();

  oled.startScreen();
  oled.cursorTo(10, 0);
  oled.printString("ATTiny85 & DHT11");

  oled.startScreen();
  oled.cursorTo(12, 9);
  oled.printString("Temp & Humidity");

  oled.startScreen();
  oled.cursorTo(10, 18);
  oled.printString("www.MDChaara.com");

  oled.startScreen();
  oled.cursorTo(0, 27);
  oled.printString("mdchaara@gmail.com");

  oled.startScreen();
  oled.cursorTo(0, 45);
  oled.printString("Humidity(%): ");

  oled.startScreen();
  oled.cursorTo(110, 45);
  oled.printString( itoa(int(hu), strHum, 10));

  oled.startScreen();
  oled.cursorTo(0, 55);
  oled.printString("Temperature(c): ");

  oled.startScreen();
  oled.cursorTo(110, 55);
  oled.printString( itoa(int(te), strTemp, 10));

  //            OLED End          //

  delay(5000);
}

```

Now I know that the OLED code works, and it was a very interesting round or research to get it to work. The DHT code is another story. I have tried 6 different libraries and none of them worked. They all either return 0, 1, or blank readings on the screen.

I have checked if the sensor is working with an Uno and a Nano, works well! I checked the connections, and the soldered parts and did continuity tests, but the issue still remains.

I am asking because I am hoping a fresh set of eyes can pin-point the issue that I am facing. Any help will be highly appreciated.

* Arduino IDE: 1.8.2
* OS: Windows 7 64 bits
* Micro controller: ATTiny85-20PU

Sketch is uploaded to the micro controller using Arduino Uno as a programmer. Sketch is uploaded at Internal 8MHz clock setting.

Thank You.

# Answer
> 1 votes
Ok i tried something like that for myself and thanks to this and ..many other posts and forums/videos i could make myself something that works but with a little other setting like in the start post (other libs ect)

in my case the main reason for the "1" output on the oled was this:

```
  float hu  = (DHT.humidity, 1);    //original

  hu  = (DHT.humidity);       //what worked for me

```

Maybe you can figure out more Problems, my code is shure not perfekt! But maybe it helps someone for a vew steps

```
#include <dht.h>
#include <U8x8lib.h>
#define DHT11_PIN 1
dht DHT;
int temp = 0;
int humi = 0;
char strTemp[4];
char strHumi[4];

U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE);         // Digispark ATTiny85 Pin 0 Data, Pin 2 clock

void setup(void)
{

  u8x8.begin();
  u8x8.setPowerSave(0); //enegergiesparen 0 aus

}

void loop(void)
{

  int chk = DHT.read11(DHT11_PIN);

  temp = (DHT.temperature);
  humi = (DHT.humidity);

  u8x8.setFont(u8x8_font_chroma48medium8_r);
  u8x8.drawString(0,0,"~~~~~~~~~~~~~~~~");
  u8x8.drawString(0,1,"Temperatur");
  u8x8.drawString(1,2,( itoa(int(temp), strTemp, 10)));
  u8x8.drawString(4,2,"Grad Celsius");
  u8x8.drawString(1,3,"--------------");
  u8x8.drawString(0,4,"Luftfeuchtigkeit");
  u8x8.drawString(1,5,( itoa(int(humi), strHumi, 10)));
  u8x8.drawString(4,5,"Prozent");
  u8x8.drawString(0,6,"~~~~~~~~~~~~~~~~");
  delay(200);
}

```

# Answer
> 0 votes
The DHT11 is notoriously slow to respond and often returns null for readings sporadically. I notice in your second circuit you have resistors by the sensor but I cant see what pins they are connected to. You will need pullup for the sensor data line 4K7 usually does the trick.

# Answer
> 0 votes
The DHT works, by specification, with a 3.5V minimally. I think you can expect anything if you don't provide the appropriate voltage, which seems to be only 3V from the picture you show.

source: https://components101.com/dht11-temperature-sensor

---
Tags: arduino-ide, library, attiny
---


# Question
Title: Mac Big Sur don't recognize generic Wemos D1 MINI PRO based ESP-8266EX
I bought one of theses cheaps & generic Wemos D1 MINI PRO with ESP-8266 to make a system to connect my lamp with google home etc. But the problem is to upload the code into wemos. The Arduino IDE do not recognize the USB port that is connected.

When I connect to my Mac the board flashes the blue LED, so I suppose that it's not dead or something. I've tried 5 different cables e nothing. I've read some articles about drivers to install but is only for Sierra or High Sierra. Also, uninstalled and installed the arduino IDE. I installed the ESP8266 Boards in the Boards Manager. I tested it out with an Arduino UNO board and it recognized normally.

I have no idea what to do. I don't have a windows PC in my house to test it out, as well.

Here the pics of the board:

# Answer
You need the CP210x drivers from here.
> 1 votes

---
Tags: esp8266
---


# Question
Title: What is the purpose of F() and FPSTR() in ESP8266WebServer -> FSBrowser?
I found this code sample from the FSBrowser (Flash File System) example in the ESP8266WebServer library:

```
replyServerError(FPSTR(FS_INIT_ERROR));
replyBadRequest(F("DIR ARG MISSING"));

```

I was a bit confused at what `F()` and `FPSTR()` do, so I looked up the source (`WString.h`) and found this:

```
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))

```

Which raised more questions. How does this code work and what does this added complexity gain over just using `char*` or `String` as is?

### EDIT: Added Metrics

Here's the memory usage before and after I removed all 25 instances of F() from a file system class, measured by PlatformIO Project Inspector:

|  | With F() | Without F() | Difference |
| --- | --- | --- | --- |
| RAM Used | 29,488 bytes (36.0%) | 29,792 bytes (36.4%) | +304 bytes |
| Flash Used | 355,312 bytes (34%) | 355,188 bytes (34.0%) | -124 bytes |
| Total (uncompressed) | 359,472 bytes | 359,344 bytes | -128 bytes |

Adding F() decreases RAM usage by 1% and increases Flash by around half that. That's for a single class with 25 instances of F(). For a program containing 20x this code, the difference can be significant. However, you'll run out of RAM before you get there. The space savings will be limited to around 5-8%. Still not nothing.

# Answer
The purpose of the `PSTR()` macro is to configure the string to be used directly from flash memory. The string is then not loaded to dynamic memory at runtime as it would be without PROGMEM specifier set by the macro.

The purpose of the `FPSTR()` macro is to cast a string to 'dummy' FlashStringHelper type to help compiler choose the right overloaded function if dynamic memory and flash memory version of a function is available. An example would be the `print` function.

The `F()` macro combines this two macros. It makes the string a PROGMEM string and casts it to FlashStringHelper.
> 3 votes

---
Tags: esp8266, c++, string
---


# Question
Title: How do I power a linear actuator at different speeds for specified periods of time
I am new to Arduino and wondering if anyone can help me get it programmed correctly. I am using two buttons to control a linear actuator to open and close a barn door. I want it to go a certain speed for a specified period of time... like 3 seconds. Then I want it to slow down and go another 2 seconds. The linear actuator does not have feedback which is fine for the application because it does not have to be precise. Below is the code I copied from the manufacturers website - it works well, but I can’t figure out how to make it go for specified periods of time. Please remember I’ve never used an Arduino before and this is literally a foreign language to me. I’m just hoping someone can tell me what to do. It’s for my house, not for a school project.

\*** ADDENDUM - Thanks for the help. Wish I could post a video... Here is the final code:

```
/* Firgelli Automations
 * Limited or no support: we do not have the resources for Arduino code support
 *
 * Program enables momentary direction control of actuator using push button
 */

int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int RPWM2 = 5; //connect Arduino pin 5 to IBT-2 pin RPWM
int LPWM2 = 6; //connect Arduino pin 6 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 0; // Top speed you can change it between [0-255]
int speed2 = 0; // Low speed you can change it between [0-255]
int speed3 = 0; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(RPWM2, OUTPUT);
  pinMode(LPWM2, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM, 255); // rotate motor with top speed (with PWM set to 255)
    analogWrite(LPWM2, 236); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for x sec
    analogWrite(LPWM, 185); // rotate motor with low speed (with PWM set to 150)
    analogWrite(LPWM2, 181); // rotate motor with low speed (with PWM set to 150)
    delay(1600);               // wait for x sec
    analogWrite(LPWM, 80); // rotate motor with low speed (with PWM set to 150)
    analogWrite(LPWM2, 80); // rotate motor with low speed (with PWM set to 150)
    delay(1400);               // wait for x sec
    analogWrite(LPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(LPWM2, 0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(LPWM2, 0);
    analogWrite(RPWM, 254); // rotate motor with top speed (with PWM set to 255)
    analogWrite(RPWM2, 255); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for x sec
    analogWrite(RPWM, 170); // rotate motor with low speed (with PWM set to 150)
    analogWrite(RPWM2, 170); // rotate motor with low speed (with PWM set to 150)
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 80); // rotate motor with low speed (with PWM set to 150)
    analogWrite(RPWM2, 80); // rotate motor with low speed (with PWM set to 150)
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(RPWM2, 0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM2, 0);
  }
}

```

# Answer
> 1 votes
You can do this easily by using Arduino built-in PWM function and using delay function. But remember that using delay in your code will block your code so if your program just want to sit and wait for 3 seconds at some speed then delay is ok for you else you need to implement Millis function.

first you need to define different speeds as per your requirement remember PWM function has value from 0-255 where 0 in min speed and 255 is top speed. So here I will define speed1 for top speed and speed2 for low speed So now your program will look like this

```
int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 255; // Top speed you can change it between [0-255]
int speed2 = 150; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(LPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(LPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
   // analogWrite(LPWM,0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(RPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(RPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
    // analogWrite(RPWM,0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
  }
}

```

---
Tags: arduino-uno, programming
---


# Question
Title: DigiSpark attiny85 computer not detecting
I purchased a DigiSpark attiny85 off of ebay. Over the weekend I tried to get my computer to recognize the DigisSpark, but it won't recongnize it. When I plug the device in, the 'Device Connection' Sound alerts me and then a second or two the 'Device Disconnection' Sound alerts, then 'Device Connection' Sound, then the 'Device Disconnection' sound. This happens until I unplug the device. The light does turn on, but Windows (10) doesn't recognize the device, it just loops the sounds.

I am trying on a Windows 10 machine. I installed the drivers from the DigiStump Github: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip

I do see 'Digispark Bootloader' in my device manager for a couple of seconds in my device manager.

I tried different cables. I tried to install the drivers on another computer and the same thing happens.

What should I try next? Am I missing other drivers?

# Answer
> 2 votes
Unless, during the short time it shows in device manager, you see that it is missing a driver, it would seem you don't need to do anything further with drivers. You didn't mention it saying it was missing a driver or as an "unrecognized" device, so I'm guessing you mean it doesn't *stay* recognised or that it isn't recognized as a *serial* device. If I'm incorrect in that, do say. The fact that it is showing in device manager for any length of time suggests that your cables are fine.

I'm not a Digispark user, but as far I can understand what you're saying, the connecting and disconnecting (once at least) is expected behaviour:

> In addition remember the Digispark only shows up as a programmable device for **5 seconds**, after that it will start running its code (when it is new and un-programmed this means it will blink) and disappear or act like the USB device you programmed it to act like.

If anything in the sketch (or lack thereof) causes the board to reset or jump to the bootloader, it *would* continually reconnect for 5 second intervals. They documentation suggests should blink, as in run a blink sketch that was put on the board before you received it. But then you got this from ebay, so who knows what they did or did not put on it. I haven't studied the micronucleous bootloader enough to know, but it wouldn't surprise me if it jumps to the sketch area irrespective of whether or not it's unprogrammed. If it *is* unprogrammed then it is probably nop-sliding, for lack of a more appropriate term, right back into the bootloader.

You're not going to see it recognized as a serial port device like a typical Arduino. The bootloader uses a vendor specific protocol that will not list as a COM# (or /dev/ttyXYZ#) device.

Indications are that if you compile the blink sketch and "upload", the IDE will run the micronucleus programming tool which gives you a 60 second window for you to plug the board in, at which point it will load the board with the blink sketch. After which it should blink the LED. If unplugged and replugged, you can expect it to show up for 5 seconds on USB and if left alone should disconnect (electrically) from USB and begin blinking.

---
Tags: digispark
---


# Question
Title: How to control speed of 28BYJ-48 stepper motor without using library?
Iam using 28byj-48 stepper motor and I want to know how to control its speed without using any library. I got to know that we need to add delays in between steps but I don't know how much delay I need to add and how delay effects the rpm. It is very much helpful if anyone suggest me how to do this.

# Answer
A stepper motor always needs a driver. As the ULN2003 (or similar) driver is normally shipped together with the 28byj-48 motor, I will assume, that you have this driver.

The ULN2003 has 6 pins:

* Vcc and ground need to be connected to your power source. Note, that it is risky to connect Vcc to the 5V pin of the Arduino. While that might work, when there is no load on the motor, a loaded stepper motor can draw rather high currents. Letting these current run through the Arduino might fry the voltage regulator or the power switching diode. High currents should always flow past the Arduino, not through it.
* The other 4 pins (which are marked as IN1 to IN4 on my ULN2003 driver board) are for controlling the phases. You need to connect these 4 pins to 4 individual digital outputs on your Arduino. As these are the phases of the stepper motor, you need to activate them in the correct order. You have this pattern

```
  1000
  0100
  0010
  0001

```

for full steps, and this pattern

```
  1000
  1100
  0100
  0110
  0010
  0011
  0001
  1001

```

for half steps. Each digit of each number represents the status of the corresponding phase; 1 means activated/HIGH, 0 means deactivated/LOW. To move the stepper motor forward, you move in the list of phases down. To move backwards, you move up in the list.

When using a stepper motor, the speed is determined by the number of steps per time interval. Let's assume, we want to use `delay()`, which is really easy, though not recommended (see explanation below), we can do steps and `delay()` inbetween:

```
void loop(){
    step();
    delay(10);
}

```

This code would do a step and then delay for 10ms. Thus we have about 1 step every 10ms. With `64*64=4096` steps per revolution (the motor itself seems to have 64 steps; additionally there is a gear with ratio 64 mounted on it; this might be different for you) we get a full revolution every 4.096s. When you use half the `delay()`, the speed will be double: with 5ms delay we get a full rotation every 2.048s. So you can use the `delay()` to set the speed of the motor.

Now we need the `step()` function, that I used above. There are multiple ways of writing this in code. I would propose to put the pins and phases into arrays and iterate through them with a static variable, which holds the current position in our phase pattern. Something like this:

```
//in global scope defining the pins for the phases
int stepper_pins[4] = {2, 3, 4, 5};

void step(bool forward){
    const uint8_t phase_pattern[][4] = {
        {1,0,0,0},
        {0,1,0,0},
        ...
    };
    static uint8_t current_step = 0;
    if(forward){
        current_step = (current_step + 1) % 4;
    } else {
        current_step = (current_step - 1) % 4;
    }
    for(uint8_t i=0;i<4;i++){
        digitalWrite(stepper_pins[i], phase_pattern[current_step][i]);
    }
}

```

We hold the phase pattern in a 2-dimensional array. The variable `current_step` is declared `static`, so it will keeps its value between the executions of the function. Then - depending on the parameter `forward` \- we increment or decrement the current step and take that value modulo 4 (the number of phase patterns). That ensures, that `current_step` stays in the index range of our phase pattern array and will wrap around from the end of the pattern to the start and vice versa. After that, we loop through the 4 stepper pins and set them according to the current element in the `phase_pattern` array. You can easily adept that code for half steps.

Note, that this code is totally untested. Also this can be reached with way less code (at least for full steps), but I think this code is better understandable.

Now: Why not using `delay()`? This function will block the execution of other code. In that time the Arduino is just fiddling thumbs. In general that is considered bad practice. It is good, when you only need that one functionality and no responsiveness. But lets assume, you want to add a button, so that the motor reacts to your button presses. Long `delay()` calls will impact the responsiveness of your code. So instead you could use a non-blocking coding style. In the Arduino world this is easily done with the `millis()` function, which returns the number of milliseconds since startup and thus acts like a clock. Refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE, and to the many tutorials on the web, that you can find with search terms like "Arduino millis tutorial" or something like that.

---

EDIT:

> how your code controlling the motor speed?

The `delay()` call is determining the motor speed. If you want to change the speed, you need to change the value of the delay. You didn't mention any input device, so I just leave the speed constant. But of course you can define a variable for the delay and change that delay based on some input device. How exactly that is done depends on your requirements, mainly what type of input you want to use.

> if we didn't specify any delays in between steps, will it spin at its max rpm?

When you don't use any delay, then most likely your code will run too fast for the motor. The driver will set the motor phases very very fast. So fast, that the motor cannot follow that (because it has a specific inertia). (Much like the wheels of your car can loose the grip on the street and spin without moving the car, the stator of the motor can loose the magnetic grip on the rotor, which leads to further rotating phases, but a rotor, that is standing still) So you reach the maximum speed before that and it depends on the motor, the driver, how much load is on the motors and how much current your power source can give you (I once tried to provide 3 of these motors with a 1A power supply, but they moved very weak, until I upgraded to a bigger power supply, that can provide about 5A, I think). You need to test yourself, how fast you can drive your motors. So try to lower the delays step by step, until the motor cannot move in your setup anymore. Then you have the minimum delay, and the maximum speed.

Note: The `delay()` function won't be accurate for very low delays in the single digit milliseconds. In that case you might wanna use `delayMicroseconds()`, which is more accurate in that range and also can get in you in the microsecond range.
> 3 votes

---
Tags: motor, stepper
---


# Question
Title: I Can't Connect to my MQTT server via arduino
I have mosquitto MQTT installed on my VPS server which I can subscribe and publish to it using paho client thorugh websockets. However when I tried to connect to it through Arduino, I get the following error:

```
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

```

I uploaded the following code to arduino:

```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "IOT";
const char* password = "11112222";
const char* mqtt_server = "burooq.com";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("test", "hello world");
      // ... and resubscribe
      client.subscribe("test");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("test", msg);
  }
}

```

i checked my server mosquitto ports which shows

```
mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP 127.0.0.1:1883 (LISTEN)

```

I checked my conf file and it has

```
listener 1883 localhost

```

so how what's wrong within my code or settings that prevents me from connecting to my server?\`

# Answer
This is the problem:

> mosquitto 10436 mosquitto 4u IPv4 46043 0t0 TCP ***127.0.0.1***:1883 (LISTEN)

Your MQTT server is listening only on port 127.0.0.1. That will accept ***local*** incoming connections only but nothing from another IP address.

The IP 127.0.0.1 is the LOCAL ONLY IP address. You need to reconfigure your MQTT server to listen on either IP 0.0.0.0 or whatever that server's actual IP address is.

Check your mosquitto.conf file and look for the line that begins with "bind\_address":

```
listener 1883 localhost

```

change this to:

```
listener 1883 0.0.0.0

```

and restart your MQTT server.
> 2 votes

---
Tags: mqtt, ubuntu
---


# Question
Title: seeeduino can-bus shield v2: can't read can bus and write on SD card
I'm using a seeeduino V4.0 and a CAN-BUS shield v2.0 with industrial grade SD card.

I'm using the default library given by the wiki of seeed.

I've simulate a can bus with two mcp2515. I can read it without trouble and everything is fine.

I can write/read on the SD card with the exemple given in the SD library.

But when I use this example, the can bus and SD card start without error. The can bus read normally and show the can bus data. But when I read the SD card, the file is created but completly empty. I've tried to modify to write on a .txt instead of .csv and when I try a

```
myFile = SD.open("test.txt", FILE_WRITE);
if (myFile)
{
  ...
}
else
{
  Serial.println("error: file not reachable");
}

```

The "*myFile*" return false.

ps: I don't ask a lot of question here. Sorry for bad formating my question.

# Answer
Despite the "the library example must be correct, It's work for other people before you", I'm not sure a lot of people make it works.

I've seen that even when the mcp2551 don't receive anything on can bus, the SPI bus is saturated by the mcp2551.

The solution was to use a simplest library make for 8MHz cristal chip. Modify it to works with standard 16MHz and use the interrupt pin (pin 2 on board) as interrupt.

If anybody got the same issue, just post a comment here and I'll do a better and more complete response.

Thank you very much @Timemage for your help
> 3 votes

---
Tags: interrupt, spi, sd-card, can-bus
---


# Question
Title: How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?
I'm trying to understand this circuit found here.

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.

# Answer
> 1 votes
Your confusion lies in *what* can "supply" power.

Your assumptions are all correct *for an IO pin*. However the Arduino has *more* than just IO pins. It has power pins.

These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.

So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.

The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).

---
Tags: arduino-uno, motor, transistor
---


# Question
Title: How can I execute two functions at the same time?
```
#include <Servo.h>

Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;

void setup() {
  myservo.attach(servo_pin);
  Serial.begin(9600);
  pinMode(led_pin,OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char serial = Serial.read();
    if (serial == '2') {
      servo();
    }
    if (serial == '1') {
      digitalWrite(led_pin,HIGH);
    } else if (serial == '0') {
      digitalWrite(led_pin,LOW);
    }
  }
  delay(100);
}

void servo() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(5);
  }
  delay(5000);  // problem is here
  for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(pos);
  delay(5);
}

```

When I run this code and send '2', the `servo()` functions start, but it includes a delay function.

Now I want to send '2' and then send '1'. When I do this, the first servo starts, but the LED starts **after** the servo function. I want to start this at the same time.

# Answer
Make little task using `millis` function.

```
// GLOBAL VARIABLE
uint32_t taskMillis = 0;

....

// IN LOOP
if (taskMillis && millis() - taskMillis >= 5000)
{ /* SWITCHES DIRECTION */ }

```

With that code you can make two tasks(one to switch direction, second to move Servo by X deg). Here is video about this topic.

https://www.youtube.com/watch?v=v5SpPXMmHJE

I hope this anwser will help you.
> 1 votes

# Answer
The short answer is no. Delay causes your Arduino to stop dead in its tracks, and do NOTHING else until the specified time has passed. (You can still service interrupt service routines, but ignore that.)

The answer is to rewrite your code to use `millis()` instead of delay. You record the current `millis()` value, and compare the new time to `millis()` to see if enough time has passed.

For the most part you should stop using the `delay()` function and forget exists. It will get you into trouble.

Do a Google search on "Arduino blink without delay" and study the project that comes up to learn this approach.
> 1 votes

---
Tags: timing
---


# Question
Title: Public variable in class not incrementing
I'm not sure what is wrong with my code, but whenever I call `addNewLine`, the `linesInserted` variable is not updating correctly. When I print the value of `linesInserted` inside of the `addNewLine` method, it shows as incrementing, but when I print the value inside of the `draw` method, it shows that it is 0.

I have tried different increment operators (`linesInserted += 1` and `linesInserted = linesInserted + 1`). Oddly enough, when I do `linesInserted = 99` instead of `linesInserted++`, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?

```
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};

```

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board

# Answer
> 3 votes
It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.

First, just a note: The code I'm testing with (because it compiles) is the code out of your github repo, which used a `char` type variable for `linesInserted` and had a commented-out `println(linesInserted);`, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters. So that might may have been confusing you. I uncommented it and added a `, DEC)` parameter to it (rather than casting) to coerce println into treating it as an int.

I tested your code without the display library in a PC environment to allow me to run valgrind on it. It didn't find anything; I wasn't necessarily expecting it to. But, I did crudely instrument your code in this enviroment to see that you're calling `malloc()`/`new` 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're `new`-ing tiny four-character chunks.

Then I ran your code as compiled for an AVR. Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.

The primary finding is that you're dangerously close to "running out" of memory:

```
000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                                 [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

```

There's 120 byte separation between the edge of the heap and the stack pointer. The implementation of the `malloc` that I ran this under checks to see whether or the the stack pointer is within `128` (`__malloc_margin`) bytes. As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate. However adding a single additional call to `addNewLine` was enough to cause `malloc()` via `new` to fail. So you are indeed right on the edge. And you have **no** checks to see if `malloc` or `new` returning `nullptr`.

You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time. So that's about 248 bytes waste in just heap structure.

I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening. In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:

```
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

```

With generated code looking like:

```
0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

```

So, if `malloc()` fails, apparently the `new` statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh. I think this is because technically you're calling the normal new that is supposed to throw an exception on failure. But there are no exceptions with the way avr-g++ is set up for Arduino. As it exists in ArduinoCore-avr version 1.8.3, the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails. Normally you would call the std::nothrow version of new\[\] that returns nullptr on failure, as in:

```
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here

```

However, there's no facility to do that in 1.8.3. The master as of writing appears to have addressed this, but that's not shipping yet.

---

The short answer to this is basically: **Don't do that.** That is:

* Avoid dynamic allocation altogether where possible.
* This was mentioned in the comments, but it's worth repeating, use flash where you can. Besides getting your character data into `PROGMEM`, you also have some string literals that can be moved into flash by way of `F()`.
* To the extent that you're doing dynamic allocation requests:

+ Check to see that they're actually succeeding
    + Make as few requests as possible.
    + Do them up-front at the beginning of the code. The "up-front" part you're more or less already doing, so that much is good.
    + It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you *not* use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed. Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call `abort()` if `malloc()` returns `nullptr`, at a minimum, if not something more sensible. Otherwise, this could drive you insane.

# Answer
> 0 votes
It would be good to see how this is used rather than just having a class with no context. But I'd start by removing unnecessary parts, like the display pointer, and you could always use a simple program, like ideone.com to compile quickly and check for errors.

As I read through it I see 2 flaws with memory management. This block is using the size of a char pointer instead of a character. I don't understand what you want this code to do.

```
(char**) malloc(sizeof(char*) * Char.sizeOfLines);

```

Try something more like:

```
(char**) malloc(sizeof(char) * <numberOfCharsPerLine> * Char.sizeOfLines);

```

But then even though you're allocating memory for a whole block of lines, then each time you add a new one, you're allocating memory for a new line.

```
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

```

Instead try something like:

```
lines[linesInserted - 1][0] = startX;
lines[linesInserted - 1][1] = startY;
...

```

---
Tags: arduino-uno, c++, class
---


title: USB FT232 driver on M1 mini

text:
# Question
Title: USB FT232 driver on M1 mini
I've scored a couple Nanos with FT232RL chips but can't see them on my brand new M1 mini. Can someone point me at how to determine whether v11.1 supports this USB chip?

It appears that the device is being instantiated but the Arduino IDE gets no response to the Get Board Info.

```
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    AR0JT9YB
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02214000 / 20
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

```

Executing the ioreg mentioned by @st2000 gives;

```
+-o Root  <class IORegistryEntry, id 0x100000100, retain 31>
  +-o AppleT8103USBXHCI@00000000  <class AppleT8103USBXHCI, id 0x100000291, registered, matched, active, busy 0 (1676 ms), retain 328>
  | +-o Extreme SSD@00200000  <class IOUSBHostDevice, id 0x10000081d, registered, matched, active, busy 0 (219 ms), retain 132>
  +-o AppleT8103USBXHCI@01000000  <class AppleT8103USBXHCI, id 0x100000295, registered, matched, active, busy 0 (4 ms), retain 39>
  +-o AppleT8103USBXHCIFL1100@02000000  <class AppleT8103USBXHCIFL1100, id 0x1000006eb, registered, matched, active, busy 0 (1220 ms), retain 494>
    +-o Keyboard Hub@02100000  <class IOUSBHostDevice, id 0x10000071c, registered, matched, active, busy 0 (164 ms), retain 30>
    | +-o Apple Keyboard@02120000  <class IOUSBHostDevice, id 0x100000805, registered, matched, active, busy 0 (162 ms), retain 32>
    +-o 4-Port USB 2.0 Hub@02200000  <class IOUSBHostDevice, id 0x100000730, registered, matched, active, busy 0 (826 ms), retain 46>
    | +-o 4-Port USB 2.0 Hub@02230000  <class IOUSBHostDevice, id 0x100000785, registered, matched, active, busy 0 (11 ms), retain 42>
    | +-o 4-Port USB 2.0 Hub@02220000  <class IOUSBHostDevice, id 0x100000791, registered, matched, active, busy 0 (16 ms), retain 43>
    | | +-o Backup+ Hub@02223000  <class IOUSBHostDevice, id 0x1000007dc, registered, matched, active, busy 0 (6 ms), retain 41>
    | +-o 4-Port USB 2.0 Hub@02210000  <class IOUSBHostDevice, id 0x10000079d, registered, matched, active, busy 0 (776 ms), retain 43>
    | | +-o FT232R USB UART@02214000  <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>
    | +-o 4-Port USB 2.0 Hub@02240000  <class IOUSBHostDevice, id 0x1000007b6, registered, matched, active, busy 0 (12 ms), retain 42>
    +-o 4-Port USB 3.0 Hub@02600000  <class IOUSBHostDevice, id 0x100000749, registered, matched, active, busy 0 (231 ms), retain 46>
      +-o 4-Port USB 3.0 Hub@02620000  <class IOUSBHostDevice, id 0x10000075e, registered, matched, active, busy 0 (170 ms), retain 43>
      | +-o Backup+ Hub@02623000  <class IOUSBHostDevice, id 0x1000007c3, registered, matched, active, busy 0 (155 ms), retain 41>
      |   +-o Backup+ Hub BK@02623100  <class IOUSBHostDevice, id 0x1000007ee, registered, matched, active, busy 0 (147 ms), retain 131>
      +-o 4-Port USB 3.0 Hub@02640000  <class IOUSBHostDevice, id 0x100000763, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02630000  <class IOUSBHostDevice, id 0x100000775, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02610000  <class IOUSBHostDevice, id 0x1000007a9, registered, matched, active, busy 0 (16 ms), retain 42>

```

Which does not appear to contain the device afai can see. Any know if this means a new device for Big Sur is indicated as per Majenko♦ ?

# Answer
> 2 votes
A MAC is usually (unless it is really old) running a derivative of Unix. I would open a console install and use "lsusb" to list out all the USB connected devices.

A (Linux) example of lsusb:

```
$ lsusb
Bus 001 Device 004: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

```

I would do this with and with out the Arduino FTDI chip connected and look for the difference. This stackexchange question/answer contains how to do this on a MAC or use other MAC commands to do the same. As pointed out in the comments the more native MAC command is:

```
ioreg -p IOUSB

```

Note, if you have fake FTDI chips there was a time when the FTDI driver that Windows ran would brick the fake FTDI chip. I think it would assign the vendor and device IDs both to zero. You should be able to see this with the "lsusb" command.

# Answer
> 2 votes
As an addendum to @st2000's answer, it's worth noting that OS X comes with a basic driver for FTDI built in. However if your device uses a non-standard VID or PID it will not work. At the time of writing this, according to this forum thread, FTDI have not yet written an updated driver for Big Sur, and seem to be struggling to do so (they have been writing one for the past year and still haven't managed it).

This should not apply to an Arduino that uses an FTDI with default settings, but worth noting for some custom devices.

# Answer
> 2 votes
I run macOS Big Sur on M1 silicon (a new machine installed in the last month) and also FT232RL interfaces (e.g., cheap HW-417-V1.2 unit). I just went back through my downloads used in setting up the machine, as far as I can recall I did *not* have to download the FTDI driver which I used to on the previous older machine. This supports @Majenko's answer regarding a built in driver. I read a little more about this here. If anyone can point to more information about the built in driver that would be awesome.

I use `ls /dev/cu.*` in a terminal window to check which USB devices are plugged in. Mine shows up as `/dev/cu.usbserial-A5XK3RJT`

On the macOS desktop, the *\[Apple Icon\]\About this Mac\System Report\USB* information (which I think is a GUI representation of the ioreg mentioned above?) shows the device as:

```
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    A5XK3RJT
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02240000 / 17
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

```

If non-standard PIDs or VIDs are causing devices to be blocked, then a possibility (which I have not tested) might be just to reflash the config on the FTDI device see: dangerousprototypes - how to get a nicely named serial device.

Use `ls /dev/cu.*` in a terminal window to see if the device is showing as a call-up USB device. Then in Arduino IDE rather than using "Get Board Info", just set Tools/Port to that USB port and try to upload a sketch. The port should show up as `/dev/cu.usbserial-AR0JT9YB` or similar.

The FTDR device is in the `ioreg` output you posted, I believe it's hiding there as:

```
FT232R USB UART@02214000 <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>

```

---
Tags: arduino-nano
---


# Question
Title: Good button debouncing/stateChange library
I need debouncing/stateChange for a push button configuration. Is there a good library for debouncing/stateChange buttons in Arduino (without delay)?

# Answer
> 7 votes
The Button library in the Arduino playground works perfectly.

# Answer
> 5 votes
I think what you need is an interrupt-based detection of the button. This way, your Arduino can do what it needs to do without stalling for the delay function.

```
// Example code usage

int pin = 13; // LED on board
int interrupt0pin = 2; // pin attached to int0 if you're using Uno
int buttonState;

void setup()
{
  pinMode(pin, OUTPUT);
  pinMode(interrupt0pin, INPUT);
  attachInterrupt(0, buttonUpdate, CHANGE); // calls buttonUpdate() when button input changes (you can also use high-to-low or low-to-high)
}

void loop()
{
    if (buttonState)
        digitalWrite(pin, HIGH);
    else
        digitalWrite(pin, LOW);
}

void buttonUpdate()
{
  buttonState = digitalRead(interrupt0pin);
  delay(50); // 50ms works for most switches - adjustable
}

```

Find out more here: http://arduino.cc/en/Reference/AttachInterrupt

Good luck!

# Answer
> 2 votes
You can use my library

https://github.com/anlgncr/Buttons

This library lets you use buttons as many as you wish with only one instance of class.

You can also call a function when button is pushed or released.

# Answer
> 2 votes
I'm on this subject right now and I'll use this to note my findings.

I found many libs on this, and this is my wishlist:

* support many buttons
* support toggles or switches
* support debouncing and maybe de-glitching
* non-blocking functions
* support long-press, double-click

Candidates:

Here are my findings for each lib:

### **Switch**

* it's really easy to use
* you can use it as a switch or a button, same class handles both
* supports callbacks
* supports many buttons
* supports debouncing and de-glitching
* supports double click and long press
* most configs have defaults, and you define them at the Button setup
* as I use PlatformIO, some warnings from this lib are shown while compiling my project

### **EasyButton**

* it's really easy to use
* very good docs
* supports callbacks
* supports many buttons
* does not support toggles/switches, although you can simulate it by checking the `wasPressed` and `wasReleased` properties
* supports debouncing
* supports double click, triple click, or a given number of clicks
* you may have a different action for single, double or triple click for the same button
* supports multiple times of long press, if needed
* most configs have defaults, and you define them at the Button setup

### **JC Button**

* easy to use, not as easy as Switch and EasyButton tough
* you can use it as a `Button` or a switch (`ToggleButton`), different class for each
* supports many buttons
* does not support callbacks
* supports debouncing
* supports multiple times of long press, if needed
* most configs have defaults, and you may define them at the Button setup, but long press time is something you define while querying it's status rather than defining it once at the button setup

### **ezButton**

* easy to use, not as easy as Switch and EasyButton tough
* supports many buttons
* does not support toggles/switches, although you can simulate it by checking the `isPressed` and `isReleased` events
* does not support long press
* does not support callbacks
* supports debouncing, does not debounce by default (you must call `setDebounceTime` on setup)
* supports an easy way to count button clicks

### Veredict

I chose avdweb/Switch. Reasons:

* in terms of debouncing AND de-glitching, it did better according to my tests
* I need a solution for Buttons and Switches, and it provides them in the same class

# Answer
> 1 votes
I can receommend the following library:

http://log.liminastudio.com/itp/physical-computing/arduino-a-new-improved-button-library-with-some-handy-features https://github.com/virgildisgr4ce/Button

On the website you will find some examples on how to use it. I have implemented this library already in several sketches and it works very reliably.

# Answer
> 1 votes
You can put a capacitor in parallel with the switch - 100nf should do the trick. Some capacitors have a minus on the packaging, next to one of the pins - if so, make sure that side is to negative (ground).

# Answer
> 1 votes
I put this together for a guy the other day. Its not a library but it achieves reading and debouncing all of your buttons and works very well maybe it could help you

```
const byte numbuttons = 15;                                                     // DEFINE HOW MAY DIGITAL INPUTS TO MONITOR(NUMBER OF BELOW PINS TO USE)
const byte digitalpin[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16 };   // DECLARE ALL DIGITAL INPUT PINS WHICH CAN BE USED IN THE ORDER IN WHICH THEY WILL BE PHYSICALLY USED(DONT INCLUDE ANY PINS USED FOR OTHER THINGS
const byte debouncetime = 50;                                                   // THIS VALUE IS THE TIME TO WAIT BEFORE RECHECKING (FOR DEBOUNCE
byte readstate[numbuttons];                                                     // READ ARRAY
byte laststate[numbuttons];                                                     // HOLDS THE BUTTON LAST STATE FOR STATE CHANGE DETECTION
byte NumBut;                                                                     // THIS IS THE VARIABLE FOR DIGITAL FORLOOP COUNTER
unsigned long checktime;                                            // RECORDS THE TIMES (IN MILLIS() TO RECHECK THE STATE FOR EACH BUTTON. FOR DEBOUCING

byte CURRENT_SETTING;
void setup() {

  // SET INITIAL STATES FOR DIGITALS
  for (NumBut = 0; NumBut < numbuttons; NumBut++) {
    pinMode(digitalpin[NumBut], INPUT_PULLUP);
    laststate[NumBut] = digitalRead (digitalpin[NumBut]);
    checktime = 0;
  }
}

void loop() {
  //call the read button method
  READBUTTONS();
  PROGRAM_OUTPUT();
}

void READBUTTONS() {
  for (NumBut = 0; NumBut < numbuttons; NumBut++) {

    readstate[NumBut] = (digitalRead (digitalpin[NumBut]));                                                                   // READ DIGITAL INPUTS INTO ARRAY

    if (readstate[NumBut] != laststate[NumBut] && millis() >= checktime )   {
      if (readstate[NumBut] == 0 && laststate[NumBut] == 1) {
        checktime = millis() + debouncetime;
        CURRENT_SETTING = NumBut;
      }
      laststate[NumBut] = readstate[NumBut];
    }
  }
}

void PROGRAM_OUTPUT(){
    switch ( CURRENT_SETTING ) {
    case 0:   //do something to turn off output break;
    case 1:   //do something with setting 1 break;
    case 2:   //do something with setting 2 break;
    case 3:   //do something with setting 3 break;
    default:    break;
}
}

```

---
Tags: arduino-uno, button, debounce
---


# Question
Title: "SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope
I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.

My sketch previously ran on my laptop with no problems. Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.

If I try to compile it for Mega, there are no problems.

I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.

# Answer
Ahhhh, I figured it out. I had to add `#include "Arduino.h"` to the .cpp file.
> 1 votes

---
Tags: serial, samd21g
---


title: esp32-cam stuck in repeat boot

text:
# Question
Title: esp32-cam stuck in repeat boot
I am trying to bring the esp32 example code live. I am able to upload the image error free but when I remove the jumper and then press the reset switch, instead of seeing it logon to my network via serial monitor, I just get this repeating over and over and over again.

```
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

Brownout detector was triggered

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

Brownout detector was triggered

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

Brownout detector was triggered

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8
ets Jun  8 2016 00:22:57

```

How do I boot an esp32-cam correctly?

code:

```
#include "esp_camera.h"
#include <WiFi.h>

//
// WARNING!!! Make sure that you have either selected ESP32 Wrover Module,
//            or another board which has PSRAM enabled
//

// Select camera model
//#define CAMERA_MODEL_WROVER_KIT
//#define CAMERA_MODEL_ESP_EYE
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE
#define CAMERA_MODEL_AI_THINKER

#include "camera_pins.h"

const char* ssid = "getAjobFool";
const char* password = "andreasd1";

void startCameraServer();

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

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //init with high specs to pre-allocate larger buffers
  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  //initial sensors are flipped vertically and colors are a bit saturated
  if (s->id.PID == OV3660_PID) {
    s->set_vflip(s, 1);//flip it back
    s->set_brightness(s, 1);//up the blightness just a bit
    s->set_saturation(s, -2);//lower the saturation
  }
  //drop down frame size for higher initial frame rate
  s->set_framesize(s, FRAMESIZE_QVGA);

#if defined(CAMERA_MODEL_M5STACK_WIDE)
  s->set_vflip(s, 1);
  s->set_hmirror(s, 1);
#endif

  WiFi.begin(ssid, password);

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

  startCameraServer();

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");
}

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

```

# Answer
The message:

> Brownout detector was triggered

is being generated by your ESP32 because there is a problem with the Vcc power to the module.

Check the following:

1. Your USB cable. Some cables are just plain cheap and can't supply the power the ESP32 needs. Get a better one.
2. Some PCs are not able to supply enough power from their USB ports to supply the ESP32, try a powered USB hub and/or a different PC.
3. Some ESP32 modules are poorly made and may have bad solder joints or low quality components. Your only real option here is to buy a better ESP32.
4. If you are powering other components from the ESP32's power supply, stop it. Power any accessories separately.
> 2 votes

---
Tags: esp32, bootloader, networking, camera
---


# Question
Title: Time signal. Determine the presence of pulses and their duration
I want to detect the exact time signal from an FM radio station. The signal is transmitted in the form of 5 short pulses and one long one. My task is to determine the presence of a pulse in the audio data stream and its duration. It is understood that the signal is received by the radio receiver and then the audio signal is fed to the atmega microcontroller. The pulse duration varies in the range of 100 ... 560 ms

How can you control the appearance of these pulses using a microcontroller, and also determine their duration? Below is an example of computer processing. The same is required to be implemented on a microcontroller.

1. I have a reference recorded signal in WAV format. This recorded signal from the output of the radio receiver contains both the speaker's speech, music, and the **exact time signal**:
2. I know the time signal is centered at 1 kHz, so apply filtering to this signal. The filter has the following frequency response:

The signal after the filter looks like:

3. It remains to apply the threshold device and duration selection. However, I do all this in an audio editor to understand the ongoing processes. In fact, I need to implement this on an arduino, so I really hope for your tips, because I don't know how to implement a filter on an arduino for one frequency, and I also don't know how to make a pulse detector and a meter for its parameters.

Below is the result of homodyne, the method suggested in the comments. On the test signal, the algorithm was able to identify the required pulses! It remains to write a sketch where there is a detection threshold and definition of the duration! I was able to write a condition, when the threshold is exceeded, the LED turns on, and turns off otherwise. But I don't know how to make the definition of duration yet ...

*Added after a few days:*

I was able to assemble the entire structure, the sketch below does the following:

1. Listens to the audio signal coming to the analog input of the arduino from the radio receiver on the RDA5807M microcircuit, through an amplifier on one transistor, which provides signal amplification and offset to the positive range.
2. Performs homodyne processing: selects only the signal with a frequency of 1 kHz, all other frequencies are suppressed
3. Selects the optimal detection threshold for finding the exact time signal of 1 kHz frequency at the background level.
4. Calculates the duration of each pulse
5. Finds the exact time by the last impulse using the recalculation formula.

Thus, at the moment I get the exact time digit in the serial port monitor.

But the end result I want to get is setting the resulting digit on a seven-segment display. Having looked at the sketches of his work, I found that the values in the loop are constantly processed there, which again slows down the microcontroller, but for me this is unacceptable. As I understand it, you need to write a separate function into which you pass the value of the hour and set this value on the indicator only once an hour. But I don’t know how to implement it. I ask for help!

```
/ * Last edited on January 25, 2021.
   1 kHz homodyne signal detection

  This program continuously samples analog input A0 and uses a homodyne
  detection circuitry for signal identification at 1 kHz (+/- 24 Hz at -3 dB).

  The A / D converter is set to "free running mode" and takes one sample every 104 µs.
  The samples are multiplied by two generated 1 kHz signals ("local oscillator") in quadrature to each other.
  The products are then low-pass filtered with a time constant of 64 sampling periods (6.656 ms),
  which gives (I, Q) signals with a bandwidth of 24 Hz.
  Finally, the signal strength is calculated as I ^ 2 + Q ^ 2.

  The program is designed for Arduino Uno and will probably work on any AVR based Arduino,
  having an ADC and operating at a frequency of 16 MHz.

  For a detailed explanation, see
  http://arduino.stackexchange.com/a/21175

  Posted by: 2016 Edgar Bonet Orozco.
* /

// Here is everything related to the parameters of the RDA5807M receiver:
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
#define RDA5807M_REG_RSSI 0x0B
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word (0x0001)
#define RDA5807M_FLG_TUNE word (0x0010)
// masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word (0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

uint8_t volume = 7; // 0..15
uint16_t freq = 938; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;
// Receiver end

unsigned long startTime; // Turn on two timers, this
unsigned long elapsedTime; // and this one
int threshold = 300; // Set the maximum noise level
boolean timing = false; // I do not know...

#include <util / atomic.h>

// The analog input used must be between A0 and A5.
const uint8_t analog_in = 0;

// The frequency we want to define, in Hz.
const float SIGNAL_FREQ = 1000.0;

// Time bits.
const float SAMPLING_FREQ = F_CPU / (128 * 13.0); // 9.615 kHz
const long PHASE_INC = round (SIGNAL_FREQ / SAMPLING_FREQ * (1L << 16));
const int LOG_TAU = 6; // tau = 64 / SAMPLING_FREQ = 6.656 ms

// Set the ADC to constant conversion mode "free running mode"
static void configure_adc ()
{
  ADMUX = _BV (REFS0) // ref = AVCC
           | _BV (ADLAR) // left adjust result
           | analog_in; // input channel
  ADCSRB = 0; // free running mode
  ADCSRA = _BV (ADEN) // enable
           | _BV (ADSC) // start conversion
           | _BV (ADATE) // auto trigger enable
           | _BV (ADIF) // clear interrupt flag
           | _BV (ADIE) // interrupt enable
           | 7; // prescaler = 128
}

// Demodulated (I, Q) amplitudes.
volatile int16_t signal_I, signal_Q;

// Interrupt handler is called every time the ADC is ready to read.
ISR (ADC_vect)
{
  // Read the ADC and convert to a signed number.
  int8_t sample = ADCH - 128;

  // Update the phase of the local oscillator.
  static uint16_t phase;
  phase + = PHASE_INC;

  // Multiply samples by square waves in quadrature.
  int8_t x = sample;
  if (((phase >> 8) + 0x00) & 0x80) x = -1 - x;
  int8_t y = sample;
  if (((phase >> 8) + 0x40) & 0x80) y = -1 - y;

  // First order low pass filter.
  signal_I + = x - (signal_I >> LOG_TAU);
  signal_Q + = y - (signal_Q >> LOG_TAU);
}

/ * Return the power reading. * /
static uint16_t get_power_reading ()
{
  int16_t I, Q;
  ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
    I = signal_I;
    Q = signal_Q;
  }
  return sq ((int8_t) (I >> LOG_TAU)) + sq ((int8_t) (Q >> LOG_TAU));
}

// *********************************************** ***********************
void setup ()
{
  configure_adc ();
  Serial.begin (9600);

  // Receiver start:
  Serial.begin (9600);
  Wire.begin ();
  // Register 02h - enable, settings
  reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  setRegister (RDA5807M_REG_CONFIG, reg02h);

  // And then we decided to further strengthen the bass: (I don't need this, I need to somehow remove it)
  reg02h | = RDA5807M_FLG_BASS;
  setRegister (RDA5807M_REG_CONFIG, reg02h);

  // Register 03h - select radio station
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister (RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);
// Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister (RDA5807M_REG_VOLUME); // Read the current value
  reg05h & = ~ RDA5807M_VOLUME_MASK; // Reset the VOLUME bits
  reg05h | = volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
  setRegister (RDA5807M_REG_VOLUME, reg05h);
  // Receiver end:
}

void loop ()
{
  // Print power readings every 8ms.
  static const uint16_t print_period = 8;
  static uint16_t last_print;
  uint16_t now = millis ();
  if (now - last_print> = print_period) {
    //Serial.println (get_power_reading ()); // Build a graph by which you can determine the optimal threshold
    // If the signal has exceeded the threshold, start timing:
    if (get_power_reading ()> threshold &&! timing)
    {
      startTime = millis ();
      timing = true;
    }
    // If the signal is below the threshold, stop the countdown and display the amount of time passed - the pulse duration:
    if (get_power_reading () <= threshold && timing)
    {
      elapsedTime = millis () - startTime;
      timing = false;
      //Serial.println(elapsedTime);
      if (elapsedTime> = 80 && elapsedTime <= 580)
      {
        int h = floor ((elapsedTime - 100) / 20); // Get the time in hours, but there are 6 pulses, but only the last one is needed.
        //Serial.println(h);
        // "valround" --- Round to the nearest integer,
        // "floor (x)" --- Round down to integer
        if (h> = 1 && h <= 24) // If the time is defined as abnormal, beyond reasonable limits, then simply forget it:
        {
          Serial.println ("Exact time:");
          Serial.print (h);
          Serial.println (": 00");
        }
      }
    }
    last_print + = print_period;
  }
}

// Receiver start:
void setRegister (uint8_t reg, const uint16_t value) {
  Wire.beginTransmission (0x11);
  Wire.write (reg);
  Wire.write (highByte (value));
  Wire.write (lowByte (value));
  Wire.endTransmission (true);
}

uint16_t getRegister (uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission (RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write (reg);
  Wire.endTransmission (false);
  Wire.requestFrom (0x11, 2, true);
  result = (uint16_t) Wire.read () << 8;
  result | = Wire.read ();
  return result;
}
// receiver end

```

# Answer
If the voice and music are superimposed on top of the signal you are looking for, that will make matters quite difficult. The first thing you have to do is filter out all the unwanted sound. The limit on how aggressively you can filter is given by the width of the pulses. If you want to detect 100 ms pulses, your filter width should probably be more than 10 Hz. The filter you used in your test is way larger than that.

Given the limited processing power of your typical Arduino, it may be preferable to do all the signal conditioning in the analog domain, prior to digitizing it on the Arduino. If you really have to do everything in the Arduino, you will still have to adjust the amplitude and the offset of the signal in the analog domain so that it fits the range of the ADC.

For implementing a narrow-band filter on the Arduino itself, I generally recommend to use an homodyne detection scheme. This can give you very narrow filters at a minimal processing cost. See this other answer where I discuss the working of the scheme, and provide a link to an implementation.

If you have something similar to an Uno, you should be able to load that sketch directly, although you may want to tweak the time constant in order to make the filter narrower. You can then send it your test signal, collect back the power readings sent by the sketch through the serial port, and plot those. This should give you a new test signal for prototyping the next stages of your processing pipeline. If all goes well, you would just have to set a threshold for detecting the pulses, and then have some condition on the length of the detected pulses to sort out spurious pulses from legit ones.

**Edit**: I suggested using a threshold on the detected power for deciding when there is a pulse and when there is not. However, if the power signal is noisy, this simple scheme may not be good enough.

One possible way to reduce the noise is to increase the time constant of the filter by increasing `LOG_TAU`. Do not set it above 8, otherwise it may overflow some variables. Also note that, the larger the time constant, the lower the bandwidth, which can be an issue if the frequencies are not very accurate.

Another option is to low-pass filter the power readings. This can be done on a sub-sampled signal in order to lower the processing cost.

Finally, for deciding whether there is a pulse or not, it can be useful to add some hysteresis to the detection, basically simulating a Schmitt trigger. This is simply accomplished by replacing the detection threshold with two distinct thresholds: a high one for the “no pulse” → “pulse” transition, and a lower one for the reverse transition:

```
const uint16_t LOW_THRESHOLD  = ...;
const uint16_t HIGH_THRESHOLD = ...;

// within loop:
static enum { NO_PULSE, PULSE } state = NO_PULSE;
uint16_t power = get_power_reading();
if (state == NO_PULSE && power >= HIGH_THRESHOLD) {
    state = PULSE;
    register_pulse_start();
}
if (state == PULSE && power < LOW_THRESHOLD) {
    state = NO_PULSE;
    register_pulse_end();
}

```
> 1 votes

---
Tags: timers, analogread, voltage-level, audio, frequency
---


# Question
Title: How to implement brown out detector arduino ESP32?
We are using ESP32 with arduino sdk for developing our application. In our application we need to implement BOD to detect with specific voltage level.

Basically we want to set specific voltage level and when device goes to power off it will detect and trigger interrupt. How I can set interrupt for brown out detect?

we have only this code:

```
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"

void setup() {
  Serial.begin(115200);
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 1); //enable brownout detector
}

void loop() {
  Serial.println("Start BOD");
  delay(1000);
}

```

# Answer
> 1 votes
The ESP32's on-board BOD is mainly intended to inhibit operations that might cause corruption if they happened with too low a voltage. There is a very unpredictable amount of time for the code in the ESP32 to do anything but effectively halt.

If that's what you want, then you have enabled it in your code above.

If you want to detect a power outage, for example, and log something, then you need two things:

1. A reliable detector that the power has failed.
2. A battery or capacitor-based circuit that will continue the ESP32's power for long enough for you to do what you need to do.

So when "1" happens you set a GPIO pin on the ESP32 which triggers your interrupt and you do what you need to do while the power remains stable.

---
Tags: arduino-ide, interrupt, esp32, voltage-level
---


# Question
Title: FreeRTOS library (AVR_ATmega328PB_Xplained_mini_GCC) versus FreeRTOS for Arduino boards
I am researching different IoT development boards and found that Espressif uses the IDF framework. When I looked at the source code it uses FreeRTOS libraries.

I have an Arduino Uno and I want to use FreeRTOS for programming it. I found that FreeRTOS has multiple libraries that support different microcontrollers. Arduino Uno has an ATmega328P and FreeRTOS has libraries for it.

I also found libraries for the Arduino family of boards.

What is the difference between these two libraries?

# Answer
**ATmega328PB** is not the same MCU as used by Arduino boards. Those use **ATmega328P** (no B). ATmega328PB is a mostly compatible successor and offers more timers, built-in touch functionality and more but does not come in large DIP packages. Arduino uses the older ATmega328P.
> 0 votes

---
Tags: arduino-uno, atmega328
---


# Question
Title: Resolved: ESP8266 works when arduino UNO reset pin is grounded
I'm setting up PIR and esp8266 with arduino UNO. First my esp8266 doesn't work after alot of research my esp8266 start working when I put arduino UNO reset pin to ground. But now my arduino UNO does not run any program and I'm not able to use PIR with this wifi module. Any help will be appreciated

Only one extra thing is that reset pin is set to GND pin.

# Answer
> 5 votes
The RESET of the UNO puts the ATMega328P (the MCU of the UNO) into an electrically inert state when it is connected to GND. It is not *supposed* to be running your sketch when it is being held in reset. It is, roughly speaking, electrically disconnected from everything else on the board. This allows you to use the UNO as though it were a USB to TTL serial cable.

If you want to be able to run a sketch on the UNO while it uses the ESP8266, you'll need to **not** hold reset to GND and you'll also, practically speaking, need to choose a different set of pins for communicating with it, as D0 and D1 on the UNO are the same signals used to for the ATMega328P to talk to the host and used for programming the UNO via its bootloader. On the UNO, you'd instead need to use SoftwareSerial (or something similar) and pins other than D0 and D1. **\[Update: see the original poster's own answer containing the guide they ultimately used, making use of SoftwareSerial on pins 10 and 11\]**

The ESP-01 can run Arduino sketches using the ESP8266 Arduino core and it may make a great deal more sense to not involve the UNO at all, and instead connect the distance sensor more or less directly to the ESP8266.

# Answer
> 1 votes
So, I got it working with this information on this blog Few things, my serial.begin(115200) where as in blog its 9600 Thanks @timemage for moving me in right direction \[1\]: https://medium.com/@cgrant/using-the-esp8266-wifi-module-with-arduino-uno-publishing-to-thingspeak-99fc77122e82

---
Tags: arduino-uno, esp8266
---


# Question
Title: Connecting the cathode of a diode to the output of a multiplexer
From the image, the diodes share the same anode which is driven by 'Do Something'. My question is: through using Arduino IDE, what code should I write that connects the output of the multiplexer (Z) to a specific diode's cathode (Y0 or Y1 or ... or Y7), which in turn is connected to 'Do Something' that drives the cathode probably? In this code, I want the ESP32 microcontroller to connect this cathode to 'Do Something' for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds \[where no diodes' cathodes are connected to Z\] (and so on: in a continuous loop).

Here some code I found online but not sure what needs to be added to get the proper functionality:

```
int outputs[4] = {4,0,2}; // pins for selecting LED
int inhibit_pin = 15; // pin for turning off all LEDs

void setup() {
  for(int i;i<3;i++){
    pinMode(outputs[i],OUTPUT); // output selection for LED control
  }
  pinMode(inhibit_pin,OUTPUT);
  digitalWrite(inhibit_pin,LOW); // raise high to disable all

}

void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){
    // turn on LEDs based on bit conversion
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    delay(100); // delay .1 sec
  }
}

```

I don't think that "digitalWrite(outputs,bitRead(j,i));" is actually needed and I am not quite sure of what it does.

# Answer
> 0 votes
The code you have posted should loop through the 8 possible MUX in/out pins (Y0...Y7) connecting one at a time to pin 3.

Assuming your Y0 through Y7 are each connected to a pin on your "do something" block, the mux should connect each of the 7 pins on your "do something" to Z.

One problem I see is that your code changes the pin select values on the MUX while the MUX is enabled. As you execute your `for(int i=0;i<3;i++)` loop and toggle the different select bits to S0...S2, the MUX will connect different Y0...Y7 pins to Z, until it settles on the final set of values for S0...S2. You should really set inhibit\_pin to HIGH (disabling the mux before entering your `for(int i=0;i<3;i++)` loop, and then set it to LOW again at the end of the `i` loop and before the delay. (to re-enable the MUX at the now-completely-selected pin.)

Your description is a little hard to follow, but it sounds like that is what you want.

If you want each pin to be connected for 3 seconds, then not connected to any pin for .1 seconds before moving on to the next pin, you might rewrite your loop like this:

```
void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){

    // disable the mux while selecting a pin
    digitalWrite(inhibit_pin,HIGH);

    // select a MUX pin
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    // re-enable the mux now that we've selected a pin
    digitalWrite(inhibit_pin,LOW);

    delay(3000); // leave the pin active for 3 seconds.

    // disable the mux for .1 seconds
    digitalWrite(inhibit_pin,HIGH);
    delay(100);
  }
}

```

---
Tags: arduino-ide, led, esp32, multiplexer
---


# Question
Title: I am making heated socks with adjustments by Nano and want to extend batterty life?
I want to set a temperature and have Nano turn on for 2 minutes then off for 2 minutes and repeat using the same temperature originally set and have the ability to change temperature settings and do the same.

The following sketch works along with displaying battery voltage using MIT Inventor 2 app via Bluetooth HC-05 to my Android phone (without the on/off sequence I am looking to do).

I hope to keep my feet warm but also extend the battery life. Can you tell me what methods I should research to figure out how to do this? I have looked at millis(), blink without delay, and my own limited programming skills without success. Thanks.

```
#define right 5
#define left 6

int leftval = 0;
int val=0;
int vg=0;

void setup() {
  Serial.begin(9600);
  pinMode(left, OUTPUT);
  pinMode(right, OUTPUT);
  pinMode(A0, INPUT);
}

void loop() {
  int vg = analogRead(A0);
  Serial.println(vg / 82.049, 1);
  delay(200);
  if (Serial.available() >= 2) {
    unsigned int a = Serial.read();
    unsigned int b = Serial.read();
    unsigned int val = (b * 256) + a;

    if (val >= 0 && val <= 255) {
      analogWrite(right,val);
      delay(200);
    }

    if (val >= 1000 && val <= 1255) {
      leftval = val - 1000;
      analogWrite(left, leftval);
      delay(200);
    }
  }
}

```

# Answer
> 1 votes
With an electrical heating element powerful enough to warm your feet, the power to the heating element is hundreds or thousands of times greater than the power to your Arduino. Anything you do to reduce the power consumed by your Arduino will have no meaningful effect on your total power consumption. It's like trying to stop a drip in your faucet to save water while the main water pipe has water gushing out of a gaping hole.

Heating elements convert watts of power to calories of heat. The more watts you put in, the more heat you get.

Current • duty cycle • on-time = total power consumed AND total heat generated.

If you reduce the duty cycle to the heating element, you will reduce the power consumed, but you will also reduce the amount of heat generated.

Given that you already have the ability to vary the duty cycle to your heating element (via your analogWrite to `right` and `left`) the only meaningful way to reduce power consumption is to lower the heat setting. It looks like you already have that ability. Turn down the heat setting and have slightly colder feet, or use a higher capacity battery.

All that said, if you turn the heat setting down to 0, the heating element completely stops using power. At that point the Arudino will slowly drain your battery while your electric socks sit in your sock drawer. It would be worth putting your Arduino in ultra-low-power sleep mode (or even turning it off entirely) to avoid draining it while you're not using it.

## Edit:

If you want to run the heating element on for 2 minutes, off for 2 minutes, that would give exactly the same power savings as running it at half the current power level, but constantly.

If you really want to implement the 2 minutes on, 2 minutes off approach, you will need to use millis() to keep track of the time when you last turned the elements on/off. I suggest refactoring your current code to remove delay and use millis as well.

Take a look at the "BlinkWithoutDelay" sketch (which I believe is included with the IDE, and is certainly available online) for an idea of how to handle timing things without using `delay()`.

---
Tags: arduino-nano
---