# Question
Title: 3,6V DC motor spinning with L298N and Arduino
I'm trying to control a re used DC motor from a drill (3,6V) with a L298N and a Arduino. It's powered with a 5V - 60A power supply.

I tried to follow this step by step tutorial (https://www.youtube.com/watch?v=dyjo\_ggEtVU) but the motor is not spinning..yet. I can ear a noise, it starts to spin a micron and then stops.

I though that it could be something wrong with the power supply but I connected the 4V battery from the drill and the same thing is happening. If I connect the motor directly to the battery it is spinning nicely...

I though then that it was a code issue but I tried a no load test and measured the voltage without the motor -\> I've the 4V required voltage. When the motor is connected I have 300mV instead of 4V.

Do you know what could go wrong? Is the L298 dead? just got it a few hours ago...

Would be nice if you have any clue.

Many thanks.

// Commande moteur int enA = 9; int in1 = 8; int in2 = 7;

```
void setup()
{
  // Définition des sorties

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  //Sens de rotation du moteur

  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);

  //Vitesse de rotation du moteur

  analogWrite(enA, 200);

  //Delay

  delay(5000);

   //Arrêt du moteur

  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
}

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

}

```

# Answer
The L239 is a terrible motor driver. It's the kind of motor driver Noah used to control The Ark.

It requires a power supply that is at least 2.5V more than the "logic input high" voltage, which is rated at 2.3V. That means an *absolute minimum* of 4.8V, which is borderline for the Arduino's 5V pin, especially if you are running off USB (which can drop as low as 4.75V and still be within specification) and *way* out when powered from the battery. It's really designed for driving motors in the 12V+ range.

To drive a low voltage motor like yours you need to pick a more modern MOSFET based motor driver.
> 1 votes

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


# Question
Title: Nothing received from function returning array of strings
My `read` function returns an array of strings. i.e ssid and password

```
String* configuration::read() {
    String rw_ssid = "";
    String rw_pswd = "";
    const int keys = 2;
    String read_ssid_pswd [keys];
    if (EEPROM.read(0) != 0) {

      for (int i = 0; i < 32; ++i) {
        rw_ssid += char(EEPROM.read(i));
      }
      for (int i = 32; i < 96; ++i) {
        rw_pswd += char(EEPROM.read(i));
      }
      Serial.print("rPASSWORD: ");
      Serial.println(rw_pswd);
      read_ssid_pswd[0] = rw_ssid;
      read_ssid_pswd[1] = rw_pswd;
      Serial.print("Sending ssid:");
      Serial.print(read_ssid_pswd[0]);
      Serial.print(" Pswd: ");
      Serial.println(read_ssid_pswd[1]);
      return read_ssid_pswd;
    } else {
      Serial.println("Data wifi not found!");
      return read_ssid_pswd;
    }
}

```

I can see the print in the serial monitor.

```
Sending ssid:SSID Pswd: password

```

but where this function is called from I have set it up like this:

```
void setup() {
  Serial.begin(115200);
  Eeprom::configuration::initialize();
  String* ssid_password = Eeprom::configuration::read();
  Serial.print(">SSID: ");
  Serial.println(ssid_password[0]);
  Serial.print(">Password: ");
  Serial.println(ssid_password[1]);
  Funcs::connection::connectWifi(ssid_password[0], ssid_password[1]);
}

```

and I get thing in the prints I thought its not giving any error at compile time so it should be correct.

# Answer
> 1 votes
Majenko has it right, your String array should be allocated in Setup(). Notice that I passed back the success/failure of your initial EEPROM test as the return value.

```
void setup() {
  Serial.begin(115200);
  Eeprom::configuration::initialize();
  const int keys = 2;
  String ssid_password[keys];
  if (Eeprom::configuration::read(ssid_password)) {
    Serial.print(">SSID: ");
    Serial.println(ssid_password[0]);
    Serial.print(">Password: ");
    Serial.println(ssid_password[1]);
    Funcs::connection::connectWifi(ssid_password[0], ssid_password[1]);
  } else {
    Serial.println("Data wifi was not found!");
  }
}

```

The String array is the parameter, not the return value. It is passed by reference. The copying of EEPROM chars to String doesn't need to be into temporary variables, in fact it's inefficient and pointless; it can go straight into read\_ssid\_pswd\[0\] and \[1\], but I didn't want to change your code excessively, and delete the debugging serial writes.

```
bool configuration::read(String read_ssid_pswd[]) {
    String rw_ssid = "";
    String rw_pswd = "";
    if (EEPROM.read(0) != 0) {

      for (int i = 0; i < 32; ++i) {
        rw_ssid += char(EEPROM.read(i));
      }
      for (int i = 32; i < 96; ++i) {
        rw_pswd += char(EEPROM.read(i));
      }
      Serial.print("rSSID: ");
      Serial.println(rw_ssid);
      Serial.print("rPASSWORD: ");
      Serial.println(rw_pswd);

      read_ssid_pswd[0] = rw_ssid;
      read_ssid_pswd[1] = rw_pswd;
      Serial.print("Sending ssid:");
      Serial.print(read_ssid_pswd[0]);
      Serial.print(" Pswd: ");
      Serial.println(read_ssid_pswd[1]);
      return true;
    } else {
      Serial.println("Data wifi not found!");
      return false;
    }
}

```

# Answer
> 2 votes
You can't return locally defined arrays like that. The array only exists in the function, and all you do is return a pointer to where that array was. As the array has gone when you leave the function your pointer just points to garbage.

Instead you should pass an array to the function that the function then populates.

---
Tags: esp8266, string, array, cpp
---


title: Debugging RN 42 HID Mouse

text:
# Question
Title: Debugging RN 42 HID Mouse
I'm trying to use the RN 42 and Arduino Uno to control a bluetooth mouse. I configured the RN 42 with the commands S~,6 and SH,0220 and R,1 to put the device in HID mouse mode. Is there anything I missed? Below is the sketch I am using to send mouse reports to the bluetooth. The sketch compiles fine, but moving the joystick does not move the cursor. I included a line of code at the end to print on the serial port whatever data is being sent through software serial to the bluetooth. However when I view the serial monitor, I get back a lot of reversed question marks. Anyone know why this is? Thanks in advance.

```

const int bluetoothTx = 4;    // TX pin of RN-42, Arduino D2 (configure as RX pin of Ard)
const int bluetoothRx = 3;    // RX pin of RN-42, Arduino D3 (configure as TX pin)
const int button = 5;
const int xAxis = A0;         // joystick X axis
const int yAxis = A1;         // joystick Y axis
int range = 12;               // output range of X or Y movement
int responseDelay = 5;        // response delay of the mouse, in ms
int threshold = range / 4;    // resting threshold
int center = range / 2;       // resting position value

SoftwareSerial BT(bluetoothTx, bluetoothRx); // args SoftwareSerial(RXpin, TXpin)

void mouseCommand(byte buttons, byte x, byte y) {
  BT.write((byte)0xFD);
  BT.write((byte)0x05);
  BT.write((byte)0x02);
  BT.write((byte)buttons);
  BT.write((byte)x);
  BT.write((byte)y);
  BT.write((byte)0x00);
}

int readAxis(int thisAxis) {
  // read the analog input:
  int reading = analogRead(thisAxis);

  // map the reading from the analog input range to the output range:
  reading = map(reading, 0, 1023, 0, 12);

  /* threshold prevents the mouse from reading small unintentional movements.
  If the output reading is outside from the rest position threshold, use it: */
  int distance = reading - center;

  if (abs(distance) < threshold) {
    distance = 0;
  }

  // return the scaled distance for this axis:
  return distance;
}

void setup() {
  pinMode(button, INPUT);
  pinMode(bluetoothTx, INPUT); // bluetoothTX is equivalent to arduino RX pin
  pinMode(bluetoothRx, OUTPUT);
  Serial.begin(115200);  // Begin the serial monitor at 115200bps
  BT.begin(115200);  // RN-42 defaults to 115200bps
}

void loop() {
  // read and scale the two axes:
  int xReading = readAxis(xAxis);
  int yReading = readAxis(yAxis);
  int buttonState = digitalRead(button);

  // move the mouse:
  mouseCommand(buttonState, xReading, yReading);
  delay(responseDelay);

  if(BT.available())  // If there's data being sent to the bluetooth module
  {
    // Send any characters the bluetooth receives to the serial monitor
    Serial.print((char)BT.read());
  }
}

```

# Answer
> 2 votes
The problem with getting no response from the mouse was that the bluetooth did not auto reconnect to the computer after powering down. I solved this by sending the command SM,6 for auto reconnect and then R,1 to reboot.

---
Tags: bluetooth, softwareserial, mouse, hid
---


# Question
Title: Is it possible to use Pi's output signal as Arduino's input signal?
I have a relay attached to an Arduino Uno which I want to control using my raspberry pi 3b. And yes I know it can be done by attaching the relay directly to Pi but I cannot do so. Don't ask me why. That is why I want to know whether it is possible to use Pi's output signal as input for the Arduino or not. I do not have spare parts so I don't want to experiment. If anyone knows about this, please tell me.

# Answer
> 1 votes
This way is fine: the Pi is a 3.3V based board, so connecting one of the GPIO pin from the pi to an Arduino will not damage it. Furthermore, the 3.3V are sufficient to be considered as `HIGH` even on a 5v Arduino like the UNO.

The other way around: connecting the *output* of a 5V Arduino to the *input* of a pi, will very likely damage the raspberry Pi!

So beware of your Pinmode before doing such a connection!

---
Tags: arduino-uno, raspberrypi
---


title: How to toggle LED on button press?

text:
# Question
Title: How to toggle LED on button press?
I want to have a LED turn on when I push a button and go off when I push the button a second time.

This code doesn't work:

```
const int buttonPin = 4;
const int motorPin =  10;
const int ledPin = 6;
 int x = 1;
// variables will change:
int buttonState = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && x==1) {
     digitalWrite(motorPin , 1);
     x=0;
    }
  if (buttonState == HIGH && x==0){
    digitalWrite(motorPin, 0);
    x=1;
  }
  delay(1);
}

```

What could be wrong?

# Answer
> 5 votes
At the moment, you've got two main problems. Firstly, both your `if` statements are being triggered one after the other. This is because the first `if` statement sets `x` to 0, which is part of the condition the second `if` statement looks for.

The second problem is that you're not monitoring the previous state of the button. `buttonState` will appear `HIGH` every time round loop, even if the button has been held down for several seconds. The result is that the output pin will be quickly getting turned on and off all the time.

What you need to do is store the last known state of the button. On every iteration of the main loop, only respond to the button if it's currently `HIGH`, *and* if it was `LOW` last time round the loop. You also need to make sure your two `if` statements are mutually exclusive; i.e. if you trigger one then don't trigger the other by mistake too, or it will cancel it out.

Something like this should work better:

```
// This will store the last known state of the button
int oldButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

```

As noted elsewhere, you still need to debounce the button, otherwise you're likely to get some false-positives. That can be done in hardware or software. A really simple way to get around it temporarily is to put in a delay of several milliseconds every time you detect the button changing state. It's not perfect, but it might be enough to get you started.

# Answer
> 4 votes
Don't forget to turn ON the LED:

```
digitalWrite(ledPin, HIGH);

```

And OFF:

```
digitalWrite(ledPin, LOW);

```

# Answer
> 2 votes
You are not handling debouncing at all. Mechanical buttons typically bounce for a few milliseconds after an "on" press. Arduino software (or some specialist hardware) needs to handle this. This really matters when you expect a button to toggle some output pin.

# Answer
> 2 votes
I just grabbed the version from the ones above here and made is somewhat smaller in terms of code. Feel free to use it in your Arduino app.

```
// This will store the last known state of the button
int lastButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int currentButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (currentButtonState == HIGH && lastButtonState == LOW) {
     // Switch the state of the output
     digitalWrite(ledPin, !digitalRead(ledPin));
  }

  // Store the button's state so we can tell if it's changed next time round
  lastButtonState = currentButtonState;
}

```

# Answer
> 2 votes
You don't need a separate variable to store the state of the LED. The output pin register does that already. So you can toggle the LED simply with

```
    digitalWrite(ledPin, !digitalRead(ledPin));

```

or if you prefer

```
    if(digitalRead(ledPin))
       digitalWrite(ledPin, 0);
    else
       digitalWrite(ledPin, 1);

```

In you code the loop executes many times while the key is bouncing. If you delay by at least 50mS after the key press is first detected, and you have toggled the led and turned on the motor, then you have effectively debounced the button. If you hold the key down continously the led will toggle every 50mS (plus a little overhead)

# Answer
> 1 votes
Pinouts, pullups and logic errors have been addressed elsewhere, so I will focus on switch debouncing. Debouncing, in my opinion, is best handled in software (rather than hardware) for large volume production costs and lazy programmers (like me). For small projects a simple pullup / cap circuit offers better reliability and improved speed, but I'm just lazy in my old age. Also keep in mind that switch bounce worsens significantly over the life of a switch. I've seen new PB's with bounce \< 20 ms worsen to over 300 ms with reasonable usage, so keep that in mind with projects that become semi-permanent.

Here's what I use for a software solution on a fairly bouncy SPST NO pushbutton. In this case, I'm using NO PB to GND with 1K external pullups, since I personally don't want to depend on whether or not the internal pullup still works on older devices I may have abused in a former life.... Of course, arguments could be made for various areas still needing cleanup, improved encapsulation, quicker response, higher quality, etc., but this works for me for now.

inSw.h:

```
class inSw
{
private:
    volatile boolean swState;           // current state ( 0 / 1 ) of switch

public:
    uint8_t  pinNum;
    volatile unsigned long lastPush;    // Time (millis() ) when last switch push detected
    unsigned long debTime = 30;         // Time (micros() ) required to debounce switch

    void init(uint8_t sw);
    boolean readState(void);
} ;

```

inSw.cpp:

```
void inSw::init(uint8_t sw) {
    pinNum = sw;
    pinMode(sw, INPUT);
    swState = 0;
    lastPush = millis();
};

boolean inSw::readState() {
//  swState = digitalRead(pinNum);
return swState;
}
void setupSwitches(void) {
    swS1.init(I2C_SOA);     // pin D20
    attachInterrupt(digitalPinToInterrupt(swS1.pinNum), swS1Press, FALLING);
}

```

Interrupt Service Routines are placed outside Setup() and Loop(), with the attachInterrupt (above) called from inside Setup(). This allows the switch to break long-running routines, such as Stepper.step(10000) which bangs against the limit switch on step 14....

```
void swS1Press() {
    unsigned long now = millis();
    if (swS1.lastPush < (now - swS1.debTime)) { // if newly pushed
        RunStop.toggle();
        swS1.lastPush = millis();       // sw last pushed now

        if (RunStop.val == RS_RUN)
            digitalWrite(LED_PIN, HIGH);   // set the LED on
        else
            digitalWrite(LED_PIN, LOW);   // set the LED off
    }
}

```

Lastly, just remember to check the switch state at various points inside loop(). I use this switch as an emergency stop switch, and the onboard LED to ensure it triggers.

# Answer
> 1 votes
```
// When first time program launches it confused to press push button twice. Well replace it with this

if (x == 1) {
    // Toggle on
    digitalWrite(ledPin, HIGH);
    x = 0;
} else {
    // Toggle off
    digitalWrite(ledPin, LOW);
    x = 1;
}

```

# Answer
> 1 votes
success case tested OK,modified from arduino examples.UNO r3,atmega 328 try it !!!!!

```
/*  The circuit:
  - pushbutton attached to pin 2 from +5V
  - 10 kilohm resistor attached to pin 2 from ground
  - LED attached from pin 13 to ground (or use the built-in LED on most
    Arduino boards)
*/

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 8;       // 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

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);

  // 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");
    }
    // Delay a little bit to avoid bouncing
    delay(10);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  // turns on the LED every four button pushes by checking the modulo of the
  // button push counter. the modulo function gives you the remainder of the
  // division of two numbers:
  if (buttonPushCounter % 2 == 0) {
    digitalWrite(ledPin, LOW);
  } else {
    digitalWrite(ledPin, HIGH);
  }
}

```

# Answer
> 1 votes
check this code. I have made some changes in your code. its working.

```
const int buttonPin = 2;
const int motorPin =  6;
const int ledPin = 13;
int x = 1;
// variables will change:
int buttonState = 0;

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

void loop() {

  buttonState = digitalRead(buttonPin);
//  Serial.println(x);
  if(buttonState == LOW && x == 1)
  {
    Serial.println("buttonState == HIGH && x == 1");
    digitalWrite(ledPin, HIGH);
    delay(500);
    x = 0;
    Serial.println("x == 0");
  }
  else if (buttonState == LOW && x == 0)
  {
    Serial.println("buttonState == HIGH && x == 0");
    digitalWrite(ledPin, LOW);
    delay(500);
    x = 1;
    Serial.println("x == 1");
  }
  delay(1);
}

```

# Answer
> 0 votes
hello sachleen try this code it working I edited from your code

```
// This will store the last known state of the button
const int buttonPin = A15;   // change as per your button attached.
const int motorPin =  12;   //
const int ledPin = 13;
 int x = 1;
// variables will change:
int buttonState = 0;
int oldButtonState = LOW;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

```

---
Tags: button
---


title: HMAC SHA256 in Arduino use case?

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

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

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

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

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

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

```
const uint32_t sha256K[] PROGMEM = {

```

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

In sha256.h:

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

```

In sha256.cpp:

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

```

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

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

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

```
#include "sha256.h"
Sha256 sha;

```

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

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

```

Then it works as well.
> 2 votes

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

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

```

from the header files. Then it is working fine.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to eliminate noise from PWM controlled 12V fan at low speed
I am trying to build a simple fan controller (single fan). So far I have successfully created a circuit which powers the fan with an external 12v DC adapter and added a transistor (NPN) to switch it on and off. The transistor is connected to a PWM port on the Arduino.

When putting `HIGH` on the port the fan works perfectly at high speed, but when I want to lower the speed (say `analogWrite(fanPin, 150)`) it starts to make a humming noise. I believe this is caused by the use of PWM.

What is the best way to control the speed of the fan without (too much) noise?

ps. The fan is a Cooler Master 3-wire PC fan. Transistor is a P2N2222A.

**Update**: Here is the schema I am using:

# Answer
> 4 votes
I had the same problem with a 5V fan. Something simple worked for me: To **decrease** the PWM frequency. You probably want to do this using pin 9 or 10 (for the Uno) as changing the frequencies of other PWM pins messes up the delay and millis functions. Details on how to do it and a very convenient function are provided in http://playground.arduino.cc/Code/PwmFrequency. In my case, using the lowest frequency possible (31250/1024 = 31Hz), I completely eliminated the hum for higher speeds and significantly reduced it for lower speeds. And by the way, I used the PWM pin to drive a MOSFET since the current of my fan was 140 mA, much higher than the 20 mA Arduino pins can safely provide.

# Answer
> 3 votes
Try using pin 3 (or 11) and lower the prescaler of timer 2 using the following code in your `setup`;

```
//move from /64 prescaler to /32 prescaler
TCCR2B |= _BV(CS20);//set bit (remove this line for a /8 prescaler)
TCCR2B |= _BV(CS21);//set bit
TCCR2B &= ~_BV(CS22);//clear bit

```

Halving the prescaler will double the frequency.

# Answer
> 3 votes
It might help to use a capacitor to smooth your PWM signal.

See http://ww1.microchip.com/downloads/en/AppNotes/00771b.pdf

# Answer
> 0 votes
**coment** add circuit to know what you have done

Does your circuit looks similar like:

Do you use resistor for transistor? Diode for fan?

I suspect that you do not have diode.

The purpose of the diode is to allow current that is flowing in the motor coil to continue to flow in the same direction when the transistor turns off. When the transistor turns off, the voltage at the transistor collector will **rise** as it was flowing out of the motor. From **Vce(SAT)** it will rise above the power supply voltage and stop only when the transistor breaks down (or when it starts to ring with parasitic capacitance). By putting a diode from the transistor collector to the +12V rail, you prevent the voltage across the transistor from exceeding 12V and and allow the motor current to continue to flow.

# Answer
> 0 votes
There is also the possibility adding a capacitor bypassing the transistor. But you have to be careful, if the capacity is to big you could damage your transistor.

# Answer
> 0 votes
SAS is correct - lowering the PWM to 31Hz works great. Tested using a 12v fan. Before lowering the PWM, the sound from the fan was a loud "WHEEEEEeeeeeeeee" sound at any speed other than full speed. Low speed made the sound worse.

After lowering the PWM frequency, the noise is inaudible at higher speeds. At lower speeds you might hear a light "clicking" noise. The sound reminds me of the faint "clicking" noise you hear as the valves on a car engine open and close.

# Answer
> 0 votes
I can also confirm that SAS answer ist correct. I tested it with a 5V DC fan. I hear a very high noise at lower speed, but you have to listen closely, and a very fast clicking noise at higher speeds.

All in all i would say lowering the PWM to the suggested 31Hz did it for me but it is not a perfect solution.

# Answer
> 0 votes
I get that this post is 4 year old, but I successfully removed all fan noise with simple electrolytic cap and one ceramic on output, after adding caps you need to bias RPM. You can still get some relay low squeak coming from mosfet but only on low RPM

# Answer
> 0 votes
25kHz power PWM solved this problem for my 3-pin fan. Diode had no effect on noise, it fixes another problem (EMI).

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


title: GPS stream question

text:
# Question
Title: GPS stream question
I have an adafruit Ultimate GPS unit, its working fine. I am reading the GPS stream, via the command line, and one of the details, is "Angle: 167.97" I looked at a page about GPS sentences, but I'm still confused. Angle, is the direction of wind, or rudder, or angle at altitude. In this case i would guess its either rudder (because I don't know what rudder it may be referring to) or wind angle. Its changing frequently, but the device is stationary in my shed.

My questions are: What is angle referring to? as in, is it wind or rudder? And where is it referring to? obviously, its not getting that data from its present location, so is that data coming from a whether station or something?

pardon me if this is the wrong exchange to post in, Im not sure where to ask.

# Answer
> 1 votes
It will be referring to the angle of travel. That is, if you're moving (say driving in a car) what direction that movement is in.

But since you aren't moving the angle is meaningless. Instead it's trying to work out a direction from the random noise of the slight changes in the calculated location.

Unless your shed is in a tornado and flying through the air then the angle is not something you need to care about. Ignore it.

---
Tags: gps
---


# Question
Title: DC motor makes noise but does not rotate
i am following Jeremy blum's tutorial on youtube. link i have done the exact same circuit design as he has.

but the dc motor just makes a continuous beep sound when i run this code.

```
int motorPin = 9;

void setup()
{
    pinMode(motorPin, OUTPUT);
}

void loop()

{
    for(int i = 0; i <= 255; i++)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);

    for(int i = 255; i >= 0; i--)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);
}

```

I am clueless as to why this is happening. would be glad if someone could help me out here.

# Answer
> 3 votes
For the benefit of anyone reading Jeremy Blum's Exploring Arduino book who is having the same issue- he has labelled the transistor wrong in the book so the collector and emitter are back to front. Turn the transistor around to face the other way and your issue will be resolved.

# Answer
> 1 votes
analogWrite uses PWM. Is the motor you are using designed for pulsed operation? Try using

```
digitalWrite(motorPin, HIGH);

```

# Answer
> 1 votes
I'm wondering if a 10 ms delay between steps is long enough for the motor to respond, especially with a cap across its terminals. Besides that the whole thing is over in 5 seconds.

It seems to me that AnalogWrite generates a PWM signal of about 500hz or about 2ms wave period. So in 10 ms you get 5 pulses of the same amplitude and smoothed by the cap. At low values of "i", say i=10, then the pulse is only 10/255\*2ms wide or about 78uS. At low values of i, a 180deg rotation has to occur in the time you apply the pulse for the motor to rotate, well not exactly but close enough.

Most small DC motors are 2 pole, so you're expecting at least one 180degree rotation in 5x78uS or about in 400uS. That would be a full rotation in about 800uS, say 1mS, or 1000 rotations in 1 second, or 60000rpm, from a standing start if the duty cycle was held constant. You have very little power at low "i" so I'd be surprised if there is enough to overcome friction and inertia. On higher values I guess it's still not enough to overcome the inertia.

The motor well may run at the higher values of "i" but then the program immediately counts down again.

So I suggest you start the counter at say 125 or even higher. Also make the delay between counting up and counting back down much longer so you can actually see the effect before it counts down again. I would also want to make the delay between counts higher so there is more time for current to flow in the motor's (inductive) windings. Remember an inductor resists a change in current. Now that I think about it, this is probably more important than the inertia and friction.

So here is a challenge... Change the delay between counts first, and report your results here. Then reset that and change a different parameter, and so on. Eventually make a number of changes together...I'm curious to see the outcome.

By the way, I suspect the sound is from the motor laminations changing shape at high frequency.

Cheers P

# Answer
> 1 votes
I had the same issue, turns out that i had configured the BJT wrong. I had confused the drain for the collector.

---
Tags: programming, motor, sketch, pwm
---


# Question
Title: Blank project gives errors while uploading Arduino Leonardo on Linux Manjaro
I'm on Linux Manjaro. I plugged my Arduino Leonardo clone (that I know works correctly). And tried to flash a blank project on it: (My IDE version is `1.8.12`)

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

}

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

}

```

It gives me this error:

```
Sketch uses 3410 bytes (11%) of program storage space. Maximum is 28672 bytes.
Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2047)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM1'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Permission denied.
    at jssc.SerialPort.openPort(SerialPort.java:170)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

```

# Answer
Okay I found a way to do this. Open Terminal and type:

```
ls -l /dev/ttyACM*

```

you will get something like:

`crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0`

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is `dialout` (is the group owner of the file).

Now we just need to add our user to the group:

```
sudo usermod -a -G dialout <username>

```

So for me that would be:

```
sudo usermod -a -G dialout john

```

BUT it seems to work with `dialout` on ubuntu/debian based distros. I am on `Manjaro` and instead of `dialout` I had to use `uucp` (and in general on `Arch` based distros) so:

```
sudo usermod -a -G uucp john

```

You will need to log out and log in again for this change to take effect.

This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error

After this procedure, you should be able to proceed normally and upload the sketch to your board or use the Serial Monitor.

Although for me that wasn't over. After doing this the only error I got was Arduino IDe simply saying that it doesn't have permission to write to that port. So I had to start `Arduino IDE` by:

```
sudo arduino

```

in the terminal. After that everything works just fine.

I found help at those links:
> 2 votes

---
Tags: arduino-leonardo, uploading
---


# Question
Title: Why does my Arduino/Ledstrip combi not work?
simulate this circuit – Schematic created using CircuitLab

I am using an Arduino Uno, and WS2813 led strip (60 leds).

It seems like a default schematics (except I did use a 470 uF (electrolytical) cap instead of 1000 uF electrolytical cap.

(I accidantally marked the VCC pin of U1 VSS).

I don't get any LED of the LED strip glowing.

The program I used is:

```
#include <FastLED.h>

#define NUM_LEDS 60
#define DATA_PIN 7

CRGB leds[NUM_LEDS];
bool led = false;

void setup() {
    //FastLED.addLeds<WS2813, DATA_PIN>(leds, NUM_LEDS);
    FastLED.addLeds<WS2813, DATA_PIN>(leds, NUM_LEDS);
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    for (int i = 0; i < NUM_LEDS; i++)
    {
      leds[i] = CRGB::Red;
    }
    FastLED.show();
    led = !led;
    digitalWrite(LED_BUILTIN, led ? HIGH : LOW);
    delay(1000);
}

```

What I tried was:

* Checking different data pins on the Arduino
* Checking different wires
* Checking that over D7 and after the resistor there is indeed 330 Ohm resistance (it was 345 Ohm)
* Tried different data pins (and adapted the scene to use a different data pin)
* Checking that LED D1 is on (5V is flowing)
* Checking that at the end of the WS2813 there the VCC and GND 5V difference (it is about 5.1 V)
* Checking that there is indeed 5 V difference between the adapter + and - (was 5.2 V, unloaded).
* Tried with WS2813's BI grounded and unconnected
* Tried without the 330 ohm resistor.
* Checked with a the same circuit but WS2812B (and adapting the code to use WS2812B)
* Used different timings for the builtin LED to see that the sketch is actually uploaded.
* Tried with `, RGB)` added in line: `FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);`
* With a logic analyzer I see that every second there is a short burst of data (not analayzed exactly what, I assume FastLed is reliable).

All no difference.

However, what I did see, is the logic analyzer data AFTER the 330 ohm resistor mostly removes the data, while the data before the resistor is ok. However, when remove the resistance, still the LED strip does not light up.

Channel 0 is before the resistor, channel 1 after:

What did I do wrong?

# Answer
> 1 votes
It is important to connect the Arduino digital pin to the correct end of the LED strip.

LED strips have a unidirectional data line.

The power and ground connections can be made from either end, but the data IN is at one end and data OUT is at the other end.

That arrangement is for the purpose of daisychaining the LED strips.

The LEDs themselves also have data IN and data OUT, and are also daisychained with their neighbouring LEDs.

The LEDs are serially connected to each other through the data line, and are connected in parallel to the power and ground lines.

---
Tags: arduino-uno, led-strip
---


# Question
Title: Matrix and State Space Arduino Implementation
I wrote an Arduino Matrix class. Then I used this class to implement State Space on Arduino. During tests I stomped upon a problem. After starting the program it stops at some point. I have no idea why this is happening. There are no error messages. Can you please tell me what im doing wrong?

Here is my code:

```
//"Matrix.h"
#ifndef _Matrix_h
#define _Matrix_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif
class Matrix
{
private:
    unsigned row_number = 0;
    unsigned column_number = 0;
    double* elems;

public:

    //Constructors + Destructor
    Matrix();
    Matrix(double, unsigned row_number = 1, unsigned column_number = 1);
    Matrix(double*, unsigned row_number = 1, unsigned column_number = 1);
    Matrix(const char*);
    Matrix(const Matrix&);
    void operator=(Matrix);
    ~Matrix();

    //Comunication Methods
    unsigned get_rows() const { return row_number; };
    unsigned get_columns() const { return column_number; };
    double& operator()(const unsigned row, const unsigned column);
    double valueAt(unsigned row, unsigned column) const ;
    void print() const;
    bool mRead2();

    //Matrix Operations
    Matrix operator+(Matrix);
    Matrix operator-(Matrix);
    Matrix operator*(Matrix);
    Matrix transpose();

    //Scalar Operations
    Matrix operator+(double);
    Matrix operator-(double);
    Matrix operator*(double);
    Matrix operator/(double);

};
Matrix mRead(unsigned row,unsigned column);
#endif

```

```
//"Matrix.cpp"

#include "Matrix.h"
Matrix::Matrix() {
  row_number = 0;
  column_number = 0;
  elems = new double[0];
}
Matrix::Matrix(double val, unsigned row_number, unsigned column_number) {
  this->row_number = row_number;
  this->column_number = column_number;
  elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i < row_number * column_number + 1; i++)
    elems[i] = val;

}

Matrix::Matrix(double* elems, unsigned row_number, unsigned column_number)
{
  this->column_number = column_number;
  this->row_number = row_number;
  this->elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i < row_number * column_number + 1; i++)
    this->elems[i] = elems[i - 1];
}

Matrix::Matrix(const char*)
{

}

void Matrix::operator=(Matrix A){
  this->column_number = A.get_columns();
  this->row_number = A.get_rows();
  this->elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i <= row_number; i++)
    for (unsigned j = 1; j <= column_number; j++)
      this->elems[(i - 1) * (column_number) + j] =  A.valueAt(i, j);

}

Matrix::Matrix(const Matrix& A) {
  this->column_number = A.get_columns();
  this->row_number = A.get_rows();
  elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i <= row_number; i++)
    for (unsigned j = 1; j <= column_number; j++)
      this->elems[(i - 1) * (column_number) + j] =  A.valueAt(i, j);

}

Matrix::~Matrix()
{
  delete[] elems;
}

double& Matrix::operator()(const unsigned row, const unsigned column)
{

    return this->elems[(row - 1) * (column_number) + column ];

}

double Matrix::valueAt(unsigned row, unsigned column) const
{

    return this->elems[(row - 1) * (column_number) + column ];

}

void Matrix::print() const
{
  for (unsigned i = 1; i <= get_rows(); i++) {
    for (unsigned j = 1; j <= get_columns(); j++) {
      Serial.print(this->valueAt(i, j));
      Serial.print(" ");
      Serial.flush();
    }
    Serial.print("\n");
  }
}
Matrix mRead(unsigned row, unsigned column) {
  int sizeM = row * column;
  double m[sizeM];
  char buffor[64];
  for (int i = 0; i < 64; i++) {
    buffor[i] = 0;
  }
  for (int i = 0; i < sizeM; i++) {m[i]=0;}
  for (int i = 0; i < sizeM; i++) {
    while (!Serial.available()) {
      Serial.write(32);
    }
    int j = 0;
    while (Serial.available() > 0) {
      Serial.println(Serial.available());
      buffor[j] = Serial.read();
      j++;
      Serial.flush();
    }
    m[i] = (double)atof(buffor);
    Serial.flush();
    //for (int i = 0; i < 64; i++) {
    //  buffor[i] = 0;
    //}
  }
  return Matrix(m, row, column);
}
bool Matrix::mRead2() {
  int sizeM = row_number * column_number;
  double m[sizeM];
  char buffor[64];
  for (int i = 0; i < 64; i++) {
    buffor[i] = 0;
  }
  for (int i = 0; i < sizeM; i++) {m[i]=0;}
  for (int i = 0; i < sizeM; i++) {
    while (!Serial.available()) {
      Serial.write(32);
    }
    int j = 0;
    while (Serial.available() > 0) {
      Serial.println(Serial.available());
      buffor[j] = Serial.read();
      j++;
      Serial.flush();
    }
    m[i] = (double)atof(buffor);
    Serial.flush();
    for (int i = 0; i < 64; i++) {
      buffor[i] = 0;
    }
  }
  *this=Matrix(m,row_number,column_number);
  return true;
}
Matrix Matrix::operator+(Matrix A)
{
    Matrix sum = Matrix(0.0, row_number, column_number);
    for (unsigned i = 1; i <= row_number; i++)
      for (unsigned j = 1; j <= column_number; j++)
        sum(i, j) = A.valueAt(i, j) + this->valueAt(i, j);

    return sum;
}

Matrix Matrix::operator-(Matrix A)
{
    Matrix diff = Matrix(0.0, row_number, column_number);
    for (unsigned i = 1; i <= row_number; i++)
      for (unsigned j = 1; j <= column_number; j++)
        diff(i, j) = A.valueAt(i, j) + this->valueAt(i, j);
    return diff;

}

Matrix Matrix::operator*(Matrix A)
{
  Matrix mult = Matrix(0.0, row_number, A.get_columns());
    double temp;
    for (unsigned i = 1; i <= row_number; i++) {
      for (unsigned j = 1; j <= A.get_columns(); j++) {
        temp = 0.0;
        for (unsigned k = 1; k <= column_number; k++)
          temp += this->valueAt(i, k) * A(k, j);
        mult(i, j) = temp;
      }
    }

    return mult;
}

Matrix Matrix::transpose() {
  Matrix transpose = Matrix(0.0, row_number, column_number);
  for (unsigned i = 1; i <= row_number; i++) {
    for (unsigned j = 1; j <= column_number; j++) {
      transpose(i, j) = this->valueAt(j, i);
    }
  }
  return transpose;
}

Matrix Matrix::operator+(double x)
{
  Matrix A = Matrix(x, row_number, column_number);
  return *this + A;
}

Matrix Matrix::operator-(double x)
{
  Matrix A = Matrix((-1) * x, row_number, column_number);
  return *this + A;
}

Matrix Matrix::operator*(double x)
{
  Matrix A = Matrix(*this);
  for (unsigned i = 1; i <= row_number; i++)
    for (unsigned j = 1; j <= column_number; j++)
      A(i, j) = this->valueAt(i, j) * x;
  return A;

}

Matrix Matrix::operator/(double x)
{
  if (x != 0) {
    Matrix A = Matrix(*this);
    for (unsigned i = 1; i <= row_number; i++)
      for (unsigned j = 1; j <= column_number; j++)
        A(i, j) = this->valueAt(i, j) / x;
    return A;
  }
  else {} //throw "Dividing by zero";
}

```

```
//"StateSpace.h"

#ifndef _StateSpace_h
#define _StateSpace_h
#include "C:\Users\Wojciech Trybulec\Desktop\Test\Matrix.h"
class StateSpace
{
private:
    Matrix State;
    Matrix A;
    Matrix B;
    Matrix C;
    Matrix D;
    Matrix Out;
public:

    //Constructors + Destructor
    StateSpace();
    StateSpace(Matrix A, Matrix B, Matrix C, Matrix D);
    StateSpace(Matrix A, Matrix B, Matrix C, Matrix D,Matrix InitState);
    StateSpace(const StateSpace&);
    StateSpace operator=(StateSpace);
    ~StateSpace();

    //Comunication Methods
    Matrix get_states() const;
    Matrix get_output() const;
    Matrix* get_all() const;
    void calculate(Matrix Signal);
    void print_states() const;
    void print_output() const;
    void print_matrices() const;

};
#endif

```

```
//"StateSpace.cpp"
#include "C:\Users\Wojciech Trybulec\Desktop\Test\Matrix.h"
#include "StateSpace.h"
StateSpace::StateSpace() {
    A = Matrix();
    B = Matrix();
    C = Matrix();
    D = Matrix();
    State = Matrix();
    Out = Matrix();
}
StateSpace::StateSpace(Matrix A, Matrix B, Matrix C, Matrix D) {
    this->A = A;
    this->B = B;
    this->C = C;
    this->D = D;
    this->State = Matrix(0.0,A.get_columns(),1);
    this->Out = Matrix(0.0, C.get_rows(), 1);
}
StateSpace::StateSpace(Matrix A,Matrix B, Matrix C, Matrix D,Matrix InitState){
    this->A = A;
    this->B = B;
    this->C = C;
    this->D = D;
    this->State = InitState;
    this->Out = Matrix(0.0, C.get_rows(), 1);
}
StateSpace::StateSpace(const StateSpace& ss) {
    this->A = ss.get_all()[0];
    this->B = ss.get_all()[1];
    this->C = ss.get_all()[2];
    this->D = ss.get_all()[3];
    this->State = ss.get_all()[4];
    this->Out = ss.get_all()[5];
}
StateSpace StateSpace::operator=(StateSpace ss) {
    this->A = ss.get_all()[0];
    this->B = ss.get_all()[1];
    this->C = ss.get_all()[2];
    this->D = ss.get_all()[3];
    this->State = ss.get_all()[4];
    this->Out = ss.get_all()[5];
}
StateSpace::~StateSpace() {
    delete this;
    //A.~Matrix;
    //B.~Matrix;
    //C.~Matrix;
    //D.~Matrix;
    //State.~Matrix;
    //Out.~Matrix;
}

Matrix StateSpace::get_states() const {
    return this->State;
}
Matrix StateSpace::get_output() const{
    return this->Out;
}
Matrix* StateSpace::get_all() const {
    Matrix all[6];
    all[0] = A;
    all[1] = B;
    all[2] = C;
    all[3] = D;
    all[4] = State;
    all[5] = Out;
    return all;

}
void StateSpace::calculate(Matrix Signal) {
    State = ((A * State) + (B * Signal));
    Out = ((C * State) + (D * Signal));
}
void StateSpace::print_states() const {
    State.print();
}
void StateSpace::print_output() const {
    Out.print();
}
void StateSpace::print_matrices() const {
    A.print();
    B.print();
    C.print();
    D.print();
}

```

And this Arduino sketch that im using for testing:

```
#include "Matrix.h"
#include "StateSpace.h"
double a[4]={-0.5,0,0,0.7};
double b[2]={1,2};
double c[4]={1,0,0,1};
double d = 0;
Matrix A=Matrix(a,2,2);
Matrix B=Matrix(b,2,1);
Matrix C=Matrix(c,2,2);
Matrix D=Matrix(d,1,1);
Matrix x=Matrix(0.0,2,1);
Matrix U=Matrix(1.0,1,1);
StateSpace ss=StateSpace(A,B,C,D);
void setup()
{
  Serial.begin(9600);
}
void loop() {
  ss.calculate(U);
  x=ss.get_states();
  Serial.print(x.valueAt(1,1));
  Serial.print("\t");
  Serial.println(x.valueAt(2,1));

  delay(100);
}

```

I really hope that you can help me

# Answer
> 0 votes
This is not a solution (meaning to pinpoint the exact problem), but to find out yourself. There are mainly two ways to debug this:

1. On Arduino: Try placing `Serial.print` statements to see where it stops (like putting them on the beginning of every function, or on other 'strategic' places. When you found which function stops, try putting `print` statements within. So within two 'runs' you can find which line is causing the problem. What I normally do is just number the print statements, e.g. function 1 you print values 100..200, next function 200.300 etc. So you can easily leave them for later reusage (just comment them out).
2. Unit test on PC: If you didn't already do, test your class on a PC... this will give you much better debugging tools than an Arduino. When you know the class itself work, create a small test sketch on the Arduino (but high likely it will work, unless you made a mistake in the test sketch). For a PC, consider writing a so-called unit-test ... so even later when you change something, you can test you didn't break anything else.

In both cases (if you start on PC also do this), check for memory usage. The Arduino has only 2 KB SRAM, on a PC you can already check how much is used. The SRAM usage shown during compiling only takes into account global variables. It does not take into account:

* Local variables
* Dynamic variables (made with `new`, `malloc`)
* Stack (passed parameters).

---
Tags: arduino-uno, programming, c++, library
---


# Question
Title: Long term stability of bluetooth connections
I have two Arduino Megas with HC-05 on Serial1 connected to a Raspberry Pi 3b+ via bluetooth, using the HC-05 and the RPi's built-in bluetooth, and python's `pySerialTransfer` library to make the connections.

For reasons I am still trying to root cause, the bluetooth connection gets severed a few times an hour. Ideally, I'd get hours to perhaps a day between severed connections; is this a realistic goal?

Over a course of a few days, my testing has shown:

1. Mega#1 median connection duration is 10 minutes & 88 minute max duration; 25 bytes sent by RPi-\>Arduino, and by Arduino-\>RPi every 0.2sec
2. Mega#2 median connection duration is 38 minutes & 153 minute max duration; 4 bytes sent by RPi-\>Arduino, and by Arduino-\>RPi every 0.2sec

During this testing, they're completely stationary within about 12" of each other, so range should not be an issue.

My RPi code detects a lost connection by virtue of failure to receive a message within 5 seconds, and attempts to reestablish the connection, and that is successful about 80% of the time. I have a second-tier of lost-connection recovery - resetting the HC-05 via an Arduino-triggered MOSFET - if a message isn't received by the Arduino in ~20 seconds, that works in the remainder of the cases, so I'm ultimately able to systematically recover within a max of about 30 seconds. However, this lost connection for ~10-30 seconds every 10-60 minutes causes a poor user experience for my remote controls.

The Python errors given for about 95% of the failures are a lack of a receipt of a heartbeat message from the Arduino to the RPi python; about 5% give a unspecific `[Errno 5] Input/output error` error.

While I'm running down multiple theories via day-long stability tests (longer byte transmissions are more error prone? there's some bug in my Arduino code causing crashes, so remove all logic except the send/receive code to test?), I've read a few posts about how finicky & fragile bluetooth can be, and so I'm curious for some thoughts about the general goal / attempt to get a longer-term (hours to a day or more) connection.

Have folks been able to achieve this with the HC-05 on Arduino? Or is a dropped connection every 10-60 minutes just something one needs to deal with through robust code? Thank you.

# Answer
> 0 votes
I ultimately found a solution, but for the benefit of others, wanted to share the tests that also did not prove fruitful. **TL;DR**: Reducing message rate from Arduino's to RPi solved the problem.

My hypotheses to test:

1. Hypothesis: Faulty Arduino code written by myself. Test: Remove all logic except read / write.
2. Hypothesis: Something to do with message size. Test: Add an extra arbitrary 80 bytes to the Mega#1 message.
3. Hypothesis: Too many small messages for RPi to deal with. Test: Reduce message frequency.
4. Hypothesis: Timing problem or other HC-05 fault as suggested by @stefan-wyss. Test: Swap modules with a 3rd one.
5. Hypothesis: Faulty RPi python code written by myself. Test: Return to basic python test harness that does nothing except exchange bluetooth messages.

Hypotheses #1 & #2 led to no appreciable difference in failure rate or failure mode.

However, hypothesis #3 was the winner, with both Arduinos running for 12+ hours so far with no severed communications. (So I did not bother to test #4 & #5).

Specifically, in the original "problem code", there were 20 messages sent every second (and 40 read attempts; I have "overclocked" the receiving in relation to the sending make sure buffers don't fill up due to slight variations in RPi vs. Arduino clocks):

* 5 sends of 25 bytes by Mega#1 to RPi per second
* 5 sends of 25 bytes by RPi to Mega#1 per second
* 5 sends of 4 bytes by Mega#2 to RPi per second
* 5 sends of 4 bytes by RPi to Mega#2 per second

Some of those didn't really need that frequency to achieve my design goals; so I changed to:

* **1** send of 25 bytes by Mega#1 to RPi **every 2 seconds**
* 5 sends of 25 bytes by RPi to Mega#1 per second
* **1** send of 4 bytes by Mega#2 to RPi **every 2 seconds**
* 5 sends of 4 bytes by RPi to Mega#2 per second

So now, instead of the RPi receiving 10x/second, it receives 1x/second. (It's still *attempting* to read 10x per second on each of the two Arduinos to minimize latency, but most of those return no data received). The RPI still has to send 10x/second (5x to each of the two Arduinos).

This simple change fixed the problem. I have no insight as to why the RPi couldn't handle the faster rate of message receipt; some benchmarking on my Python code showed that processing of the received heartbeat messages was not a bottleneck. But the important part, at least for me & the project, is that the problem is solved.

# Answer
> 0 votes
Bluetooth communication works with fixed time intervals that both communication partners have to agree during the advertising and connection phases. Such an agreement could be: "While connected, lets' meet every second. If one does not show up during 3 meetings, let's leave the connection state".

From this you can see that timing is a very important factor in bluetooth communication. So **both communication partners need a very accurate clock.** No two clocks have exactly the same speed, one is always lagging the other.

It could be that one or multiple of the clocks of your HC-05's do have too much clock drift, so the connection will be lost. Maximum clock deviation allowed for a bluetooth clock is ±40 ppm (i.e. ±40 parts-per-million!) over the entire temperature range.

You could check this theory with multiple HC-05s. If individual modules lead to individual connection lengths, then this could be your problem.

---
Tags: bluetooth, hc-05, raspberrypi
---


title: MAX9611/2 - receiving junk data

text:
# Question
Title: MAX9611/2 - receiving junk data
I'm connecting to a MAX9611 on a custom PCB (using a SAMD Cortex M0 running an Adafruit Feather bootloader) using I2C. I have code that reads the voltage, current and temperature from the internal registers, but I'm receiving junk data from the voltage and current registers. Temperature works reliably.

Sometimes voltage and current are 0. Sometimes voltage is 10x what it should be (that's the raw ADC value - this isn't a conversion bug). The current reading depends on whether the temperature request is commented out or not.

I've been reading through the documentation for a day now and can't see what I'm doing wrong. The kicker is that the code to request the register data is essentially identical (just pointing at different registers) between the working temperature request and the non-working voltage and current requests. I have posted it below, along with the relevant schematic section - does anyone have any ideas what I'm doing wrong?

Thanks!

```
#include <Wire.h>

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

void loop()
{
  Serial.print("mV:   ");  Serial.println(get_MAX9611_voltage());
  Serial.print("mA:   ");  Serial.println(get_MAX9611_current());
  Serial.print("Temp: ");  Serial.println(get_MAX9611_temp());
  Serial.println();
  delay(1000);
}

uint16_t get_MAX9611_voltage (void)
{
  Wire.beginTransmission(0x70);
  Wire.write(0x0A);                             //Select control register 1
  Wire.write(0x03);                             //Set mux to read from RS+
  Wire.endTransmission();

  Wire.beginTransmission(0x70);
  Wire.write(0x02);                             //Select RS+ data register MSB
  Wire.endTransmission();

  Wire.requestFrom(0x70,2);
  uint8_t msb = Wire.read();                    //Read RS+ MSB
  uint8_t lsb = Wire.read();                    //Read RS+ LSB

  uint16_t MAX9611_voltage = word(msb,lsb);
  MAX9611_voltage = MAX9611_voltage >> 4;       //shift right by 4 due to 12 bit value
  MAX9611_voltage = MAX9611_voltage*14;       //57.3V full scale, 14mV per ADC step

  return MAX9611_voltage;
}

uint16_t get_MAX9611_current (void)
{
  Wire.beginTransmission(0x70);
  Wire.write(0x0A);                             //Select control register 1
  Wire.write(0x02);                             //Set mux to read from current sense amplifier with gain 8x, full scale = 55mV
  Wire.endTransmission();

  Wire.beginTransmission(0x70);
  Wire.write(0x00);                             //Select CSA data register MSB
  Wire.endTransmission();

  Wire.requestFrom(0x70,2);
  uint8_t msb = Wire.read();                    //Read CSA MSB
  uint8_t lsb = Wire.read();                    //Read CSA LSB

  uint16_t MAX9611_current = word(msb,lsb);

  MAX9611_current = MAX9611_current >> 4;       //shift right by 4 due to 12 bit value
  MAX9611_current = (MAX9611_current*0.01342)*5;  //ADC value in millivolts, I=V/R where R is 0.2

  return MAX9611_current;
}

int16_t get_MAX9611_temp (void)
{
  Wire.beginTransmission(0x70);
  Wire.write(0x0A);                             //Select control register 1
  Wire.write(0x06);                             //Set mux to read from temp sensor
  Wire.endTransmission();

  Wire.beginTransmission(0x70);
  Wire.write(0x08);                             //Select temp data register MSB
  Wire.endTransmission();

  Wire.requestFrom(0x70,2);
  uint8_t msb = Wire.read();                    //Read temp MSB
  uint8_t lsb = Wire.read();                    //Read temp LSB

  int16_t MAX9611_temp = word(msb,lsb);
  MAX9611_temp = (((MAX9611_temp >> 7) * 480)/1000);                     //shift right by 7 due to 9 bit value, LSB is 480mC

  return MAX9611_temp;
}

```

# Answer
That didn't take long to find the bug... Continuous read mode requires 2ms pause between each ADC read. I'm reading far faster than that, especially considering my micro is far faster than the 8 bit 328s that many other examples use. I added 2ms delay between reads and the problem seems to have disappeared, although I will have to check the current measurements when I have access to better equipment.
> 2 votes

---
Tags: i2c, wire-library
---


title: Trying a crude water level sensor

text:
# Question
Title: Trying a crude water level sensor
first of all, Im from Cuba, that means I may have some problems to find parts...

I have a little system to measure the water level in my house water tank. The system is pretty rough: a proximity sensor HC-SR04 well fixed in the top of the tank, some long wires to an ArduinoNano, and a LCD screen where I display information as: water level in liters and in %.

The problem is the proximity sensor HC-SR04 seems to be broken now, not work at all and I was thinking in replace it by raw cables

Something like in the image below, but maybe with more steps:

So... My questions are:

-Is this posible? I just test it with a glass of water and two short wires and it work, but sometimes it throw me some falses-positives... It may be my code: just light on a led if digitalpin X is high when I put two wires in the water (1 wire to arduino 5V pin and the other to the digitalpin I wanna check if is high), and it do it, but when I pull out the wires the led stay on for more than a few seconds.

-If it is posible, how long can be the wire? Is 10m ok?

Thanks

# Answer
> 1 votes
As others have said, you need to make sure you have pull-up or pull-down resistors on all digital inputs so their value doesn't "float" (fluctuate between high and low.)

Given that water tanks and wells tend to be strongly earth grounded, I would suggest some changes:

Change the common wire to a ground, not +5V

Change all of your other pins to analog inputs. Connect them to high ohm pull-up resistors (say 10kΩ). They will read a full 5V when their ends are not in water. When the water rises and the ends dip into the water, their voltages will drop. Use analog readings to detect those voltage drops.

You could also use something like graphite a pair of graphite rods in the water, and a voltage divider circuit. As the water level rises, the current would travel through less graphite, and the resistance would drop. I don't know if that would give you enough top-to-bottom measuring distance.

---
Tags: arduino-nano, hc-sr04
---


title: Arduino Due SPI clock pauses each octet

text:
# Question
Title: Arduino Due SPI clock pauses each octet
I'm trying to communicate with SPI slave using Arduino DUE as master. Device requires commands to be 32 bit wide, SPI mode 3.

I've ran the minimum code (using Arduino IDE 1.8.12) to send some 32 bit wide nonsense, and I've noticed that clock stops for a while after each octet is sent. Also the pause after CS goes LOW is too long.

What is the best practice to achieve a clean 32 bit wide transmission?

```
#include <SPI.h>

const int cs_pin = 25;
const SPISettings spi_settings(2000000, MSBFIRST, SPI_MODE3);
uint8_t tx_buffer[4];

void setup() {
  pinMode(cs_pin, OUTPUT);
  SPI.begin();
}

void loop() {
  tx_buffer[0] = 0xDE;
  tx_buffer[1] = 0xAD;
  tx_buffer[2] = 0xBE;
  tx_buffer[3] = 0xEF;

  SPI.beginTransaction(spi_settings);
  digitalWrite(cs_pin, LOW);
  SPI.transfer(tx_buffer, 4);
  digitalWrite(cs_pin, HIGH);
  SPI.endTransaction();
}

```
* SCLK - CH1 (Yellow)
* CS - CH3 (Purple)
* MOSI - CH4 (Blue)

Expected signal:

# Answer
SPI is synchronous. That means that within certain constraints the timing and the width of any part of the signal is irrelevant.

What makes you think that it's bad to have a slight variance in the timing, or that the "pause after CS goes LOW!" is "too low"?

If you think it's from the timing diagrams, those times are *minimum* times (generally) and all things happen at either the rising or falling edge of the clock (depending on the SPI mode).
> 1 votes

---
Tags: arduino-due, spi
---


# Question
Title: Arduino IDE Serial Monitor - how to send NUMBERs - not charcters of numbers
Serial link send and recieves Bytes. Serial monitor at Arduino IDE reads it's input as character.

So if I type '0' in serial monitor, then FW will read byte 48 - I don't want to implement some silly translation from character value to int - I want to input NUMBER as byte into serial monitor - how do I do that?

```
byte inByte = Serial.read(); // read the incoming byte
if(inByte == 1) // do stuff

```

# Answer
Based on comments under question no one seems to really know the answer.

So the short answer is: **IT'S IMPOSSIBLE** \- to use Arduino IDE serial monitor to send raw data.

@Edgar\_Bonet submitted hint for linux users

@jsotola suggested to use PuTTY, but no additional info on how to do that. Short glance at settings and I couldn't find the way to achieve raw input.

After some additional googling i found some reading where I found program called RealTerm which does the job.

Simply setup your port on *Port* card and then hit *Change* button.

On card *Display* change *Display As* From ASCII to your prefered format, such as Hex(space)

Then swich on card Send - type your number into input box left to button *Send Numbers* and press that button

Thats all

The input box accepts decimal value from 0 to 255, or a hexadecimal value, which are prefixed with either a "0x" or a '$'. Each value is separated by space.

Following line is correctly accepted: "255 0xff 0xFF $ff $FF"

Yet another useful tool is Serial Port Monitor. With this you can observe what is really transmitted on line without relying on the interpretation of you application.

Usage is really simple: click white file icon, or Session \> New session or press Ctrl+N

Choose port and vizualizer and click Start monitoring... that's it.

I found most useful mode "Dump view"
> 1 votes

# Answer
I think the comments on your question are quite clear. The important point: any asynchronuous protocoll *must* include the info either *how many* bytes are transmitted or which byte is *the last one*. In "raw data", where each value (0-255) can be a legit data value, there is no way to use bytes for meta data. That's why typically only encoded data is transmitted: you have a small range of byte values that can contain the actual info (alphabet and digits) and you have a bunch of values that are free to be used as meta data. E.g. the commonly used `\n` as endbyte has the int value 10. How would you transmit the int value 10 in that case?

"I don't want to implement some silly translation from character value to int" - it's not silly, that's the way to go! What about float, boolean or negative values (8-bit, 16-bit, etc.)? You may even want to transmit structured data like python dictionaries. The only way the achieve this is using some kind of parser which knows the protocol.
> 2 votes

---
Tags: serial, ide
---


# Question
Title: Can I use string and int in Serial.println together?
I just yesterday started programming on Arduino, and I have a little problem.

I want to print `"#S|SKAITYMAS|[1]#"` in one line, except instead of `"1"` I would like to use an int value. However, this one doesn't work:

`Serial.println ("#S|SKAITYMAS|[",LINENR,"]#");`

Any hint or tips would be appreciated.

# Answer
Do something like this:

Start with your string and integer:

```
String string = "PI is equal to ";
int integer   = 3.1416;

```

Then put this in your loop:

```
Serial.print(string);  //string here
Serial.print(integer); //int here

Serial.println();      //change line

```

Serial.print() doesn't change line. Its Serial.println() which is the print that changes line so everything that is printed without println will be on the same line.
> 3 votes

# Answer
The answer by canadiancyborg is fine. However, it is always better to avoid using String objects if at all possible, because they use dynamic memory allocation, which carries some risk of memory fragmentation. Simple and safe:

```
int answer = 42;
Serial.print("The answer is ");
Serial.println(answer);

```

The only drawback is that the constant string ("The answer is ") takes some RAM. This can be avoided by embedding it in the `F()` macro, which means “keep this in Flash memory only”. Then, the most memory-friendly idiom is:

```
int answer = 42;
Serial.print(F("The answer is "));
Serial.println(answer);

```
> 4 votes

# Answer
It can be done the **C way**:

`sprintf()` can be used to generate a formatted string, and then `Serial.println()` to send the string

```
char buf[32];
sprintf(buf, "#S|SKAITYMAS|[%d]#", LINENR);
Serial.println(buf);

```

or with **String class** as explained here:

https://www.arduino.cc/en/Tutorial/StringAdditionOperator

```
  String str = "#S|SKAITYMAS|["
  str += LINENR;
  str += "]#";
  Serial.println(str);

```

**Do not do everything in just one line, as explained on the page link above.**
> -1 votes

---
Tags: arduino-uno, serial
---


title: About ATTINY85 Development Board

text:
# Question
Title: About ATTINY85 Development Board
I am thinking to buy one of "ATTINY85 Development Board"...

Before buying I was checking details/Advantages of it.

**First I thought this is just a breakout board & USB for power.**

**But, then found It can be programmed with "Digispark driver & board manager" directly by the USB.**

---

I checked this Question: EBay “Development Programmer Board for ATtiny”

Someone said there:

> "While limited, this type of board can be useful for "blink an LED on USB command" type tasks"

---

My Main question is:

**Is it really programmable withut any TTL/ICSP/FTDI extention?**

**If so, is it possible to program other AVR chip (Attiny/Atmega) with simple codes directly via USB...?**

**(with same method)**

# Answer
> 1 votes
> Is it really programmable withut any TTL/ICSP/FTDI extention?

Only if you use an ATTiny chip that has the "Micronucleus" bootloader already installed.

> If so, is it possible to program other AVR chip (Attiny/Atmega) with simple codes directly via USB...?

Some can, but most need a bootloader installing. The ATMega32U4, for example, has a "DFU" mode, which is essentially a bootloader in ROM, that you can use directly over USB. In general, though, the answer is "Not without installing an appropriate bootloader with some hardware programmer first".

---
Tags: programming, usb, attiny85
---


# Question
Title: How does the motor shield determines how much voltage to supply to a motor?
Can i connect 6v DC motor and 12v DC motor, or 6v DC and 12V stepper to adafruit motor shield v1, and an external 12v power supply? also, how does it determine how much voltage needs to be supplied to a motor? is it done by code, when we set the speed of the motor, or the frequency?

do i have to take care of how much voltage i am supplying to the motor shield?

# Answer
> Can i connect 6v DC motor and 12v DC motor to adafruit motor shield v1, and an external 12v power supply?

No.

> how does it determine how much voltage needs to be supplied to a motor?

It doesn't. It supplies whatever voltage you supply through the power input.

You must match the power supply to the motor. The motor shield is merely a switch that turns the power on and off in the right way to change the speed and direction of the motor.
> 1 votes

---
Tags: arduino-motor-shield
---


# Question
Title: How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno)
I have an arduino mega with a LCD shield (from keyestudio KS2056). I am trying to create a menu with a submenu that would have addable and removable strings based on inputs from a RFID scanner(addable) and buttons(to remove selected strings). I am not so sure how I could possibly do this. Any assistance would be great.

# Answer
I will skip the RFID part, that is unrelated to the menu.

What you can do is creating two variables:

```
int menuLevel1 = 0;
int menuLevel2 = 0;

```

Assuming you have 2 levels, if you have more levels consider an array.

Now you can print the screen based on the values of these two variables (use a `switch` statement for menuLevel1 which calls new functions, each with their own `switch` statement for menuLevel2.

Note there are more solutions, but this is a rather simple solution.

The RFID scanner just changes the values, so going to a different menu screen.

A slightly different solution is to not use numbers, but an enumeration (or one for the main level, and x for the second level etc). This can add up, so you can also use a single enum value (with one entry per possible menu page).

The last example looks like:

```
enum EMenuPage
{
   StartPage,
   MainMenu,
   FirstMenu,
   DisplayX,
   SetY,
   …
}

enum EMenuPage _menuPage;

```

Displaying like:

```
switch (_menuPage)
{
case StartPage:
   // Fill LCD with start page
   break;

case …

```

And when an RFID messages comes in:

```
if (RFID... == Back)
{
  _menuPage = MainMenu;
}
else …

```
> 1 votes

# Answer
\[State machines\]\[1\]. it's the general form of the solution provided by michael above. it's a big help on situations when the application have to answer to, or act on many states (e.g. a menu). the good part is you can `draw them on a piece of paper` , draw a graph, manage input/output and write a general routine to act in various states. the state names themsevles can be represented by an integer variable and represented better by enumeration. after that, there should be a routine to act based on the current state, and the input from current state to go to another state. in it's easiest form, it's just a `if-else` block. depsite the idea is the same as the bare variable solution provided in the other answers, ignoring state machine related techniques (e.g. just drawing state graphs down on a piece of paper) makes a big application unmanageable.
> 0 votes

---
Tags: arduino-uno, arduino-mega, programming, lcd, rfid
---


# Question
Title: Why do ESP boards break out the SPI flash pins?
I have an ESP32 development board and a NodeMCU board here. Both breaking out the pins for the SPI flash of the ESP. These pins are mentioned in standard pinout descriptions as must/should not connect. This pinout description states, that they

> are not recommended for other uses. So, don’t use these pins in your projects

The answer to this question suggests, that you can somehow connect other SPI devices to the same bus as the SPI flash. The linked documentation from that answer states, that in that case you cannot control the chip select for the additional SPI device via a digital pin, but have to let the "hardware arbiter" (whatever that is) decide, when to connect to the additional SPI device.

That is the only use of these pins, that I could find, and even this seems pretty niche. It doesn't seem to be a standard way of usage for the pins and also rather difficult.

**Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?**

Maybe there is another use of the pins or I just underestimate the importance of adding additional SPI devices to the bus.

# Answer
> Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?

The ESP32 is not designed specifically for Arduino. There are other boot modes, such as SD card boot, whereby the internal flash is not directly used. In this situation you are free to use those pins as you wish (given that there is a flash chip attached to them).

The "ESP32 Development Board" was not primarily designed for Arduino. Instead it's a generic board designed by Espressif (and copied many times), and is usable with the Arduino core as one of many options.

In short: the pins aren't there for Arduino users, they're there for other users.

---

Addendum:

The SPI flash pins can also be used for (and are most commonly used for):

* Adding more SPI flash chips which then get integrated into the normal memory space and with the internal caching system, and
* Adding PSRAM to increase the RAM memory space.

A good example of the latter is the ESP32-CAM which has an SPI-connected PSRAM chip for framebuffering and image analysis connected to the SPI pins.

You can think of them not so much as SPI pins but as the EBI pins of the PIC32MZ or the EMB of the ATMega2560, etc. Used for expanding the memory rather than for adding random peripherals.
> 3 votes

---
Tags: nodemcu, pins, esp32
---


title: RGB LEd and a push button in TinkerCAD

text:
# Question
Title: RGB LEd and a push button in TinkerCAD
I'm working on TinkerCAD, I want to design and simulate a circuit in which there are following components. 1. 1 RGB LED 2. 1 Push button 3. 3 Photo-resistors. 4. 1 Arduino board. So the light should be off at the starting. When the push button is pressed for the first ever time, the LED should light up as red, and then the brightness of the red color should be able to controlled by one of the three photo-resistors used, the second time when the push-button is pressed the LED should light up as green and green color this time should be controlled by another photo-resistor..when the button is pressed for the third time , the LED should now change to blue color and the third photo-resistor should be able to control the brightness of the blue color. And this cycle should go on, upon pressing the Push button.

please tell me what's wrong.

Code looks like this

```
int button_state = 0;//declaring a variable
int counter;//declaring another variable,will keep count of which color to be lighted
const int pRed = A2; //assigning pin A2 as pRed
const int pBlue = A1; //.............A1....pBlue
const int pGreen = A0; //............A0.....pGreen
int inputRed;//adjusted value of led brightness will be stored
int inputGreen;
int inputBlue;
const int ledRed = 9;
const int ledGreen = 11;
const int ledBlue = 10;

void setup()
{
  pinMode(2,INPUT);
  pinMode(ledRed,OUTPUT);
  pinMode(ledGreen,OUTPUT);
  pinMode(ledBlue,OUTPUT);
  pinMode(pRed,INPUT);
  pinMode(pGreen,INPUT);
  pinMode(pBlue,INPUT);
}

void loop()
{
  button_state = digitalRead(2);// reading the button state
  inputRed = analogRead(pRed);// Reading the value from A2 pin
  inputRed = map(inputRed,0,1023,0,255);//value from A2 pin adjusted for led's brightness
  if (button_state == HIGH) {
    counter = 0; // Declaring counter as 0 again
    analogWrite(ledRed,inputRed);
    analogWrite(ledGreen, 0);
    analogWrite(ledBlue, 0);
    delay(10);// Wait for 10 millisecond(s)
    green();// Jumping to green
  }
}
void green()
{
  while (counter == 0){//counter was declared 0 in loop function,so the code won't go ahead till it's 0 only
  button_state = digitalRead(2);//for reading the button state once again
  inputGreen = analogRead(pGreen);//reading the signal from A0 as it is the inputpin for photoresistor for green light
  inputGreen = map(inputGreen,0,1023,0,255);  //value from A0 pin mapped
  if (button_state == HIGH) {
    counter++; // Increasing counter by 1 so that it becomes 1 now.
    analogWrite(ledRed,0);
    analogWrite(ledGreen,inputGreen);
    analogWrite(ledBlue,0);
    delay(10);//wait for 10 millisecond(s)
    blue(); //jumping to function for blue led now
  }
}
}
void blue()
{
  while (counter == 1)//using while, so that the code won't go ahead if counter=1,as made in function for green light
  {
  button_state = digitalRead(2);
  inputBlue = analogRead(pBlue);//reading value from A1 pin
  inputBlue = map(inputBlue,0,1023,0,255);//value from A1 pin mapped
  if (button_state == HIGH) {//
    counter++;
    analogWrite(ledRed,0);
    analogWrite(ledGreen,0);
    analogWrite(ledBlue,inputBlue);
    delay(10);//wait for 10 millisecond(s)
  }
  }
}

```

# Answer
> please tell me what's wrong.

I'm sorry to say, but pretty much everything. You need to rethink your program flow from the ground up.

Separate out the button from the LED actions. The button should only control the counter. The counter then makes the decision what to do with the LEDs.

Also you have to learn about the concept of *change* with the button. You don't want to be doing something if the button is high, since that will be being done all the time the button is pressed. Instead you need to learn how to do something only at the moment the button changes from low to high.

As a rough outline to how your program could look, here's a pseudo-listing:

* Set the counter to 0
* If the button changes from LOW to HIGH
    + Increment the counter
* If the counter is greater than 3
    + Set the counter to 1

That would give you a sequence of 0-1-2-3-1-2-3-1-2-3 for the counter as you press the button.

Next you have a separate section in your loop to deal with what the counter is.

* If the counter is 0
    + Turn off all LEDs
* If the counter is 1
    + Control the red LED and turn off the others
* If the counter is 2
    + Control the green LED and turn off the others
* If the counter is 3
    + Control the blue LED and turn off the others

If you implement that properly you will have created a *finite state machine*.
> 1 votes

# Answer
Your code might look something like this

```
#define debounceTime 50   //Tweak this value to adjust amount of debouncing
unsigned long lastButtonMillis = 0;
uInt8 switchState = 0;
uInt8 oldButtonState = LOW;

void setup() {
   //Your setup code
}

void handleSwitchChange(uInt8 switchState) {
   switch switchState {
      case 0:
         //code for red
         break;

      case 1:
         //code for green
         break;

      case 1:
         //code for blue
         break;

   }
}

void loop() {
    //If enough time has elapsed, check for button presses
    if (millis() - lastButtonMillis >= debounceTime) {
        lastButtonMillis = millis();
        if (oldButtonState == LOW && digitalRead(switchPin) == HIGH) {
            oldButtonState = HIGH;
            switchState = (switchState + 1) % 3; //value will cycle 0,1,2,0,1,2
            handleSwitchChange(switchState);
        }
    } else {
        oldButtonState = digitalRead(switchPin);
    }
}

```
> 0 votes

---
Tags: arduino-uno, rgb-led
---


# Question
Title: ESP32 Cannot assign value to string. Getting wrong value
*Hello* I have problems with strings in my sketch. I assingn values to my string (for example tempStrReturn) in the functions setNr1, setNr2. If i pass the value 1 to the function i get "" or "application/x-www-form-urlencoded" when there should be 1. I don't understand why this is happening.

**If you see the output printout from the function setNr1 i get "" then after assigning the value (nr1+"") to the tempStrReturn i still get "". After i use the tempStrReturn in the setNr2 function it asigns a mishmash value to it.**

*I dont use the tempStrReturn, she is just there for showing the error. When i change the int values of nr1 or nr2 that i want to assign to the string, the value mishmash in the strings changes. With the same numbers the string value has always the same mishmash.*

*OUTPUT:*

```
192.168.43.140
Function setNR1............
Got: 0
NR1 int: 0
tempStrReturn before:
tempStrReturn after:
Function setNR2............
Got: 1
NR2 int: 1
tempStrReturn before:
tempStrReturn after: application/x-www-form-urlencoded
Function setID...........
String id: ID
Set msgId to: 0
Set msgPos to: 1
Function setNR1............
Got: 1
NR1 int: 1
tempStrReturn before: ID
tempStrReturn after: application/x-www-form-urlencoded
Function setNR2............
Got: 1
NR2 int: 1
tempStrReturn before: application/x-www-form-urlencoded
tempStrReturn after: application/x-www-form-urlencoded
Function setH...........
nr1: 1
nr2: 1
Created value: 11
Original value in string: 0
nrX: 0 nrPos: 1 Value i want to enter: n/x-www-form-urlencoded
Value afther assignment: n/x-www-form-urlencoded

```

*MY CODE:*

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <Wire.h>

const char* ssid = "Ti";
const char* password = "1234567891234";
// Stores LED state
String ledState;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

#define ledPin 2  //BuiltInLed is inverted
#define countMax 2500
#define multiplyMax 100
int count = 0, multiply = 0, msgDel = 0;
int nr1=0, nr2=0,msgPos, msgId, msgVar;
String inOut[10][10];
String tempStr1, tempStr2, tempStrReturn;
bool oneShot = false;

//***************************************

/*Set value of String[] on the nrPos to val*/
void inOutSet(int nrX, int nrPos, String val)
{
  Serial.print("Original value in string: "); Serial.println(inOut[nrX][nrPos]);
  Serial.print("nrX: ");Serial.print(nrX);Serial.print(" nrPos: ");Serial.print(nrPos);
  Serial.print(" Value i want to enter: "); Serial.println(val);
  inOut[nrX][nrPos] = val;
  Serial.print("Value afther assignment: ");Serial.println(inOut[nrX][nrPos]);
}

String inOutGet(int nrX, int nrPos)
{
  return inOut[nrX][nrPos];
}

String dataRequest(int roomNr)
{
  tempStrReturn = "";
  Serial.println("Preparing to send data as word...");
  Serial.print("Value in TempStringReturn before: "); Serial.println(tempStrReturn);
  tempStrReturn = "g" + roomNr;
  tempStrReturn = tempStrReturn+".";
  Serial.print("Adding g and . : "); Serial.println(tempStrReturn);
  nr1 = 0; nr2 = 0;

  for (int i = 0; i < 9; i++)
  {
    Serial.print("Data Request: "); Serial.println(msgId);
    tempStrReturn = tempStrReturn+inOut[roomNr][i];
    Serial.print("Ading value from inOut: "); Serial.println(tempStrReturn);
  }
  Serial.print("Returning value: ");
  Serial.println(tempStrReturn);

  return tempStrReturn;
}

//saves value to nr1 as int
String setNr1(String var)
{
  Serial.println("Function setNR1............");
  Serial.print("Got: "); Serial.println(var);
  nr1 = var.toInt();
  Serial.print("NR1 int: "); Serial.println(nr1);
  Serial.print("tempStrReturn before: "); Serial.println(tempStrReturn);
  tempStrReturn = nr1+"";
  Serial.print("tempStrReturn after: "); Serial.println(tempStrReturn);
  return nr1+"";
}

//saves value to nr2 as int
String setNr2(String var)
{
  Serial.println("Function setNR2............");
  Serial.print("Got: "); Serial.println(var);
  nr2 = var.toInt();
  Serial.print("NR2 int: "); Serial.println(nr2);
  Serial.print("tempStrReturn before: "); Serial.println(tempStrReturn);
  tempStrReturn = nr2+"";
  Serial.print("tempStrReturn after: "); Serial.println(tempStrReturn);
  return nr2+"";
}

//Creates values for the array
String setID()
{
  Serial.println("Function setID...........");
  msgId = nr1;
  msgPos = nr2;
  nr1 = 0; nr2 = 0;
  tempStrReturn = "ID";
  Serial.print("String id: "); Serial.println(tempStrReturn);
  Serial.print("Set msgId to: "); Serial.println(msgId);
  Serial.print("Set msgPos to: "); Serial.println(msgPos);
  return "ID";
}

//Creates value from nr1 and nr2
String setH()
{
  Serial.println("Function setH...........");
  msgVar = (nr1*10)+nr2;
  Serial.print("nr1: "); Serial.println(nr1);
  Serial.print("nr2: "); Serial.println(nr2);
  nr1 = 0; nr2 = 0;
  if (msgVar >= 99)  {  msgVar = 100;  }
  Serial.print("Created value: "); Serial.println(msgVar);
  inOutSet(msgId, msgPos, msgVar+"");
  return "H";
}

String getIO()
{
  nr1 = nr1/10;
  return dataRequest(nr1);
}

String processor(const String& var){
  Serial.print("Processor in: ");  Serial.println(var);
  return var;
}

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600);

  //Filling the inOut array
  for (int i = 0; i < 10; i++)
  {
    for (int x = 0; x < 10; x++)
    {
      inOut[i][x]= "0";
    }

  }

  if(!SPIFFS.begin()){Serial.println("\nSPIFFS chyba!"); return;}

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", String(), false, processor);//change
  });

  //route to favicon
  server.on("favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/favicon.png", "image/png");
  });

  // Route to load style.css file
  server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/style.css", "text/css");
  });

  // Route to javascript
  server.on("/main.js", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/main.js", "text/javascript");
  });

// Nr1 of the msg
  server.on("/0", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("0").c_str());
  });
  server.on("/1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("1").c_str());
  });
  server.on("/2", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("2").c_str());
  });
  server.on("/3", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("3").c_str());
  });
  server.on("/4", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("4").c_str());
  });
  server.on("/5", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("5").c_str());
  });
  server.on("/6", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("6").c_str());
  });
  server.on("/7", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("7").c_str());
  });
  server.on("/8", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("8").c_str());
  });
  server.on("/9", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("9").c_str());
  });
// Nr2 of the msg
  server.on("/X0", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X0").c_str());
  });
  server.on("/X1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X1").c_str());
  });
  server.on("/X2", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X2").c_str());
  });
  server.on("/X3", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X3").c_str());
  });
  server.on("/X4", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X4").c_str());
  });
  server.on("/X5", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X5").c_str());
  });
  server.on("/X6", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X6").c_str());
  });
  server.on("/X7", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X7").c_str());
  });
  server.on("/X8", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X8").c_str());
  });
  server.on("/X9", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X9").c_str());
  });
//end commands for use the nr values
  server.on("/ID", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setID().c_str());//Set ID nr
  });
  server.on("/H", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setH().c_str());//Set value to id
  });
  server.on("/G", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", getIO().c_str());//Get value
  });

  // Start server
  server.begin();
}

/*-------------LOOP---------------*/
void loop() {
  count++;
  if (count > countMax)  {    multiply++; count = 0;  }
  if (multiply > multiplyMax)
  {
    if (!oneShot)
    {
      setNr1("0");
      setNr2("1");
      setID();
      setNr1("1");
      setNr2("1");
      setH();
      oneShot = true;
    }

    if (nr1 != 0 || nr2 != 0)
    {
      msgDel++;
      if (msgDel > 5)
      {
        nr1 = 0; nr2 = 0;
        Serial.println("DELETING...");
        msgDel = 0;
      }

    }

    //delay(60000);
    multiply = 0;
  }
}

```

# Answer
`nr1+""` is *not* how you convert an integer to a String. All you are doing there is taking the value of `nr1` and adding it to the address of a string constant that consists of just a `\0`. Then assigning that to a String.

The results of such an operation are undefined.

Instead you should go:

```
tempStrReturn = String(nr1);

```

which will create a new `String` object, populate it with the text representation of the value of `nr1` then copy that content into the `tempStrReturn` String.

However I would recommend avoiding using `String`, even on a chip as capable as the ESP32. Instead use C strings (NULL terminated character arrays) which are far less wasteful of resources.
> 1 votes

---
Tags: esp32, string, web-server
---


# Question
Title: Programatic FOTA (Firmware-Over-The-Air) upgrades with Uno R3
I have been searching for a way to upgrade the sketch on my Arduino Uno wirelessly (preferable WiFi, but not a must). Does the Uno support such function? If not - are there any other boards that might support it?

Also, to further extend on the problem - I wouldn't want to upload a new sketch through the Arduino IDE but rather do it programmatically (trying to integrate it with a version management system of my own).

# Answer
> 4 votes
There's two ways you can go about this - hardware and software.

To do it in software would mean writing a new bootloader that supported whatever wireless medium you chose. The bootloader might end up quite large and thus restrict the size of sketch you are able to support. It may also require advanced programming techniques in order to fit it into memory. Not a task for a beginner.

Doing it in hardware is easier but more restrictive. You need a wireless medium that can emulate a serial device *including the ability to perform a reset of the Arduino*. There are bluetooth interfaces for the Arduino that can perform this kind of functionality, but I am not aware of anything WiFi or Ethernet that even remotely comes close.

There are Arduino boards available with this kind of bluetooth interface built in.

A possible third option is something in between - you have two Arduinos (or some other external MCU based system, like an ATTiny for instance), the "target" and the "programmer". The "programmer" is what is connected to the wireless and accepts instructions and commands over the air. It is then capable of putting the "target" into bootloader mode (reset it) and pass data through to its serial port for programming. It does mean the "target" isn't directly connected to the wireless though, so it is up to the "programmer" to support whatever wireless functionality is needed and communicate properly with the "target" to get it to do everything it should. There is no way to do FOTA to the "programmer" though, so you're back at square one if you want to reprogram that...

# Answer
> 3 votes
There are plenty of examples of Arduinos being used to reprogram Arduinos:

So the obvious choice here is to have **two** chips. One does the real work, the other one programs the first one, when required.

The "programmer" chip could be written to read from a disk file, accept data over Ethernet, WiFi or whatever. And it could be programmed to reprogram the target chip at a certain time of day, or on command.

In this system the "main" chip gets on with whatever-it-is it is doing, and the "programmer" chip just monitors its source of new code.

> Does the Uno support such function? If not - are there any other boards that might support it?

I don't know of any boards that directly support that. These boards are generally built as educational tools, not as ready to deploy in the field as robust auto-upgrading devices. For one thing, keeping things cheap enough for students to purchase, perhaps one for each student in a classroom of 30, was one of the design criteria.

# Answer
> 0 votes
You can wire an ESP32-based board or module to your Arduino, and use https://vcon.io for a remote OTA. vcon firmware can act as an AVR (and not just AVR) programmer, and reflash your Arduino remotely.

Also, as a side-effect, you'll get remote control capability for your Arduino. https://dash.vcon.io cloud service gives you device dashboard and an API for remote control and OTA.

Disclaimer: I do represent https://vcon.io product.

---
Tags: arduino-uno, bluetooth, wifi, firmware
---