# Question
Title: Reading contents of ESP8266 Flash from inside sketch
I am aware that there is a way to create a dump of the flash via esptool, but is there a way to read the contents of the sketch (just the sketch, not the full flash or SPIFFS) memory via the sketch *itself*? As in, have a program on the ESP8266 able to read its own machine code from the flash to do something with? I do not need write access, just read access.

I would like to be able to create a backup of the current sketch in SPIFFS so that it is possible to revert a bad sketch so long as the reversion trigger isn't broken. (For example, if a later part of the boot process is messed up, or if a function acts slightly wrong, a button could be held, and it would restore from the saved image. The restore process is something that I've figured out from my previous question, but I would like a way to write the sketch *to* SPIFFS that does not require a separate manual upload or a wrapper around the OTA process.)

\[edit:\] Thank you for the comments.

I have created this code that SHOULD have copied the sketch to SPIFFS. However, it does not seem to have done so properly (since the result does not have the same checksums as the original file, and attempts to write it yield a nonfunctional device). Can I have someone look over it and see if they can figure out why?

```
unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint32_t *data = new uint32_t[SPI_FLASH_SEC_SIZE];
File f = SPIFFS.open("/fw.bin", "w");
while (rem > 0) {
  ESP.flashRead(addr, data, SPI_FLASH_SEC_SIZE);
  int sz = SPI_FLASH_SEC_SIZE * sizeof(uint32_t);
  if (rem < sz)
    sz = rem;
  f.write(reinterpret_cast<uint8_t *>(&data[addr]), sz);
  addr += SPI_FLASH_SEC_SIZE;
  rem -= sz;
  yield();
  Serial.println(rem);
}
f.flush();
f.close();

```

# Answer
> 3 votes
I think you're reading of flash is slightly wrong

while `ESP.flashRead` takes a unit32\_t pointer for output data, the read "count" argument is in bytes - looking at Updater.cpp code it does this

```
uint8_t buff[128];
for(int i = 0; i < binSize; i += sizeof(buff)) {
  ESP.flashRead(_startAddress + i, (uint32_t *)buff, sizeof(buff));
  .....
}

```

so, the the address and count are in bytes - given that SPI\_FLASH\_SEC\_SIZE is 0x1000 or 4096, your code is doing the following

* reading 4096 bytes into a 16384 buffer
* writing 16384 bytes (so the last 12288 bytes are zero, or random, not sure)
* adding 4096 to the address
* subtracting 16384 from size
* repeat until all read

So, the written size will be correct, but the data will be three quarters wrong :p

Therefore, your code should be

```
unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint8_t *data = new uint8_t[SPI_FLASH_SEC_SIZE];
int sz = SPI_FLASH_SEC_SIZE;
File f = SPIFFS.open("/fw.bin", "w");

while (rem > 0) {
    ESP.flashRead(addr, (uint32_t *)data, SPI_FLASH_SEC_SIZE);
    if (rem < sz)
        sz = rem;
    f.write(data, sz);
    addr += SPI_FLASH_SEC_SIZE;
    rem -= sz;
    yield();
    Serial.println(rem);
}

f.flush();
f.close();

```

---
Tags: esp8266, arduino-ide, flash
---


# Question
Title: Arduino Uno - Variables randomly changing
So I have a circuit for a timer (I don't think it is the problem)

Sorry for it being a little messy.

And I have this code (probably the problem):

```
// LiquidCrystal - Version: Latest
#include <LiquidCrystal.h>

/*

*/

const int switchUnitButton = 9;
const int selectButton = 10;
const int startButton = 8;
const int stopButton = 7;
const int d4 = 5;
const int d5 = 4;
const int d6 = 3;
const int d7 = 2;
const int rs = 12;
const int en = 11;
String unit = "sec";
int unitCycle = 1;
int secCount = 0;
int minCount = 0;
int hourCount = 0;
int dayCount = 0;
int switchUnitState;
int prevUnitState;
int selectState;
int prevSelectState;
int startState;
int prevStartState;
int stopState;
int prevStopState;
LiquidCrystal lcd = LiquidCrystal(rs, en, d4, d5, d6, d7);

void setup() {
  Serial.begin(9600);
  pinMode(switchUnitButton, INPUT);
  pinMode(selectButton, INPUT);
  pinMode(startButton, INPUT);
  pinMode(stopButton, INPUT);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  switchUnitState = digitalRead(switchUnitButton);
  selectState = digitalRead(selectButton);
  startState = digitalRead(startButton);
  stopState = digitalRead(stopButton);

  if (switchUnitState == HIGH) {
    if (prevUnitState != switchUnitState) {
      if (unitCycle < 4) {
       unitCycle++;
      } else if (unitCycle == 4) {
       unitCycle = 1;
      }
    }
  }

  Serial.print(unitCycle + "\n");

  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

  lcd.setCursor(0, 0);
  lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));
  lcd.setCursor(0, 1);
  lcd.print("Hr: " + String(hourCount) + " Day: " + String(dayCount));

  prevUnitState = switchUnitState;
  prevSelectState = selectState;
  prevStartState = startState;
  prevStopState = stopState;
}

```

And sometimes without me clicking a button the unit value changes or sometimes when I click the selectButton for the amount to go up it changes which unit it is adding to. And sometimes the string has parts before it from other units like "inhour" what is happening?

# Answer
> 1 votes
You are seriously abusing the String class. There is absolutely no need to use any Strings at all in your program.

For example:

```
  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

```

would be better written as:

```
  if (unitCycle == 1) {
    Serial.println(F("sec"));
  } else if (unitCycle == 2) {
    Serial.println(F("min"));
  } else if (unitCycle == 3) {
    Serial.println(F("hour"));
  } else {
    Serial.println(F("day"));
  }

```

And:

```
  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

```

as:

```
  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unitCycle == 1) {
        secCount++;
      } else if (unitCycle == 2) {
        minCount++;
      } else if (unitCycle == 3) {
        hourCount++;
      } else {
        dayCount++;
      }
    }
  }

```

And then the cardinal sin:

```
lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));

```

All that string creation, concatenation, and destruction is just evil. Instead, use:

```
lcd.print(F("Sec: "));
lcd.print(secCount);
lcd.print(F(" Min: "));
lcd.print(minCount);

```

---
Tags: arduino-uno, code-review
---


# Question
Title: How to power Arduino nano and LED strip?
I am making a project that uses an Arduino nano and a sound detector module to power a 1m LED strip. I got the idea from this video and I am not sure how to power it. My LED strip flashes for a split second and turns off, and people say that the usb power source I am using is not enough power. I am worried though that if I use a more powerful power source that it will fry my Arduino. I am very new to this and I have no idea what to do.

# Answer
> 1 votes
WS2812 can draw 60mA when on full white, x 60 LEDs = 3.6A. If you have a 4 to 5A external 5V supply powering all the components, you'd be okay. If you're trying to power the strip from the Nano 5V line thru its regulator, the regulator will overheat and shutdown.

# Answer
> 0 votes
You could use a relay and have a larger power supply that will light up the LED strip on the other side, after the relay gets the signal to turn on.

---
Tags: arduino-nano, electronics, led-strip
---


# Question
Title: Connecting (SD or HD) TV screen to Arduino
I had a thought about making myself an arcade cabinet. I found a nice cheap and sturdy 8 directional arcade joystick online, and now I'm thinking about the possible ways of displaying graphics.

I would like to know how can I send graphical data to a large screen using Arduino. When I was researching this I saw "TV Text" library that allows sending PAL and SECAM signals, but that's not the "modern" way. Is there a way of using DisplayPort or HDMI to simply use a cheap used PC monitor? Maybe there are other protocols that I can use? I'm looking for a "cheap" way to create a display that's physically as large as screen of arcades from "the good old days".

# Answer
> 3 votes
I'm just going to post things that I found thanks to comment by Juraj.

1. "TV Text" library - PAL, SECAM, NTSC
2. "VGAX" library - VGA

And with large dedication to everyone who wrote that "it's impossible" I give you a blog post of someone who actually did create he's own NTSC console and a game from scratch (called "The Box") using ATmega328P with external 16Mhz crystal. And he did it in 2013.

http://petenpaja.blogspot.com/2013/11/toorums-quest-ii-retro-video-game.html

Original sources were deleted, but I think they can be found when looking for Toorum Quest 2

I think I'll try analyzing the VGAX. It looks promising.

**EDIT:**

There actually is HDMI shield for Arduino!

https://github.com/techtoys/HDMI-Shield/tree/master/Ra8876\_Lite

And a nice and very easy VGA tutorial here:

http://www.pyroelectro.com/tutorials/arduino\_basic\_vga/

---
Tags: communication
---


title: Button to exit a running loop

text:
# Question
Title: Button to exit a running loop
I have a very basic circuit setup:

* A button connected to pin 2
* An LED connected to pin 9

Desired Functionality:

When the button is pressed, the user can toggle through 4 LED patterns.

The Problem:

Once the first fade pattern begins, the user has to wait until it has finished running before the button can toggle to the next pattern. What I want is that the button push will move to pattern 2, even if pattern 1 has already started.

Attempted Solutions:

I've tried to insert a while function in a couple of places i.e while buttonstate =lastbuttonstate, but that doesn't seem to work.

Here's the code: (I realize all the fadeloops are the same right now, they will different in the working model)

```
//PROBLEM: The fade function has to complete a full loop before allowing toggle to next one

const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 9;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

int brightness = 0;    // how bright the LED is
int firstFadeAmount = 5;    // how many points to fade the LED by
int secondFadeAmount = 5;    // how many points to fade the LED by

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      buttonPushCounter++;
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  lastButtonState = buttonState;

  while (buttonPushCounter = lastButtonState) {
    if (buttonPushCounter == 1 && buttonState == HIGH) {
      fadeLoop1();
      delay(50);//JP Edit
    }

    else if (buttonPushCounter == 2 && buttonState == HIGH) {
      fadeLoop2();
      delay(50);
    }

    else if (buttonPushCounter == 3 && buttonState == HIGH) {
      fadeLoop3();
      delay(50);
    }

    else if (buttonPushCounter == 4 && buttonState == HIGH) {
      fadeLoop4();
      delay(50);
    }

  }
  if (buttonPushCounter == 4) {  //Resets back to zero after 4 presses
     buttonPushCounter = 0;
  }

}

void fadeLoop1()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop2()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop3()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop4()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

```

# Answer
## Short Answer:

Switch from using a loop for the entire animation and convert to only tracking what needs to happen at a single point in time.

## Long Answer:

The 'while' approach is a good way to test out an individual pattern but for the behavior you describe, you need to limit the use of loops inside of the 'loop()' function.

Essentially, if you use a while to control the entire pattern, as you encountered, you have to wait for the while to exit before the rest of the code can check for a button press.

Here is how I've done the same thing. I don't have the code handy so I'll have to edit the answer later. The basic form is something like this:

```
int pattern = 0;
int brightness = 0;
int maxBrightness = 100;

setup()
{
// your setup code here
}

loop()
{
   if (pattern = 0)
   {
      //increment brightness
      //call code to set the LED to the current brightness
      if (brightness => maxBrightness)
      {
          brightness = 0;
      }
   }
   checkforbuttonpress();
}

```

What you notice is I didn't use a for / while loop to do my animation, because the already existing loop() function already does that for me. All I have to do is track what needs to happen right now, with variables for which pattern and the current brightness for the code to interact with the hardware. Remember to handle the repetition manually (maxBrightness in this example) and now when the button is pressed, you can change the pattern anywhere because there is no secondary loop to wait for.
> 1 votes

# Answer
Rewrite the fade loops so they return immediately and instead use global state to adjust the LEDs and `millis()-timestamp` to set the timing.

You can use blinkwithoutdelay as inspiration.
> 0 votes

---
Tags: button, loop
---


# Question
Title: How to run Arduino codes in Java netbeans?
Having a hard time searching the net on how to run arduino codes on java. Can somebody please help me. Thank you.

# Answer
Java is a programming language. Arduino is a platform that is mostly accessed by the C++ programming language. You cannot run "Arduino code" in Java.
> 5 votes

# Answer
The Arduino can't run Java. Full stop.
> 1 votes

---
Tags: arduino-ide, java
---


# Question
Title: Using an Android bluetooth terminal to change preset states on 8x8 LED matrixes
I'm trying to create eyes for a project, and while I have been able to properly program the different expressions, and have them triggered by commands from the COM3 terminal, I have not been able to make any commands from the Bluetooth Terminal on my phone work.

Details:

Mega2560

2x 8x8 LED Displays - MAX7219

HC-05 Bluetooth Transceiver - default Baud - 9600

Using LEDControl.h, SoftwareSerial.h

This is the loop on my device, when I type the commands A, B, etc. into the COM3 terminal it works just fine, but the same commands on the phone are just interpreted as ASCII, even when I put parentheses around them.

```
void loop()
{
  // Feed any data from bluetooth to Terminal.
  if (EEBlue.available()){
  Serial.write(EEBlue.read());
  }
  if (Serial.available())  //verifies if there is serial data available
  {
    char cmd = Serial.read();

    if(cmd == 'A') {
      display_eyes(eye_neutral_l, eye_neutral_r);
    }
    if(cmd == 'B') {
      display_eyes(eye_shock_l, eye_shock_r);
    }
    if(cmd == 'C') {
      display_eyes(eye_love_l, eye_love_r);
    }
    if(cmd == 'D') {
      display_eyes(eye_suspicious_l, eye_suspicious_r);
    }
    if(cmd == 'E') {
      display_eyes(eye_happy_l, eye_happy_r);
    }
    if(cmd == 'F') {
      display_eyes(eye_hurt_l, eye_hurt_r);
    }
    if(cmd == '1') {
      display_eyes(eye_mad_l, eye_mad_r);
    }
  // Feed all data from termial to bluetooth
  EEBlue.write(Serial.read());
  }
}

```

# Answer
> 1 votes
Your problem is, that you read from the `EEBlue` serial interface, but you are just echoing it over `Serial` and don't do anything with it. The display code is only executed, when the commands come through `Serial`.

The simplest way is to copy the code in the `if(Serial.available())` statement into the `if(EEBlue.available())` statement and changing the read to use `EEBlue`. Of course you should delete the existing `EEBlue.read()` from this statement.

But that way would mean to have double the code to maintain. It is cleaner to first read data from either serial interface and then process it. Something like this:

```
if(Serial.available()){
    cmd = Serial.read();
} else if(EEBlue.available()){
    cmd = EEBlue.read();
}

// insert the code to check the cmd variable for the expected values and act accordingly

cmd = 0; // Resetting the cmd to prevent multiple executions of one command

```

---
Tags: arduino-mega, led, bluetooth, hc-05, max7219
---


# Question
Title: Programfault when dereferencing a 64bit int on due
I am running into a strange behaviour with my code. The following works without problems on an Arduino Nano but it seems to crash on a DUE

```
void putData64(byte* packet, int pos, uint64_t data)
{
    uint64_t* h= (uint64_t*) (packet+pos+2);
    *h= data;
}

```

the problematic line seems to be the second one (\*h= data) as commenting it out lets the program run without problems.

Similar, the following lines cause a problem on a DUE but run fine on a Nano:

```
char* data;
// ... data is filled with something
uint64_t* t= (uint64_t*) (data+1);
uint64_t test= *t;

```

Is there something I am missing?

# Answer
> 0 votes
I concur with Majenko's comment: it's probably a memory alignment problem. I don't know the specifics of the Due, but when you access memory in chunks of 32 bit data words on a 32 bit CPU, it can happen that the architecture requires the data words to be aligned to 32 bit (i.e. 4 byte) boundaries. This means that the address of an `uint32_t` or `uint64_t` should be a multiple of 4. Maybe even 8 for a `uint64_t`, you will have to check.

The only solution to this issue is to fill the packet *byte by byte*:

```
void putData64(byte* packet, int pos, uint64_t data)
{
    union {
        uint64_t integer;
        byte bytes[8];
    } h = { .integer = data };
    for (int i = 0; i < 8; i++) {
        packet[pos+2+i] = h.bytes[i];
    }
}

```

Note that the AVR (in the Nano) is an 8 bit architecture with no alignment constraints whatsoever.

---
Tags: arduino-due, pointer
---


# Question
Title: nodeMCU - 2 loops at a time - one continuously and second every 10 seconds
i have nodeMCU v3(esp8266) so i need to make 2 checks 1 check is the pin D1 which needs to be done continuously and another check is web link check every 10 seconds, problem is coz when i put delay then it stops the first check

```
void loop() {

 if (digitalRead(pinD1)==1){
       digitalWrite(pinD0, HIGH);
       delay(20000);
 }else{
       digitalWrite(pinD0, LOW);
 }

      loop2();

}

void loop2(){
   if (json1=="ON"){
    digitalWrite(pinD0, HIGH);
      delay(20000);
}else{
     digitalWrite(pinD0, LOW);
               delay(10000);

  }
}

```

# Answer
Rather than using `delay`, use `millis()` and a variable to check if the some time has expired

```
void loop()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (digitalRead(pinD1)==1){
            digitalWrite(pinD0, HIGH);
            check = now + 20000;
        } else {
            digitalWrite(pinD0, LOW);
            check = now;
        }
    }
    loop2();
}

void loop2()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (json1=="ON"){
            digitalWrite(pinD0, HIGH);
        } else {
            digitalWrite(pinD0, LOW);
        }
        check = now + 20000;
    }
}

```
> 1 votes

---
Tags: arduino-uno, esp8266, programming, nodemcu
---


# Question
Title: ESP8266 crashes when trying to copy a string into a big char
I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.

My ESP8266 crashes every time I try to use the `toCharArray` method.

here's my code

```
// here I'm getting an http request
String payload = https.getString();

// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);

// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;

// Prepare the character array
char xml[str_len];

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here

```

the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?

As you can imagine I'm just starting with the c language :)

EDIT: `https.getString().c_str()` \+ less variables was the right way to save memory

# Answer
Function local variable are created on the stack, and in the case of an ESP8266, the total size is limited to 4096 Bytes - so, 3900 for one variable is cutting it close.

I would recommend you either use malloc/free

```
int str_len = payload.length() + 1;

// Prepare the character array
char *xml = (char *) malloc(str_len);

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
//
// when done, free the memory malloc'd

free(xml);

```

or, if you know an absolute maximum size for the string, e.g. 5000, make `char xml[5001];` in the global scope
> 0 votes

---
Tags: string
---


# Question
Title: What is the maximum number of sensors that can be operated on a single Aurdino unit
I currently have an Aurdiuno uno and a motor driver shield: (http://www.hobbytronics.co.uk/arduino-motor-shield).

Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor,

Will the Aurdiuno uno paired with the motor sheild be able to run these components or will I need to buy an Aurdiuno mini? Could I please gain some insight into how you figure out what pins are required and how would i connect the sensor pins to the motor sheild since it does not have any direction slip on connections like the Aurdiuno Uno. Will I need to solder the sensor connections on?

Thankyou

# Answer
> 0 votes
> Will the Aurdiuno uno ... buy an Aurdiuno mini?

The main differences between the uno and mini are:

* footprint
* 6 (uno) vs 8 (mini) analog inputs

You will get two extra analog inputs and a much smaller size at the cost of the shield not fitting anymore.

> Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor, Will the Aurdiuno uno paired with the motor sheild be able to run these components?

According to the website the shield supports up to 4 motors or 5 servos, so i would guess that it would work.

if the shield can't do 3 motors and 1 servo at the same time, then you can just use the servo library and a pin for that.

The shield requires 3 pins to function; so you need 3 or 4 pins depending on configurations.

Inputs 1 digital, 4 analog; 1 Digital I\O, 1 Analog In

so it looks like you need 4-5 DIO pins and 4 analog pins, which the uno has so yes.

If you were using motor driver boards instead of a shield the cost would be

2x PWM per Motor/driver combo = 6 PWM 1 DIO for servo 1 DIO for digital input 4x Analog Inputs

Which also fits in the budget all 6 of the PWM DIO pins, + 2 more (leaving 6 of the 14) and 2/3rds of the analog pins (also good you can leave A3,4 alone since they share a timer and only use the other ones)

---
Tags: arduino-uno, sensors, pins, arduino-motor-shield
---


title: Need help with buttonstate

text:
# Question
Title: Need help with buttonstate
I'm creating a program that works like a piano. I have four button, a piezo buzz and an LCD screen. I'm having a little trouble with the buttonstate.

Here is my program, when I run it the piezo buzz doesn't stop producing sound. The way it's suppose to work is when I push the green button, the piezo is suppose to produce a C sound but it doesn't. Can anyone please tell me what I've done wrong?

code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

int buttonyellow = 3;
int buttonred = 4;
int buttongreen = 5;
int buttonblue = 6;

int C,D,E,F;
int buzz = 7;

int buttonstate;

void setup()
{
  lcd.begin(16, 2);

  lcd.print("hello, world!");

  Serial.begin(9600);
  pinMode(buttonyellow,INPUT);
  pinMode(buttonred,INPUT);
  pinMode(buttongreen,INPUT);
  pinMode(buttonblue,INPUT);
}

void loop()
{
  lcd.setCursor(0, 1);

  lcd.print(millis() / 1000);

  C = digitalRead(buttonyellow);
  D = digitalRead(buttonred);
  E = digitalRead(buttongreen);
  F = digitalRead(buttonblue);

  buttonstate = digitalRead(C);
  if(buttonstate == HIGH){
    tone(buzz,523);
  }  else if ( buttonstate == LOW) {
    tone(buzz,1000);
  }else{
   noTone(buzz);
  }
  delay(50);
}

```

# Answer
> 1 votes
As jsotola has pointed out, there is a mistake in your code. Remove the line

```
buttonstate = digitalRead(C)

```

and replace

```
if(buttonstate == HIGH)

```

with

```
if(C == HIGH)

```

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button

---
Tags: button
---


# Question
Title: How to write a function to return matrix?
I need a function to return a 2x2 rotation matrix, something like:

```
float matrix(float phi){
  float R[2][2] = { {cos(phi), -sin(phi)},
                    {sin(phi),  cos(phi)} };
return R;
}

```

But it doesn't work obviously. **What is the best way to write this function?**

# Answer
> -1 votes
One way would be to make the function return a pointer to float ie create a new array and return it

```
float** matrix(float phi){
   float** R= (float **)malloc(2 * 2 * sizeof(float));
   R[0][0]= cos(phi);
   R[0][1]= -sin(phi);
   R[1][0]= sin(phi);
   R[1][1]= cos(phi);
   return R;
}

```

Do not forget to free the memory once you do not need it any more!

However, I would advise you not to do it but rather pass the array to the function. See How can I declare an array of variable size (Globally) and Is using malloc() and free() a really bad idea on Arduino? for an explanation why it might not be a good idea to allocate the memory in the function (in an embedded aka Arduino environment)

# Answer
> 1 votes
You cannot return an array from a function. There are several alternatives, though. One of them is to allocate the memory for the array within the function, as suggested by user2912328's answer. I would not recommend this approach though, for the reasons already stated in that answer.

For an overview of the other possible options, see this response to the question “Returning an int array from a function”.

Now, your problem is slightly different, as you have a 2D array. The C/C++ syntax for dealing with those is tricky, but here we go.

If you opt for the “static array” solution (make sure you understand the implications), you could write:

```
float (*matrix(float phi))[2]
{
    static float R[2][2];
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

```

and you would use it like this:

```
float (*M)[2] = matrix(angle);

```

If you instead let the caller manage the allocation, then

```
float (*matrix(float phi, float (*R)[2]))[2]
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

```

Or maybe forgo the return value to make the syntax simpler:

```
void matrix(float phi, float (*R)[2])
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
}

```

and you could use it like:

```
float M[2][2];
matrix(angle, M);

```

The “array in a struct” solution is more straightforward.

If the syntax for dealing with 2D arrays bothers you (which would be understandable), you can instead use arrays of pointers to 1D arrays. This are easier to deal with but trickier to allocate. That approach could warrant another answer...

---

**Edit**: One common way to simplify a convoluted array syntax is to use typedefs. As an identifier for a 2x2 array decays to a pointer to an array of 2 floats, you can name that type:

```
typedef float (*pmatrix)[2];  // pointer to an array of 2 floats

```

Then, instead of

```
float (*matrix(float phi))[2] { ... }
...
float (*M)[2] = matrix(angle);

```

you would write

```
pmatrix matrix(float phi) { ... }
...
pmatrix M = matrix(angle);

```

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


title: Two buttons, one LCD

text:
# Question
Title: Two buttons, one LCD
I'm trying to make a program that whenever a button is push, a different word will show on a lCD screen. However, it seems that the two buttons provide the same output ("Screen A"), it's like there is no difference between them, and I'm not sure what's the cause.

The code is very simple:

```
const int buttonPin1 = 13;     // the number of the pushbutton pin
const int buttonPin2 = 12;     // the number of the pushbutton pin

int buttonState = 0;

long randNumber;

void setup() {

  for(int x=0; x<2; x++)
  {
    pinMode(buttonPin[x], INPUT);
  }

}
    void loop() {

      for(int x=0; x<2; x++)
      {
        buttonState = digitalRead(buttonPin[x]);

        if (buttonState == HIGH && buttonPin[x] == 13) {
          lcd.print("  Screen A ");
        }
        if (buttonState == HIGH && buttonPin[x] == 12) {
          lcd.print("  Screen B ");
        }
      }

    }

```

Any help is appreciated

# Answer
I guess it's something with the circuit ... can you add it to your question.

Also, make sure buttonPin has the values 13 and 12 in the first and second index.

Btw, The following code is functionally identical:

```
void loop()
{
    if (digitalRead(buttonPin[0]) == HIGH)
    {
       lcd.print("  Screen A ");
    }
    if (digitalRead(buttonPin[1]) == HIGH)
    {
       lcd.print("  Screen B ");
    }
}

```

If you want to have the loop and a flexible amount, use something like:

```
#define NR_OF_PINS 2

int buttonPins[NR_OF_PINS] = { 8, 9 };
String screens[NR_OF_PINS] = { "Screen A", "Screen B" };

void loop()
{
    for (int pin = 0; pin < NR_OF_PINS; pin++)
    {
        if (digitalRead(buttonPins[pin]) == HIGH)
        {
            lcd.print(screens[pin]);
        }
    }
}

```

**Update**

My answer is related to the code before you edited.

Remarks:

* After your edited code, you forgot to declare buttonPin:

int buttonPin\[\] = { buttonPin1, buttonPin2 };
* You do not use `long randNumber`
* Instead of a global variable `int buttonState` you can create it locally in the loop function (although you do not need it according to my code above).

buttonState = digitalRead(buttonPin\[x\]);
* Also, what you high likely want to add is button debouncing (check the arduino example about this), unless you add a delay after showing a screen of a considerable amount (like 100 ms or more).
> 1 votes

---
Tags: lcd, button
---


title: Random without parameters

text:
# Question
Title: Random without parameters
During a programming contest, I used the following line of code:

```
symbols[i] = random() & 0b11;

```

After the contest, when I looked into the Arduino reference, I found out random takes one or two parameters. Based upon that, I would expect the code not to compile. However, this code somehow worked as I expected. (Assigning a random number from 0 to 3) How come?

# Answer
Simple: `random()` isn't an Arduino function - it's a standard C function.

> **Function random()**
>
> `long random(void)`
>
> The `random()` function computes a sequence of pseudo-random integers in the range of 0 to `RANDOM_MAX` (as defined by the header file `<stdlib.h>`).
>
> The `srandom()` function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by `rand()`. These sequences are repeatable by calling `srandom()` with the same seed value.
>
> If no seed value is provided, the functions are automatically seeded with a value of 1.
>
> -- AVR LIBC Manual Page
> 1 votes

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


# Question
Title: How to add numbers to a position when controlling a seven-segment display
I'm recently having a hard time with my Arduino project. I'm trying to control a seven-segment display (it has a microcontroller on it) with an encoder, and I'm trying so that everytime I rotate the encoder it adds 5 to the number on the display. What am I doing wrong here???

P.S: there are some parts that are for controlling relays, they are not related to the issue. I removed them on this thread on purpose.

Code (without any attempts to change the added amount to the display):

```
#include <RotaryEncoder.h>
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 10
#define DIO 11

// Setup a RoraryEncoder for pins A2 and A3:
RotaryEncoder encoder(A2, A3);

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   1000

TM1637Display display(CLK, DIO);

void setup()
{
    Serial.begin(57600);
    Serial.println("SimplePollRotator example for the RotaryEncoder
    library.");
}

// The Interrupt Service Routine for Pin Change Interrupt 1
// This routine will only be called on any signal change on A2 and A3:
//exactly where we need to check.
ISR(PCINT1_vect) {
    encoder.tick(); // just call tick() to check the state.
}

// Read the current position of the encoder and print out when changed.
void loop()
{
    static int pos = 0;
    int newPos = encoder.getPosition();
    if(newPos > -1)
    {
        if (pos != newPos) {
            Serial.print(newPos);
            Serial.println();
            pos = newPos + 4;
            display.setBrightness(0x0f);
            // All segments on
            // Show decimal numbers with/without leading zeros
            display.showNumberDec(newPos, true); // Expect: 1234
            delay(100);
        }
    } // if
} // loop ()
// The End

```

# Answer
> 2 votes
In your code, you call:

```
newPos = encoder.getPosition();

```

which grabs the absolute position of the encoder. When you rotate this one step, the value of `newPos` goes up (or down) by one.

Then, you make `pos = newPos + 4`, which simply adds 4 to the value that is going up or down by one step at a time.

```
newPos: 1    pos: 5
newPos: 2    pos: 6
newPos: 3    pos: 7
newPos: 4    pos: 8
newPos: 5    pos: 9

```

Instead, it sounds like you wish the display to always read 5 times the encoder position. If so, then you should write `pos = newPos*5`.

```
newPos: 1    pos: 5
newPos: 2    pos: 10
newPos: 3    pos: 15
newPos: 4    pos: 20
newPos: 5    pos: 25

```

Then, when you write to the display, you do so as:

```
display.showNumberDec(newPos, true); // Expect: 1234

```

But `newPos` is not the newly calculated value. Instead, call

```
display.showNumberDec(pos, true); // Expect: 1234

```

---
Tags: arduino-uno, rotary-encoder, 7-segment
---


# Question
Title: `LOW` being defined as `0` and `HIGH` being defined as `1` - is this a part of external specification?
`Arduino.h` defines `LOW` as `0x0` and `HIGH` as `0x1`. Does the Arduino API intend to expose that fact? Does it guarantee that this will always be that way?

In other words, what is the intended purpose of these manifest constants: `LOW` and `HIGH`?

* Is this purely cosmetic mnemonics added as an alternative for `0/1` and `false/true`, for those who like `LOW/HIGH` better?
* Or is this an attempt to abstract/isolate the user's source code from the actual representation of `LOW` and `HIGH` (e.g. in case the representation changes in the future)?

The underlying reason for this question is to figure out whether code like

```
digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

```

is a good programming practice. (If `LOW` and `HIGH` are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

# Answer
> 4 votes
> The underlying reason for this question is to figure out whether code like
>
> ```
> digitalWrite(some_pin, true);
> digitalWrite(some_other_pin, !digitalRead(some_other_pin));
>
> ```
>
> is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Strictly speaking, no, that is not good programming practice.

`digitalRead()` returns an `int`. `digitalWrite()` expects an `int`. Using `!` converts the `int` into a `bool` and then it's promoted back to an `int` again.

In fact, the "next gen" Arduino core API changes HIGH and LOW from a simple `int` to an `enum` \- and that struggles with casting through `bool` like that:

```
typedef enum {
  LOW     = 0,
  HIGH    = 1,
  CHANGE  = 2,
  FALLING = 3,
  RISING  = 4,
} PinStatus;

```

You can see the problems that causes here.

---
Tags: programming, arduino-ide, digital
---


# Question
Title: Sending data from Arduino Mega to nodeMCU using serial (Multiple sensor data) & upload to firebase
Im working in a project where i have to deal with multiple sensor data.

1. BME 280
2. WindSpeed Sensor
3. Water level Sensor x 10
4. Soil moisture x 5
5. Soil pH sensor x 2

i have found this code for both arduino uno and nodemcu esp8266

```
//Arduino code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);

void setup() {
s.begin(9600);
}

void loop() {
int data=50;
if(s.available()>0)
{
 s.write(data);
}
}

//for nodeMCU
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5);
int data;
void setup() {
s.begin(9600);
Serial.begin(9600);
}

void loop() {
  s.write("s");
  if (s.available()>0)
  {
    data=s.read();
    Serial.println(data);
  }
}

```

**In this code here send 1 value from arduino uno to nodeMCU... but if i want to send 10 values(float temperature,humidity,pressure,waterlevel,windSpeed,windDirection) from mega to nodeMCU using serial, how to do that using serail.**

# Answer
> 1 votes
As i know nodemcu still not work as a slave device . Maybe this support will be available in the future but if you test it and it work . This how to do it Let's assume you have tow dat to send cast them to string , concatenated characters of string\_data1+string\_data2 then send theme via uart communication to the nodemcu . Now in the nodemcu take the string and decoding \[split\] string to string 1 and string 2 and cast theme again to any var type you want. If this method seems so hard to you or your level in coding is still under development use some library exist that can do the work for you i recommend. The easytransfer library by madsci1016 in github enter link description here.

---
Tags: serial, nodemcu
---


# Question
Title: Arduino and Processing Call and response not working
I have been trying to develop a connection from the arduino IDE to Processing so I can send data measured on the arduino Pins to processing to display.

I first packaged the 10-bit integers I was receiving from the arduino into characters each with their own byte. For example, 1023 was a 10-bit integer which i packaged into 4 8-bit characters, 1, 0, 2 and 3. These could then be sent over the serial port and were reconstructed on the other end by processing.

However, I have been trying to make a call and response relationship between the two where after one program is done receiving and processing the data, it asks the other to send the next set.

I used the example code given on the arduino website which works fine on its own. But when i try and implement the character packaging to it, it stops working. The output in processing always miss out the first couple of characters.

Whats more is that i deleted the myPort.print('A') from the processing code, and arduino was still sending data repeatedly, despite processing not sending it's response back.

It is a vague question, but where have i gone wrong when implementing the packaging code? and why does the arduino keep sending data regardless of whether processing responds.

Thanks a lot

===================================

Arduino Code:

```
int inByte = 0;

//void establishContact();

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  establishContact();
}

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

  if (Serial.available() > 0) {
    // get incoming byte:
    //inByte = Serial.read();

      int MzValue = analogRead(A0);
      int FzValue = analogRead(A1);
      int FyValue = analogRead(A2);

      char Mz_Str[10];
      char Fz_Str[10];
      char Fy_Str[10];

      sprintf(Mz_Str, "%d", MzValue);
      sprintf(Fz_Str, "%d", FzValue);
      sprintf(Fy_Str, "%d", FyValue);
      // Now str contains the integer as characters

      Serial.write(Mz_Str);
      Serial.write(",");
      Serial.write(Fz_Str);
      Serial.write(",");
      Serial.write(Fy_Str);
      Serial.write(",");
      Serial.write("\n");

      delay(20);
  }
  else {
    delay(20);
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.print('A');   // send a capital A
    delay(1000);
  }
}

```

=================================== Processing Code:

```
import processing.serial.*;

  Serial myPort;                       // The serial port
  boolean firstContact = false;        // Whether we've heard from the microcontroller
  String val;     // Data received from the serial port
  int numValues = 3;
  float[] values = new float[numValues];
  int inByte = 0;

  void setup() {
    size(256, 256);  // Stage size
    noStroke();      // No border on the next thing drawn

    // Print a list of the serial ports for debugging purposes
    // if using Processing 2.1 or later, use Serial.printArray()
    println(Serial.list());

    // I know that the first port in the serial list on my Mac is always my FTDI
    // adaptor, so I open Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    String portName = Serial.list()[0];
    myPort = new Serial(this, portName, 9600);
  }

  void draw() {
    // read a byte from the serial port:
    if ( myPort.available() > 0) {
    inByte = myPort.read();
    }
    //print(inByte);
    // if this is the first byte received, and it's an A, clear the serial
    // buffer and note that you've had first contact from the microcontroller.
    // Otherwise, add the incoming byte to the array:
    if (firstContact == false) {
      if (inByte == 'A') {
        myPort.clear();          // clear the serial port buffer
        firstContact = true;     // you've had first contact from the microcontroller
        myPort.write('A');       // ask for more
        println(inByte);
      }
    }
    else {
        val = myPort.readStringUntil('\n');         // read it and store it in val
        println(val); //print it out in the console
        values = float(splitTokens(val, ","));

        myPort.write('A');
        delay(20);
      }
    }

```

# Answer
> 1 votes
Why not just send all the data at once, in a comma separated list, with a `\n` char as a "end of message" delimiter?

Here are 2 test sketches. The Arduino sketch sends the A0 to A2 values to serial every 500ms, and the Processing sketch displays the received data. Parsing the received data into an integer array is more of a Java question, not an Arduino one, so I'll leave that up to you.

**Arduino**

```
// Send the values of A0, A1 and A3
// to serial every 500ms.
// 2416 bytes.
char data[20];
char buffer[6];

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

void loop(){
  itoa(analogRead(A0), buffer, 10);
  strcat(data, buffer);
  strcat(data, ",");
  itoa(analogRead(A1), buffer, 10);
  strcat(data, buffer);
  strcat(data, ",");
  itoa(analogRead(A2), buffer, 10);
  strcat(data, buffer);
  strcat(data, "\n");
  Serial.write(data);
  memset(data, 0, sizeof(data));
  delay(500);
}

```

**Processing**

```
// Display the data received from the serial port, sent every
// 500 ms from the Arduino. The values sent are from A0, A1
// and A2, and were sent concatenated together, as a comma
// separated list, followed by a \n char.
import processing.serial.*;
import java.awt.TextArea;
Serial myPort;
TextArea myTextArea;
String input;

void setup(){

  try{
    myPort = new Serial(this, Serial.list()[0], 9600);
  }
  catch(Exception e){
    System.err.println(e);
    e.printStackTrace();
  }

  myTextArea = new TextArea("", 23, 49, 1);
  this.add(myTextArea);

  size(500, 380);

}

void draw(){

  if(myPort.available() > 0){
    input = myPort.readStringUntil('\n');
    myTextArea.append(input);
  }

}

```

**EDIT**

As Juraj mentions in his comments, I could have just used `Serial.print()` 6 times instead of the `char` arrays. Here is a second Arduino sketch that uses `Serial.print()`. Before you use it, be aware that it's compile size is 288 bytes **more** than the `char` array method. Imagine that :)

```
// Send the values of A0, A1 and A3
// to serial every 500ms.
// 2704 bytes.
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.print(analogRead(A0));
  Serial.print(",");
  Serial.print(analogRead(A1));
  Serial.print(",");
  Serial.print(analogRead(A2));
  Serial.print("\n");
  delay(500);
}

```

---
Tags: serial, arduino-due, processing-lang
---


title: Multi-threaded Robot

text:
# Question
Title: Multi-threaded Robot
I am working on a small robot project, the code which i made for this has a sequential execution in a single thread. There are a lot of Delay() function needed. Due to which the accuracy is extremely bad. i want to to implement the movements in one thread and the sensor detection in another thread.

```
#define M1 3
#define M2 5
#define M3 6
#define M4 9
#define L_trig 2
#define L_echo 4
#define R_trig 7
#define R_echo 8
#define servo 10
#define solenoid_pin 11
#define LDR_pin1 12
#define LDR_pin2 13
void setup()
{
// Motors Initilization
pinMode(M1,OUTPUT);
pinMode(M2,OUTPUT);
pinMode(M3,OUTPUT);
pinMode(M4,OUTPUT);
// Ultrasonic  Initilization
pinMode(L_trig, OUTPUT);
pinMode(L_echo, INPUT);
pinMode(R_trig, OUTPUT);
pinMode(R_echo, INPUT);
S.attach(servo);
}

void loop()
{

 Runmotor(M1);
 Runmotor(M2);
 Runmotor(M3);
 Runmotor(M4);
 servo_rotation();
 Ultrasonic_value(L_trig,L_echo);
 Ultrasonic_value(R_trig,R_echo);

 if(Ultrasonic_value(L_trig,L_echo)<5 || Ultrasonic_value(R_trig,R_echo)<5)

   {
     turnLeft();
     //Serial.println("Working");
   }

}

// Run Motor
void Runmotor(int which)
{
  for(int i=0;i<1023;i++)
  {
 analogWrite(which, i);
  }
}
// Stop Motor
void stopmotor(int which)
{
  digitalWrite(which,LOW);
}
// To turn the robot left side
void turnLeft()
{
  stopmotor(M2);
  stopmotor(M3);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}
// To turn the robot Rightside
void turnRight()
{
  stopmotor(M1);
  stopmotor(M4);
  delay(5000);
  Runmotor(M1);
  Runmotor(M4);
}
// Servo Rotation
void servo_rotation()
{
 for(angle=0;angle<=180;angle++)
{
 S.write(angle);
 if(angle==90)
 {
   delay(2000);
 }
}
delay(2000);
for(angle=180;angle>=0;angle--)
{
  S.write(angle);
  Serial.println(angle);
  if(angle==90)
 {
   delay(2000);
 }
}
 delay(2000);
}

// Calculation of distance
long Ultrasonic_value(int which_trig,int which_echo)
{
  long duration, distance;
  digitalWrite(which_trig, LOW);
  delayMicroseconds(2);
  digitalWrite(which_trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(which_trig, LOW);
  duration = pulseIn(which_echo, HIGH);
  // distance = duration*343*100/2;
  distance = (duration/2) / 29.1;
  delay(100);
  return distance;
}

void Solenoid_Fire()
{
  digitalWrite(solenoid_pin,LOW);
}

void Solenoid_Reload()
{
  digitalWrite(solenoid_pin,HIGH);
}
/*
bool LDR_reading(int LDR_pin1 , int LDR_pin2)
{

}
*/

```

Please help me. I want to implement this code in a Multi-thread fashion. Thanks in Advance

# Answer
> 2 votes
You could also give my ThreadHandler library a try

https://bitbucket.org/adamb3\_14/threadhandler/src/master/

It uses an interrupting scheduler to allow context switching without relaying on yield() or delay().

I created the library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.

## How it works

Each cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.

### Scheduling rules

The scheduling scheme of the ThreadHandler library is as follows:

1. Highest priority first.
2. If the priority is the same then the thread with the earliest deadline is executed first.
3. If two threads have the same deadline then the first created thread will execute first.
4. A thread can only be interrupted by threads with higher priority.
5. Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
6. The loop function has priority -128 compared to ThreadHandler threads.

## How to use

Threads can be created via c++ inheritance

```
class MyThread : public Thread
{
public:
    MyThread() : Thread(priority, period, offset){}

    virtual ~MyThread(){}

    virtual void run()
    {
        //code to run
    }
};

MyThread* threadObj = new MyThread();

```

Or via createThread and a lambda function

```
Thread* myThread = createThread(priority, period, offset,
    []()
    {
        //code to run
    });

```

Thread objects automatically connect to the ThreadHandler when they are created.

To start execution of created thread objects call:

```
ThreadHandler::getInstance()->enableThreadExecution();

```

# Answer
> 1 votes
I think this needs a major rework. First here:

```
  for(int i=0;i<1023;i++)
  {
  analogWrite(which, i);
  }

```

The maximum you can analogWrite is 255, so change 1023 to 255.

Next, get rid of the delay() calls.

---

Let's look at `turnLeft` :

```
// To turn the robot left side
void turnLeft()
{
  stopmotor(M2);
  stopmotor(M3);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}

```

Why stop the motor and then start it again? Do you mean:

```
// To turn the robot left side
void turnLeft()
{
  stopmotor(M1);
  stopmotor(M4);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}

```

I don't see what the delay achieves anyway. Get rid of it:

```
// To turn the robot left side
void turnLeft()
{
  stopmotor(M1);
  stopmotor(M4);
  Runmotor(M2);
  Runmotor(M3);
}

```

In fact, I don't see what any of the delay() calls achieve. Try removing them.

---

See my post How to do multiple things at once ... like cook bacon and eggs for tips on doing multiple things without using delay().

---

Also consider using arrays. Instead of M1, M2, M3, M4, make an array:

```
const int NUMBER_OF_MOTORS = 4;
const int motorPins [NUMBER_OF_MOTORS] = { 3, 4, 6, 9 };

```

Now it is easier to set them all to output:

```
// Motors Initilization

for (int i = 0; i < NUMBER_OF_MOTORS; i++)
  pinMode (motorPins [i], OUTPUT);

```

It is also easier to start or stop all of them:

```
for (int i = 0; i < NUMBER_OF_MOTORS; i++)
  stopmotor (i);

```

Where stopmotor is now:

```
// Stop Motor
void stopmotor(int which)
{
  digitalWrite(motorPins [which],LOW);
}

```

---

*(Edited to add)*

I also don't see what this achieves:

```
void Runmotor(int which)
{
  for(int i=0;i<1023;i++)
  {
 analogWrite(which, i);
  }
}

```

Apart from the fact that you can't go up to 1023, if you stop at 255, the time taken to do all those analogWrite is just over 2 ms. Why bother? Why not just do this:

```
void Runmotor(int which)
{
  digitalWrite (which, HIGH);
}

```

# Answer
> 1 votes
You may want to take a look at LMX by David Anderson A Light-Weight Multi-Tasking Executive.

He has a very good set of videos on the code that he did for Dallas Personal Robotics Group (DPRG).

The specific videos for LMX are:

# Answer
> 1 votes
You could use a scheduler and simply start tasks with:

```
#include <Scheduler.h>
...
void setup()
{
  ...
  Scheduler.start(servoSetup, servoLoop);
  Scheduler.start(sensorSetup, sensorLoop);
  ...
}

void servoSetup()
{
  S.attach(servo);
}

void servoLoop()
{
  int angle;
  for(angle = 0;angle <= 180; angle++) {
    S.write(angle);
    if (angle == 90) {
      delay(2000);
    }
  }
  delay(2000);
  ...
}
...

```

The tasks must call *yield()* or *delay()* to context switch. The *taskSetup* function is called first and once by the task. The *taskLoop* function is repeatedly called by the task. This can be viewed as running an additional sketch.

For more details see the example sketches.

# Answer
> 0 votes
I am looking at this, for a similar project. It seems light and simple enough that you could have a quick trial. Converting those functions to threads shouldn't be too time consuming.

Once every activity is implemented as thread, you could use semaphores to hold them blocked and then create a state machine which controls them through the semaphores.

---
Tags: arduino-uno, robotics, threads
---


# Question
Title: Question about include statements and details in Arduino.h file from core library
This is more of a C/C++ question. However the files I am asking about are a part of the Arduino library.

In */arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/Arduino.h* :

```
#ifndef Arduino_h
#define Arduino_h

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>

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

#include "binary.h"

#ifdef __cplusplus
extern "C"{
#endif

```

How are these blocks found at compile time in the main sketch?

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

```

Does `#include <avr/somelibrary.h>` mean that this is a standard library from either *avr-g++* or *avr-gcc*? As opposed to a standard g++ or gcc compiler?

One last question, how can there be an *Arduino.h* without an *Arduino.c*? I searched through the project but could not find an *Arduino.c*. All of these are probably stupid questions, as I am in the process of learning C/C++. I am completely new to it.

# Answer
> Does `#include <avr/somelibrary.h>` mean that this is a standard library from either *avr-g++* or *avr-gcc*? As opposed to a standard g++ or gcc compiler?

No. It simply means that the compiler should check both its built-in include paths as well as any passed via the `-I` command line option (or its local equivalent) for a file called "avr/somelibrary.h". That AVR GCC knows where AVR Libc is located is incidental.

> One last question, how can there be an *Arduino.h* without an *Arduino.c*?

There is no obligation to match each header file with a .c/.cc/.cpp file, or vice versa.
> 1 votes

# Answer
I think after all this time, you may found the answers for your question.

But to add some information to this topic incase if anyone opened this question.

> Does #include mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?

Yes, what is included with `avr/` is related to avr standard libraries, which is also found in avr standard compilers.

> One last question, how can there be an Arduino.h without an Arduino.c?

Because, as Mr @Ignacio Vazquez-Abrams answered that there's no obligation for connecting the header file for anything else. You can write multiple header files and use them for one source file.
> 0 votes

---
Tags: uploading, core-libraries, avr-gcc, gcc
---


# Question
Title: No ttyACM0 with Pro Micro on Ubuntu 18.04
I am trying to determine the dev path of a USB keyboard running an Arduino Pro Micro on my Ubuntu 18.04 system. The files /dev/ttyACM0 and /dev/ttyUSB0 do not exist.

When I run dmesg I get:

```
[  410.770931] usb 3-3: new full-speed USB device number 3 using xhci_hcd
[  410.962180] usb 3-3: New USB device found, idVendor=feed, idProduct=3060, bcdDevice= 0.01
[  410.962184] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  410.962187] usb 3-3: Product: Dactyl-Manuform (5x6)
[  410.962189] usb 3-3: Manufacturer: tshort
[  410.962191] usb 3-3: SerialNumber: 0
[  411.006440] input: tshort Dactyl-Manuform (5x6) as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.0/0003:FEED:3060.0008/input/input27
[  411.063192] hid-generic 0003:FEED:3060.0008: input,hidraw0: USB HID v1.11 Keyboard [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input0
[  411.089097] input: tshort Dactyl-Manuform (5x6) Mouse as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input28
[  411.147172] input: tshort Dactyl-Manuform (5x6) System Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input29
[  411.147297] input: tshort Dactyl-Manuform (5x6) Consumer Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input30
[  411.147395] hid-generic 0003:FEED:3060.0009: input,hidraw1: USB HID v1.11 Mouse [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input1

```

Dactyl-Manuform is the keyboard so it seems to recognize the device. The command lsusb returns several usb devices. The entry with no title is the keyboard (based on doing watch lsusb):

```
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID feed:3060
Bus 003 Device 002: ID 045e:02d1 Microsoft Corp. XBOX One Controller for Windows
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 1e7d:2c2e ROCCAT
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

```

I have installed arduino and arduino-core from the official repos.

However, I still cannot get a ttyACM0 or ttyUSB0 to appear, and in the Arduino IDE the "Serial Port" option is greyed out (even when using sudo).

What can I check for to either 1) get the ttyACM0 file to exist for my Arduino device or 2) find some other dev port to use as the serial port?

# Answer
> 1 votes
A Pro Micro will only give a /dev/ttyACMx device node if the firmware installed on it creates a CDC/ACM interface. That device obviously is running custom firmware which only provides the interfaces that the manufacturer wants to provide - in this case keyboard and mouse interfaces.

To use it as an Arduino you will first have to install the Arduino bootloader. That will then remove the existing manufacturer firmware, and you will have to write your own to make it act as a keyboard again.

---
Tags: usb, arduino-pro-micro, ubuntu
---


title: Questions about HMC5883L library

text:
# Question
Title: Questions about HMC5883L library
I'm studying the structures of libraries currently. I want to learn how good programmers write code, what are the strategies they follow, the art the programmer followed to develop the library. And how important the library should be written in the well arranged form.

But as I'm go back and forth into the library over and over, I really need to understand, the way the programmer followed, and the reasons behind the applied strategy.

The example I'm studying now is the HMC5883L and how the programmer used the Wire library to manage the developing the library. This should be quite easy for experienced programmers, but I'm really studying the concepts, strategies .. etc.

As I'm going over and over I have different questions, so to start this discussion I want to begin with this question about the programmer writing two very similar functions that pretty much do the same thing.

```
// Read byte to register
uint8_t HMC5883L::fastRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    while(!Wire.available()) {};
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

```

Update: Actually, the programmer used the 1st version only in the `HMC5883L.begin();` function, but why?

```
if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
|| (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
|| (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
{
return false;
}

```

# Everything else in the library used the 2nd version.

So, basically the two functions are to read a specified register in the HMC5883L, my questions:

1. what is the difference? I know that there's an extra care has been put into the second function, but why ?
2. Is it so important ?
3. Are there situations that require any version of the functions ?

# Answer
TBH the second version of the function is trash. The first version is (almost) the right way to do it. There's stuff in the second version that really shouldn't be there. There is absolutely no reason why the creator of the library created that second function.

* It "waits" for data to be available, when that data will be available the moment `requestFrom()` completes - so is completely redundant
* It makes a spurious `beginTransmission()` call right before the `requestFrom()` call. `beginTransmission()` is only for writing, not for reading. It's pointless there.

However:

* **Both** functions do an `endTransmission()` after the `receiveFrom()`, which makes no sense - the `endTransmission()` goes to balance a `beginTransmission()` only - not a `receiveFrom()`. `receiveFrom()` is a completely self-contained function that needs no other handling.

This library is probably not a good one to study for learning how to use the Wire library. It contains code that indicates the author themselves didn't have a proper grasp of the workings of the library.
> 2 votes

# Answer
There is no "fast" way to do i2c. If you already use the "fast" functions in your code, then you can make it a inline call to readRegister8.

The function below reads a byte from the HMC5883L.
When the HMC5883L is not connected, the Wire.read() returns -1. That will be converted to a return value of 0xFF.

```
// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.write(reg);
    Wire.endTransmission();    // add parameter 'false' for repeated start

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    value = Wire.read();

    return value;
}

```
> 1 votes

---
Tags: programming, library, wire-library, core-libraries
---


title: Cannot make LCD & Gyro work together

text:
# Question
Title: Cannot make LCD & Gyro work together
I'm new to this so there are some poor methods in my code when I try to introduce the LCD into the loop. My issue is that the LCD delay and the servo delay are interfering with each other. How can I isolate them? I like the 50ms response for the servo. But I would like maybe a 200ms refresh for the LCD. But in their current state they are giving a very odd response if I have them both in the loop. The servo is spinning slower as though it's adding both delays. If I disable the LCD it all goes back to normal. Any ideas? Could someone please show me the correct method so I can expand in the future? Thanks!!!!

I've got this so far:

```
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

//SERVO
#include <Servo.h>
Servo microservo1;
int servo_pin = 8;

//MAPPED VALUES
int16_t AcXmapped, AcYmapped, AcZmapped;

//LCD
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
//initializes the library

void setup(){

  //SERVO SETUP
  microservo1.attach ( servo_pin );

  //WIRE SETUP
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
  Serial.println("Transmission Line Initializing");
  delay(350);
  //print("3"); print("2"); print("1");
  Serial.println("3");
  delay(1000);
  Serial.println("2");
  delay(1000);
  Serial.println("1");
  delay(1000);

  //LCD SETUP
  lcd.begin(16,2); //setup LCD number of columns and rows
  digitalWrite(9,1); //can either go 0 --> 1 or LOW --> HIGH || turns LCD on or off ||
  analogWrite(6,70); //contrast setting for the text on the LCD
}

void loop(){

  //WIRE LOOP
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print(" | AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  //Serial.print(" | Tmp =  "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

  //MAPPING the values from e.g. AcX to AcXmapped so they're better values for servo control.
  //set the AcX inside the map to negative if you want to invert the rotation of the servo.
  AcXmapped = map (AcX, -17000, 17000, 0, 180); //ROLL
  AcYmapped = map (AcY, -17000, 17000, 0, 180); //PITCH
  AcZmapped = map (AcZ, -17000, 17000, 0, 180); //YAW

  //SERVO LOOP
  microservo1.write(AcYmapped);
  //50 ms response between movements
  delay(50);

  //LCD LOOP
  lcd.setCursor(0,0); //set the cursor to (0,0)
  lcd.print(AcYmapped);
  delay(50);

  //EXTRA LCD
  lcd.noAutoscroll(); //turns off autoscroll
  lcd.clear(); //clears the screen for the next loop

}

```

# Answer
> 1 votes
First upload the msg errors you've get . Second the lcd can't display values in realtime because when the gyroscope move the arduino blocking the lcd and reading the data from gyroscope because you using no scheduling coding. I recommend you to use millis instead of delays and use multitasking code like freertos .

# Answer
> 0 votes
Don't use `delay()` at all. You need to refactor your code to record the value of `millis()` at the beginning of a time interval and then wait until the new value of `millis()` is greater by the desired interval. Do a google search on "Arduino blink without delay" for articles that discuss this coding technique. It's a fundamental of programming for a single-threaded microcontroller like the Arduino, and something you must learn to do if you're going to write anything of any complexity for the platform.

---
Tags: arduino-mega, lcd, mpu6050
---


# Question
Title: Implementing sending from N and recieving from N with FreeRtos and RF24 radio module
I'm trying to make my first chip send data through a nrf24 radio pipe and the other listen to it. After the first data is received it should switch to transmit mode and itself transmit new data. The main goal of all of this is to implement the raft protocol with at least 3 chips participating. So the requirements would be to have each chip listening all the time and to have it stop listening at random intervals to send a broadcast message to all other chips. Basically the communication is never between just two chips but always one to many. I've come across tutorials such as http://forum.arduino.cc/index.php?topic=421081 but it always comes down to a stable Master vs Slaves state while my situation is more dynamic. This is my current task. The listener works perfectly until the first received message when it opens a writing pipe. It then does not write and does not go back to listening.

```
void test_Task(void *pvParameters){

    printf("some init\n");
    bool hastoSend = false;

    radio.openReadingPipe(1, address);
    while(1){

        radio.startListening();
        if (radio.available()) {
            radio.read(&rx_data, sizeof(rx_data));

                if (rx_data[1] == 101){
                    printf("Received message: %d\n", rx_data[1]);
                    hastoSend = true;
                    printf("%d\n",rx_data[0]);
                    //int someint = *((int*)pvParameters);

                    // turn on led1
                    write_byte_pcf(led1);
                    vTaskDelay(pdMS_TO_TICKS(200));
                    write_byte_pcf(0xff);
                }

        }else{
                if (hastoSend){

                    printf("I need to send a message!\n");
                    printf("sending a message\n");
                    radio.openWritingPipe(address2);
                    radio.stopListening();
                    transmit_nrf24();
                    radio.printDetails();
                    hastoSend = false;
                    radio.openReadingPipe(1, address);

                }
        }

    }

}

```

This is my radio setup:

```
static inline void setup_nrf() {

    uart_set_baud(0, 115200);
    gpio_enable(SCL, GPIO_OUTPUT);
    gpio_enable(CS_NRF, GPIO_OUTPUT);

    // radio configuration
    radio.begin();
    radio.setChannel(channel);
    radio.setAutoAck(false);

}

```

For testing purposes the messages being transmitted come from my other device which is just a manual transmitter. What would solve my problem is a way to completely reset the radio when the first message is received so that the pipes do not bother each other and the device could then be re-initialised as a transmitter.

Cheers!

# Answer
Solved it by simply repeating

```
gpio_enable(SCL, GPIO_OUTPUT);
gpio_enable(CS_NRF, GPIO_OUTPUT);

// radio configuration
radio.begin();
radio.setChannel(channel);
radio.setAutoAck(false);

```

before opening a new writing pipe.
> 2 votes

---
Tags: esp8266, programming
---


# Question
Title: Is it possible that function will get a parameter that can be int OR char?
I'm trying to create a function that enters a key/value into a JSON file.

But, since value can be an `int` or `char`, I don't want to create 2 functions for each type.

Is there a way ?

```
void setValue(char *key, char* value){
        StaticJsonDocument<512> tempJDOC;
        tempJDOC[key]=value;
}

```

**EDIT1**

```
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (char *key);

template <class T>
void setValue(const char *key, T value);
//void setValue(const char *key, char *value);

};
#endif

```

**EDIT2**

```
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define LOG_LENGTH 4
#define DOC_SIZE 512

template <class T> // . <---- line added
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (const char *key);
void removeValue(const char *key);
// void setValue(const char *key, char *value); <--- comment out
void updateArray(char* array_key, int val);
void printFile();
void setValue(const char *key, T value); <---- Added

};
#endif

```

and in .cpp file :

```
void myJSON::setValue(const char *key, T value){
        StaticJsonDocument<512> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
        myJSON::PrettyprintJSON(tempJDOC);
}

```

# Answer
> 2 votes
In C++ you can create a template function. (The ArduinoJson `[]` operator is a template too.)

```
#include <ArduinoJson.h>

StaticJsonDocument<512> tempJDOC;

template <typename T>
void setValue(const char *key, T value){
  tempJDOC[key] = value;
}

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

  setValue("a", 5);
  setValue("b", "xyz");

  serializeJson(tempJDOC, Serial);
}

void loop() {
}

```

the compiler will create function based on this template for every different type you use as second parameter in your sketch

# Answer
> 1 votes
The short answer is “no, it's not possible”. You will have to use two different functions. These two functions can share the same name, using function overloading. You can even have the compiler write these functions for you, based on a template you provide, as shown in Juraj's answer. These language features help provide the illusion of there being a single function. But it's just an illusion, albeit a useful one that helps with program readability. At the fundamental level, you still have two different functions.

---
Tags: functions
---


# Question
Title: the code and the actual output didn't match
i want to make the stuff, which the output is written from the analogread, but when the A3 == HIGH, the output pin 9 is used, but when the A3 == LOW, the output pin 10 is used, and when i simulate it on proteus, it seems not the same as i mean, what's wrong with the code, please need your help.

```
  int hasil
  int reado;
  int z;
  int baca;
  bool en = false;
  void setup() {
  // put your setup code here, to run once:

  TCCR1A = 0b00100010;
  TCCR1B = 0b00011001;
  TCCR0A = 0; TCCR0B = 0;
  ICR1 = 100000;//disable millis, delay and mciroseconds function
  //disable millis, delay and mciroseconds function

   // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(A2, INPUT); pinMode(A3, INPUT);
  pinMode(9,OUTPUT); pinMode(10,OUTPUT);
  }

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

 hasil = analogRead(A2);
 baca = digitalRead(A3);
 for (z=0; z<=hasil; z++)
 reado = map (hasil, 0, 255, 0, ICR1);
 if (hasil > 30 && baca == HIGH)
 {analogWrite(9,hasil); analogWrite(10,0);}
 else if (hasil >30 && baca == LOW)
 {analogWrite(9,0); analogWrite(10,hasil);}
 else if (hasil<30)
 {analogWrite(9, 0);
 analogWrite(10, 0);}}

```

# Answer
> 1 votes
You wrote:

> when i simulate it on proteus, it seems not the same as i mean

The attached picture is not very clear, but it seems to me that it's doing exactly what you asked for: a PWM output that switches between two different output pins. The program should work as expected, with only a few caveats. Let me comment it in some detail:

```
ICR1 = 100000;

```

Here you are setting `ICR1` to 34464 (i.e. 100000 modulo 216). This is likely not what you mean...

```
Serial.begin(115200);

```

There is no point in initializing the serial interface if you are not going to use it.

```
for (z = 0; z <= hasil; z++)
    reado = map(hasil, 0, 255, 0, ICR1);

```

There is no point in calculating many times the exact same value. Actually, there is no point in calculating it even a single time, since you are not using the result anywhere in your program.

```
analogWrite(9, hasil);

```

Here you are setting the duty cycle to some number between 31 and 1023. Given that the top value of the timer is 34464, the actual duty cycle will always be less than 3%. This is the reason why it looks like a series of narrow spikes on the virtual scope.

But maybe what you really meant is

```
reado = map(hasil, 0, 1023, 0, ICR1); // note: 1023, not 255
analogWrite(9, reado);

```

I would not recommend using `analogWrite()` with a non-standard top counter value. There is a special case handled in `analogWrite()` where, if the argument happens to be 255, you get instead a `digitalWrite(pin, HIGH)`. This is most likely *not* what you want. Now that you started controlling the timer with raw IO access, you should continue this way.

```
else if (hasil < 30)

```

Did you consider what the program should do if `hasil` happens to be exactly 30? None of the if/else cases would then match. You probably meant

```
else if (hasil <= 30)

```

but, as suggested by user11249082's answer, a plain `else` is the best way to ensure you did cover all possible cases.

# Answer
> 0 votes
The problem as i can see exist in the if else statements . You use multiple else if statements but in the end you must end it with else statement . Use the “if/else if” if you need to choose either one or none of a series of options. You could write the above program using separate if statements such as show below but the if/else if approach is cleaner and better indicates that the program should choose either one or none of the options Here how you do it If (){}.... Else if (){}..... Else if(){} ...... Else{} here this can help you enter link description here

---
Tags: pwm, adc
---


# Question
Title: VirtualWire `vw_get_message`: docs and examples on the PJRC site
I'm looking at he following page, that describes functions from VirtualWire library and provides some examples.

https://www.pjrc.com/teensy/td\_libs\_VirtualWire.html

Some basic questions I have after reading it:

1. The description of `vw_get_message` function states.

> Read the last received message. This should be called only when a message is known to be received with any of the 3 functions above.

"3 functions above" refers to `vw_have_message`, `vw_wait_rx` and `vw_wait_rx_max` functions.

However, in the example on that very same page `vw_get_message` function is called from receiver's `loop()` without making any attempts to call any of those 3 functions first.

Why? Is it legal to use `vw_get_message` by itself? And how does it work in this case, i.e. what is the semantics of the return value?

The function is explicitly described as non-blocking, apparently implying that if this usage is legal, there's no way to tell "corrupted message" situation from "no message" situation.
2. Does the library preserve the granularity/separation of messages? I.e if the TX side sends 1-byte messages, does it guarantee that each call to `vw_get_message` on RX side will return 1-byte messages? It seems to be implied by the description of the protocol, but I'd like to ask just in case.
3. If the answer to the second question is "yes", then does this API preserve zero-length messages? Or are they discarded immediately?

# Answer
> 1 votes
1. The example with only `vw_get_message` is the common usage of the VirtualWire library. It returns `true` if something was received and the checksum was okay.
2. Yes, each message is seperated from the other messages. Each message gets extra bits (intro bits) and extra bytes (checksum and length).
3. I don't know, I have never tested that. Looking at the source code, there is no problem with zero length messages.

The VirtualWire library is outdated, although it is still used with Arduino boards with little memory (Arduino Uno, Nano, Leonardo, Pro Mini, and so on).
The RadioHead library (www.airspayce.com/mikem/arduino/RadioHead) has included the VirtualWire protocol with the RH\_ASK mode. The examples for the RH\_ASK mode shows that the usage is almost the same. The RadioHead library should be used when there is more memory (Arduino MKR, Zero, Due, and so on).

---
Tags: virtualwire
---


# Question
Title: About UART one transmitter multiple receivers
I have vector nav vn100 IMU that sends data serially rs232...I want to drive 4 servo motors using atmega32 upon roll angel from vector nav vn100..atmega32 can only drive 2 servos using hardware fast pwm mode 14...so I should to use two atmega32...so I should receive the vn100 message to the two atmega32...my question is ..does UART rs323 support one transmitter multiple receivers?

# Answer
> 0 votes
If you do not need the control lines, and the communication is only one way, then yes, you can connect the TX (transmit) of the IMU to the RX (receive) of both microcontrollers. On the other hand, connecting one RX to multiple TX is likely to burn something.

Note however that the ATmega MCUs do not support RS-232 communication. If you want to go this way, you will then have to attach an RS-232 transceiver to each MCU. If the distances are short (say, a few centimeters), I would recommend using “serial TTL” instead.

---
Tags: serial, servo, avr, serial-data
---


# Question
Title: Encoder coupled with motor shaft.Encoder is giving larger redings than expected
I am a rookie and i dont have much experience on arduino. please help me. I intend to build a robot that will drive on a straight path even on nonuniform surfaces like the ones we see in agricultural fields(It is just a prototype, so i want to run it on normal offroad surfaces).The robot has 4 motors, one for each wheel. I plan to use encoder feedback method to drive straight. Right now, I have coupled a slotted disc to the shaft of a dc motor and i am trying to get the counts from the encoder and display the count after a certain interval(5 seconds) on serial monitor. The count that i get is way off the mark. The disc is having 30 slots. With just 2 to 3 rotations I am getting a count of around 180.

I am using arduino R3. Encoder output:- Pin2 (external interrupt) motor Pins :- 8,9 I am attaching the code below.

```
const int motorPin1  = 8;  // Pin 14 of L293
const int motorPin2  = 9;  // Pin 10 of L293
const int encoder_pin = 2;
volatile unsigned int count = 0;
 int time1 = 0;
 int time2 = 0;
void setup() {
  // put your setup code here, to run once:
  pinMode(motorPin1, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    pinMode(encoder_pin,INPUT);
    digitalWrite(encoder_pin,HIGH);
    attachInterrupt(0,encoder,RISING);
    Serial.begin(9600);
     digitalWrite(motorPin1,HIGH);
    digitalWrite(motorPin2,LOW);
    time1 = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
    time2 = millis();
    if(abs((time2 - time1) > 5000))
    {
    digitalWrite(motorPin1,LOW);
    digitalWrite(motorPin2,LOW);
    Serial.println(count);
    }
}

 void encoder()
 {
  count++;

 }

```

the end of code

The disc that i have mounted on the shaft doesn't rotate in vertical plane exactly. But i do get the blinks on the encoder when i rotate the shaft with my hand.Can that misalignment be the reason.

# Answer
I guess this is a kind of debouncing problem, caused by noise on the interrupt pin. The behaviour might also get worsened by the disalignment you mentioned. You could verify this by manually rotating the shaft, even though you "get the blinks" I doubt they are accurate in count.

If that is the case there are two things you could do:

* add a capacity or a RC filter to the interrupt pin to smoothen out voltage peaks if there are some. This will decrease the chance that the interrupt gets triggered accidentially (and will **not** solve the problem), but as a low pass it also limits the maximum count rate you are able to detect.
* implement debouncing in software. This is usually done by ignoring the input signal for a specific amount of time ("deadtime") after an interrupt has occured. As you are expecting a periodic signal and debouncing behaviour might be different at different speed it could be a good idea to capture the time span between two "blinks" and make the deadtime dependend on this calculated speed.

Something else: the way you check for the timestamp is little incorrect. You should instead do something like this:

```
void setup() {
  unsigned long starttime=millis();
}

void loop() {
  if (millis()-starttime > 5000) {
    starttime=millis();
    // put code here to run every 5000 ms
  }
}

```
> 1 votes

# Answer
Usually a rotary encoder has at least 2 sensors.

Incremental rotary encoders usually only have 2 sensors. Absolute or positional encoders have more, and let you figure out the absolute orientation of your sensor by reading a bit pattern.

To read an incremental encoder you write your code to only pay attention to alternating changes in the sensors. That gives you automatic debouncing of the contacts. I suggest you search for Arduino code for decoding rotary encoders.
> 0 votes

---
Tags: arduino-uno, motor, switch, rotary-encoder
---


# Question
Title: Controlling a Stepper Motor - sending to specific positions on a 'buttonPushCounter ==' cue, forwards and backwards
I am working on a project using an Arduino control a Stepper Motor. The motor drives a lead screw which moves coloured filters to specific positions along a linear track - forwards and backwards. The movements are triggered by another device that counts its revolutions (using a sensor. The Arduino reads the inputs and activates the motor on specific revs ie. at 10 move 70mm forwards, at 30 move 70mm backwards. I can control the Stepper to execute precise moves repeatedly one after another, independently of the counter. I can link the Arduino to the counter and switch on/off an LED at specified counts. But when I try to run the motors from the counter, it's triggered but only moves in tiny discontinuous steps, and only goes one way. Here is that Sketch below. Any help very welcome. Thanks.

```

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  if (buttonPushCounter == 10) {
    digitalWrite(ledPin, HIGH);
    Astepper1.moveTo(600);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  if (buttonPushCounter == 30) {
    digitalWrite(ledPin, LOW);
    Astepper1.moveTo(200);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  }
}

```

# Answer
> 1 votes
Thanks. Your description of the fault makes sense to me. As you point out blocking would be a problem as I need the counter to continue to be registering while the movement is being executed. I've revised the script as you suggest - inside the loop but outside the if statement - have I done as you meant? But the same problem occurs - the motor advances in single steps.

```

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // save the current state as the last state, for next time through the loop
    lastButtonState = buttonState;

    if (buttonPushCounter == 10 ) {
      digitalWrite(ledPin, HIGH);
      Astepper1.moveTo(20000);
      Astepper1.setAcceleration(6000.0);
      Astepper1.setSpeed(600);
      //Astepper1.setSpeed(600);
      Astepper1.run();
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

    if (buttonPushCounter == 30) {
      digitalWrite(ledPin, LOW);
      Astepper1.moveTo(200);
      Astepper1.setSpeed(600);
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

  }

```

# Answer
> 0 votes
There are several `run`-like methods in the AccelStepper library.

The one you are using, `run()`, is intended to be called at **EVERY** pass through `loop()`, and it will only cause a step if one is necessary, based on the internal state of the library (i.e., current position, target position, acceleration profile, etc.) It is safe to call so often -- it will determine itself if there is any motion needed.

You could move the `run()` call to a place inside `loop()`, but outside of any `if` statements.

Alternatively, there is a `runToPosition()` function, which is blocking -- it will stop all execution of your code until the stepper is at the target position. This would be fine for your current code as posted, but if you wish to monitor the revolution counter also, then this would not be the best option to take.

---
Tags: stepper
---