# Question
Title: I am not able to set the correct configuration of sound module
I have been trying to make sound reactive LED lights but my sound module is detecting only very close voice the LED react only when I press it to the speaker with my hands I have tried to set the potentiometer many times but I got unsuccessful I have connected the Analogue output to Arduino.

The voice module I used:

I have used the following code-

```
#include <FastLED.h>

/** BASIC CONFIGURATION  **/

//The amount of LEDs in the setup
#define NUM_LEDS 10
//The pin that controls the LEDs
#define LED_PIN 6
//The pin that we read sensor values form
#define ANALOG_READ 0

//Confirmed microphone low value, and max value
#define MIC_LOW 0.0
#define MIC_HIGH 737.0
/** Other macros */
//How many previous sensor values effects the operating average?
#define AVGLEN 15
//How many previous sensor values decides if we are on a peak/HIGH (e.g. in a song)
#define LONG_SECTOR 5

//Mneumonics
#define HIGH  3
#define NORMAL 2

//How long do we keep the "current average" sound, before restarting the measuring
#define MSECS 2000
#define CYCLES MSECS / DELAY

/*Sometimes readings are wrong or strange. How much is a reading allowed
to deviate from the average to not be discarded? **/
#define DEV_THRESH 0.8

//Arduino loop delay
#define DELAY 1

float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve);
void insert(int val, int *avgs, int len);
int compute_average(int *avgs, int len);
void visualize_music();

//How many LEDs to we display
int curshow = NUM_LEDS;

/*Not really used yet. Thought to be able to switch between sound reactive
mode, and general gradient pulsing/static color*/
int mode = 0;

//Showing different colors based on the mode.
int songmode = NORMAL;

//Average sound measurement the last CYCLES
unsigned long song_avg;

//The amount of iterations since the song_avg was reset
int iter = 0;

//The speed the LEDs fade to black if not relit
float fade_scale = 1.2;

//Led array
CRGB leds[NUM_LEDS];

/*Short sound avg used to "normalize" the input values.
We use the short average instead of using the sensor input directly */
int avgs[AVGLEN] = {-1};

//Longer sound avg
int long_avg[LONG_SECTOR] = {-1};

//Keeping track how often, and how long times we hit a certain mode
struct time_keeping {
  unsigned long times_start;
  short times;
};

//How much to increment or decrement each color every cycle
struct color {
  int r;
  int g;
  int b;
};

struct time_keeping high;
struct color Color;

void setup() {
  Serial.begin(9600);
  //Set all lights to make sure all are working as expected
  FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
  for (int i = 0; i < NUM_LEDS; i++)
    leds[i] = CRGB(0, 0, 255);
  FastLED.show();
  delay(1000);

  //bootstrap average with some low values
  for (int i = 0; i < AVGLEN; i++) {
    insert(250, avgs, AVGLEN);
  }

  //Initial values
  high.times = 0;
  high.times_start = millis();
  Color.r = 0;
  Color.g = 0;
  Color.b = 1;
}

/*With this we can change the mode if we want to implement a general
lamp feature, with for instance general pulsing. Maybe if the
sound is low for a while? */
void loop() {
  switch(mode) {
    case 0:
      visualize_music();
      break;
    default:
      break;
  }
    delay(DELAY);       // delay in between reads for stability
}

/**Funtion to check if the lamp should either enter a HIGH mode,
or revert to NORMAL if already in HIGH. If the sensors report values
that are higher than 1.1 times the average values, and this has happened
more than 30 times the last few milliseconds, it will enter HIGH mode.
TODO: Not very well written, remove hardcoded values, and make it more
reusable and configurable.  */
void check_high(int avg) {
  if (avg > (song_avg/iter * 1.1))  {
    if (high.times != 0) {
      if (millis() - high.times_start > 200.0) {
        high.times = 0;
        songmode = NORMAL;
      } else {
        high.times_start = millis();
        high.times++;
      }
    } else {
      high.times++;
      high.times_start = millis();

    }
  }
  if (high.times > 30 && millis() - high.times_start < 50.0)
    songmode = HIGH;
  else if (millis() - high.times_start > 200) {
    high.times = 0;
    songmode = NORMAL;
  }
}

//Main function for visualizing the sounds in the lamp
void visualize_music() {
  int sensor_value, mapped, avg, longavg;

  //Actual sensor value
  sensor_value = analogRead(ANALOG_READ);

  //If 0, discard immediately. Probably not right and save CPU.
  if (sensor_value == 0)
    return;

  //Discard readings that deviates too much from the past avg.
  mapped = (float)fscale(MIC_LOW, MIC_HIGH, MIC_LOW, (float)MIC_HIGH, (float)sensor_value, 2.0);
  avg = compute_average(avgs, AVGLEN);

  if (((avg - mapped) > avg*DEV_THRESH)) //|| ((avg - mapped) < -avg*DEV_THRESH))
    return;

  //Insert new avg. values
  insert(mapped, avgs, AVGLEN);
  insert(avg, long_avg, LONG_SECTOR);

  //Compute the "song average" sensor value
  song_avg += avg;
  iter++;
  if (iter > CYCLES) {
    song_avg = song_avg / iter;
    iter = 1;
  }

  longavg = compute_average(long_avg, LONG_SECTOR);

  //Check if we enter HIGH mode
  check_high(longavg);

  if (songmode == HIGH) {
    fade_scale = 3;
    Color.r =  8;
    Color.g = 1;
    Color.b = -2;
  }
  else if (songmode == NORMAL) {
    fade_scale = 3;
    Color.r = -1;
    Color.b = 6;
    Color.g = -2;
  }

  //Decides how many of the LEDs will be lit
  curshow = fscale(MIC_LOW, MIC_HIGH, 0.0, (float)NUM_LEDS, (float)avg, -1);

  /*Set the different leds. Control for too high and too low values.
          Fun thing to try: Dont account for overflow in one direction,
    some interesting light effects appear! */
  for (int i = 0; i < NUM_LEDS; i++)
    //The leds we want to show
    if (i < curshow) {
      if (leds[i].r + Color.r > 255)
        leds[i].r = 255;
      else if (leds[i].r + Color.r < 0)
        leds[i].r = 0;
      else
        leds[i].r = leds[i].r + Color.r;

      if (leds[i].g + Color.g > 255)
        leds[i].g = 255;
      else if (leds[i].g + Color.g < 0)
        leds[i].g = 0;
      else
        leds[i].g = leds[i].g + Color.g;

      if (leds[i].b + Color.b > 255)
        leds[i].b = 255;
      else if (leds[i].b + Color.b < 0)
        leds[i].b = 0;
      else
        leds[i].b = leds[i].b + Color.b;

    //All the other LEDs begin their fading journey to eventual total darkness
    } else {
      leds[i] = CRGB(leds[i].r/fade_scale, leds[i].g/fade_scale, leds[i].b/fade_scale);
    }
  FastLED.show();
}
//Compute average of a int array, given the starting pointer and the length
int compute_average(int *avgs, int len) {
  int sum = 0;
  for (int i = 0; i < len; i++)
    sum += avgs[i];

  return (int)(sum / len);

}

//Insert a value into an array, and shift it down removing
//the first value if array already full
void insert(int val, int *avgs, int len) {
  for (int i = 0; i < len; i++) {
    if (avgs[i] == -1) {
      avgs[i] = val;
      return;
    }
  }

  for (int i = 1; i < len; i++) {
    avgs[i - 1] = avgs[i];
  }
  avgs[len - 1] = val;
}

//Function imported from the arduino website.
//Basically map, but with a curve on the scale (can be non-uniform).
float fscale( float originalMin, float originalMax, float newBegin, float
    newEnd, float inputValue, float curve){

  float OriginalRange = 0;
  float NewRange = 0;
  float zeroRefCurVal = 0;
  float normalizedCurVal = 0;
  float rangedValue = 0;
  boolean invFlag = 0;

  // condition curve parameter
  // limit range

  if (curve > 10) curve = 10;
  if (curve < -10) curve = -10;

  curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
  curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function

  // Check for out of range inputValues
  if (inputValue < originalMin) {
    inputValue = originalMin;
  }
  if (inputValue > originalMax) {
    inputValue = originalMax;
  }

  // Zero Refference the values
  OriginalRange = originalMax - originalMin;

  if (newEnd > newBegin){
    NewRange = newEnd - newBegin;
  }
  else
  {
    NewRange = newBegin - newEnd;
    invFlag = 1;
  }

  zeroRefCurVal = inputValue - originalMin;
  normalizedCurVal  =  zeroRefCurVal / OriginalRange;   // normalize to 0 - 1 float

  // Check for originalMin > originalMax  - the math for all other cases i.e. negative numbers seems to work out fine
  if (originalMin > originalMax ) {
    return 0;
  }

  if (invFlag == 0){
    rangedValue =  (pow(normalizedCurVal, curve) * NewRange) + newBegin;

  }
  else     // invert the ranges
  {
    rangedValue =  newBegin - (pow(normalizedCurVal, curve) * NewRange);
  }

  return rangedValue;
}

```

# Answer
The potentiometer is only supposed to modify the threshold at which the Digital Output Pin will output a HIGH or LOW value. The Analog Output Pin should be not altered by the potentiometer.

I think your sound module might not be the best for your project, if you are working with weak audio signals. It suits more for projects like clap detectors and such. You might be able to use that sensor for detect weaker signals if you put an audio amplifier after the Analog Output Pin, or change the Analog Reference value on the Arduino.
> 1 votes

---
Tags: sensors, arduino-nano, led, sound
---


title: Exception Handling with the Arduino IDE

text:
# Question
Title: Exception Handling with the Arduino IDE
I'm using a port of the STL found here and trying to debug with a simple `try{...}catch{...}` loop. When compiling with the Arduino IDE, I get the error message

> exception handling disabled, use -fexceptions to enable.

I'm not quite sure what this means. Can the Arduino simply not support exceptions? Or is `-fexceptions` a compiler flag I can enable?

# Answer
> 5 votes
As you have already found out, add `-fexceptions` to the compiler flags. This can be done by modifying the `platform.txt` of your Arduino IDE installation.

See https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L28. There is `-fno-exceptions` defined, so you have to remove that, too.

# Answer
> 1 votes
Arduino is a very limited platform, and handling exceptions requires quite a bit of hidden code to properly unwind the stack wherever the exception occurs.

So the default is to turn it off and teach users to not use exceptions in arduino and instead other type of error handling.

---
Tags: arduino-ide
---


# Question
Title: Value read is not changing while rotating pot in arduino?
I am trying to read voltage using analogRead in Arduino Uno from a voltage divider circuit consisting of 1k resistor and 10k pot. The Pot used is bourns 3296. The values obtained only range from 1011 to 1023? Why is the count not reducing further if I rotate the pot?

(this how i have connected the circuit, but the pot is the one that i have mentioned above, i couldn't find that kind in the software, but i have made the connection this way only)

```
int analogPin = A0;

// variable to store the value read
float val = 0;

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

void loop() {
  Serial.println(val); // read the input pin
  val = analogRead(analogPin); // debug value
}

```

Since potentiometer itself is a voltage divider, I have tried connecting as per the answer, the ends of the 10k pot to 5V and ground , and the slider pin to the analog pin A0. The new circuit is as shown below, but I am still unable to get the value ranging from 0 to 1023. The values returned only vary in between 1010 to 1023. What is going wrong? How do I get the full range?

# Answer
A potentiometer is already a voltage divider by itself. The outer contacts are connected to the ends of a resistor strip. The middle pin is connected to a wiper, which can slider over the strip, dividing the strip into 2 parts. So you connect it like it is described at the start of your sketch (before the last edit): The outer pins to 5V and ground respectively and the middle pin to the analog input. (When using this in different circuits, keep in mind, that you should not draw too much current from the middle pin. Don't drive any load directly from it. The analog input does only draw a very small amount, so that's absolutely no problem.)

When adding a constant resistor in series with the pot, you are only adding a dead range, that cannot be set with the circuit.

---

> what does those voltage dividers with pots serve purpose for?

Only the pot: Potentiometers are mostly used to give a setpoint, a user controlled voltage, which can be read by a microcontroller or used directly for controlling further electronics.

With an additional resistor: You can put in an additional resistor at the high side of the pot, to lower the voltage further. For example if you - for whatever reason - have to use a higher voltage for the voltage divider, than the microcontroller can handle. You can calculate the value of the resistor, so that the voltage on the analog pin will never exceed the limits. But this scenario must be very rare. I didn't encounter such a situation ever.
> 1 votes

# Answer
OK, I am unable to leave a comment (\< 50) so...

Use this link to learn about the AREF pin on the Arduino, this may not be your problem but it is good to know about anyway: what is arduino adc reference?

Your pot MAY be broken. Measure the resistance of the pot with an ohm meter, from the center pin to either of the side pins. Verify when you turn it the resistance varies from 10K to 0.

You can also measure the voltage it is providing your Arduino by measuring the voltage it presents to pin A0. Verify the voltage changes little by little from +5 to 0 when you turn it back and forth.

You list the pot as being a "bourns 3296" which the data sheets show as a "**Multiturn** / Cermet / Industrial / Sealed" pot.

Just so you know, when you adjust it you will have to turn it 25 turnes to fully adjust it through its entire range. The data sheet shows "Effective Travel.........25 turns nom."
> 1 votes

---
Tags: arduino-uno, sensors, analogread, potentiometer, voltage-divider
---


# Question
Title: Serial monitor shows repeated CIPSEND and CIPCLOSE
I'm trying to build a heart rate monitor using ESP-01. The code compiles and uploads well but once uploaded, in the serial monitor it shows the following. It keeps repeat CIPSEND and CIPCLOSE over and over. What could cause this? Could it be faulty hardware or is it a problem with the code?

```
 AT+CIPSTART="TCP","184.106.153.149",80
 AT+CIPSEND=29
 AT+CIPCLOSE
 AT+CIPSTART="TCP","184.106.153.149",80
 AT+CIPSEND=29
 AT+CIPCLOSE
 AT+CIPSTART="TCP","184.106.153.149",80
 AT+CIPSEND=29
 AT+CIPCLOSE
 AT+CIPSTART="TCP","184.106.153.149",80

```

# Answer
> 0 votes
The reason that you are seeing those messages on the serial monitor is because the code is *telling* it to print those messages on the serial monitor.

Every time a message is sent to the ESP8266 it is also sent (for debugging purposes) to the Serial.

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


title: SG90 servo motor not working

text:
# Question
Title: SG90 servo motor not working
I tried to test a servo motor for a project using this simple circuit but the motor won't move. I've used this before with the same setup and code and it worked, but now suddenly nothing works, even tried a different servo motor. I have tried changing arduinos, changing signal pins , changing servos but nothing works. I had got them to work only a few days back but now suddenly i cant and i dont know where im going wrong. **here is my circuit** :- image of circuit

```
#include <Servo.h>
Servo myservo;
int pos = 0;
void setup()
{
myservo.attach(9);
}
void loop()
{
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos);
 delay(15);
}
for (pos = 180; pos >= 0; pos -= 1)
{
 myservo.write(pos);
delay(15);
}
}

```

# Answer
There's nothing wrong with your code. Check your wiring:

* Servo brown -\> Gnd
* Servo red -\> +5v (not +3v)
* Servo Orange -\> pin 9
* Connections at the servo-connector and at the Arduino are electrically sound
* Try swapping the 3 jumper wires (the only parts you didn't say you'd swapped)
> 1 votes

---
Tags: arduino-uno, servo
---


title: Help with Bluetooth shield

text:
# Question
Title: Help with Bluetooth shield
Hey guys I have this Bluetooth shield

Does anybody know how I can get it to connect to Arduino? I can't find any guides on it.

I have this serial program that I want to use to turn on a led. but I can't seem to enter AT mode, or get any indication that besides it connecting to my Mac it's receiving or transmitting any signals.

Anybody got any tips for tutorials/tips for tests for a MAC OSX user?

UPDATE: here is a better foto

I'm trying to run this Arduino code. that uses a 1 to turn a led on and a 0 to turn it off. I want to send these 1's and 0's through a Mac program called Bluterm. I connect it to the HC-05 BUT it doesn't send me anything back. (THE LED IS GREEN, IT'S CONNECTED ON MAC AND ON BLUTERM)

Here is my Arduino code:

```

int led = 13;
int value = 0;

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);

}

void loop() {
  if (Serial.available() > 0) {
    value = Serial.read();
    delay(5);

    if (value == '1') {
      digitalWrite(led, HIGH);
      Serial.println("LED IS ON");

    }

    if (value == '0') {
      digitalWrite(led, LOW);
      Serial.println("LED IS OFF");

    }

  }
  }

```

UPDATE 2: Here is the code from the PDF that was shipped with my shield:

```

unsigned int timeout=0; unsigned char state=0;
ISR(TIMER2_OVF_vect) {
TCNT2 = 0; timeout++;
if (timeout>61) {
state=1;
timeout=0; }
}
void init_timer2(void) {
//Timer2 Service
TCCR2A |= (1 << WGM21) | (1 << WGM20);
TCCR2B |= 0x07; // by clk/1024
ASSR |= (0<<AS2); // Use internal clock - external clock not used in Arduino
TIMSK2 |= 0x01; TCNT2 = 0; sei();
}
void setup() {
//Timer2 Overflow Interrupt Enable
Serial.begin(9600);
pinMode(2,INPUT); pinMode(13,OUTPUT); attachInterrupt(0,cleantime,FALLING); init_timer2();
}
void loop() {
switch(state) {
case 0:
digitalWrite(13,LOW); break;

case 1: digitalWrite(13,HIGH); Serial.print("Hellow BT"); break;
} }
void cleantime() {
timeout=0;
state=0; }

```

Anybody can help me decipher this code? none of this looks familiar to me thanks guys,

juriaan

UPDATE 3:

UPDATE 4

# Answer
> 0 votes
You need to understand the basics before you try running code to "do things":

1. The shield can run in two modes: AT command mode, which is used to configure it, and Transparent UART mode, which is used to communicate.
2. Communication with the Arduino is done through UART serial, and the pins used for that communication are selected using the big bank of jumpers.
3. Nothing will happen until you have configured the shield using AT commands.

To progress you really need the manual for the shield. This should be available from wherever you purchased it. That will detail:

* What the positions of the jumpers mean
* What the AT command set of the module is
* What the baud rate is which you need to use to communicate

And if it's any good:

* Example code

Once you have at least the first set of those bits of information you can write some software for the Arduino which will pass anything received on Serial through to the bluetooth shield, and anything received from the bluetooth shield back through to Serial. You can then use the serial monitor in the IDE to interact with the shield and configure it in the way you need it.

Once you know how to configure it you can then write some better software for the Arduino that does any startup configuration you need and then operates on the data coming in through Transparent UART mode.

---
Tags: arduino-uno, bluetooth, shields
---


title: Data type conversion problem

text:
# Question
Title: Data type conversion problem
I have a Wemos D1 board with a OLED display using the u8g2 library.

I am printing my MAC-adress on the serial port & would like to print the same information on the OLED:

```
#include <ESP8266WiFi.h>
#include <U8g2lib.h>
byte mac[6];
setup(){
  Serial.println(WiFi.macAddress());
  WiFi.macAddress(mac);
  u8g2.drawStr(1,10,WiFi.macAddress());
  u8g2.sendBuffer();
}

```

This does not work. It prints the MAC-address on the serial port but not on the OLED.

I get: no known conversion for argument 3 from 'String' to 'const char\*

How can I print the MAC-information on my oled using the u8g2-library?

# Answer
As said by @Mikael Patel You need to append `.c_str()` to `u8g2.drawStr(1,10,WiFi.macAddress());` creating the line: `u8g2.drawStr(1,10,WiFi.macAddress().c_str());`

The problem is that `WiFi.macAddress()` returns a `String` not the needed `const char*` by the `drawStr` function. `c_str` converts the `String` object into a `const char*`.

Please look at the documentation of the `u8g2` library for the `drawStr` function.

link

And here the documentation for `String`

link
> 1 votes

---
Tags: data-type
---


title: Leonardo soft bricked

text:
# Question
Title: Leonardo soft bricked
I was uploading a sketch to my Arduino Leonardo and I pressed the reset button accidentally while it was still uploading. Now the board does not get recognized by my computer. Is there something that can be done to save it or should I get a new one?

# Answer
> 0 votes
You'll need to program it trough the ISP port with an AVR programmer if you can't program it through a reset or double reset anymore. This can be done using another arduino. A tutorial is on the arduino.cc website.

---
Tags: arduino-leonardo
---


# Question
Title: Schematic with Atmega32U4 and WS2812 Led (Smiley Shape). Does it work?
I'm new here and I'm a newbie in electronics. Since 1 year I'm playing around with Arduino (different types) and now I want to build my own thing: a smiley with WS2812D-F5 RGB leds. But I'm not sure if I did any misstakes. Is it possible that an expert in electronics can check my schematic? That would be very kind, nice and cool :)

Functions: The switch SW1 is connected on D8 (PB4) and if pushed the smiley changes from sad to happy. pushed again it changes again and so on.

Because the WS2812 leds needs a lot of current, I have added some different possibilities to power the whole thing: 1x DC jack connected on a voltage regulator that output 5V fixed and two pins for a LiPo 3.7V that ist connected too on the voltage regulator. I dont know if it works if the LiPo has only 3.7V.

Well.. then I added a power switch, micro usb, FTDI and SPI connection. If one fails to burn the bootloader or to upload a sketch, I have more possibilities to do that ;)

Yeah I think thats it. If I forgot something, just ask me. Thanks a lot!

Kind regards.

Greetings from Switzerland

delf

Edit 15.5.19 18:00 Ok, I just changed the schematic based upon your great advices :) Thanks a lot to everyone. I changed/added the regulator. Current output=3A (each one). Should be enough. But I'm not sure if I can divide the current in that way.

What do you think? :)

Greetings to everyone :)

# Answer
> 0 votes
On the FTDI header you need to swap the TX and RX pins. The TX of the FTDI should connect the the RX of the Arduino, and vice-versa.

Also, on the FTDI header, the USBVCC pin is connected directly to the 5V pin. I would want to connect my PC to that header if external power is applied to your board. If you're never going to use that pin to power the board, you could leave it disconnected. The same applies to the USB port.

I'd have the LiPo connector bypass the regulator, as all it does is drop the voltage even lower. A LiPo is around 4.2V when full. The 3.7V is only it's nominal voltage.

D1 is in a weird location. If you want to use it to prevent reverse polarity, move it between the jack, and the input of the voltage regulator.

# Answer
> 2 votes
No. That circuit will not work.

The moment you turn on more than a few of the LEDs the regulator will go into meltdown. No matter how powerful your power supply is, that regulator is the bottleneck and will overheat the moment you try and light your smiley face.

The regulator (a venerable 7805 - I mean, come on, that's from the ark. There's far better modern regulators now...) is rated for a maximum of 1A. That is with *very good heatsinking and thermal management, and an input voltage only slightly above 5V + the dropout voltage*. Your circuit can draw up to about 4A. That's 4x what the regulator is rated for when it's at its most optimim - probably 6x to 8x what your arrangement would be able to provide.

For this kind of circuit you *need* a switching regulator. One that can provide many many times the current of a linear regulator like the 7805 (or the more modern LM1117-5.0). You need one that will provide at least 4A, and ideally a little more for some extra headroom. So you're looking at 5A.

With a decent efficiency you could then run the whole thing from a 12V input with 2.5A minimum current. Assuming 85% efficiency:

* 12V @ 2.5A = 30W
* 85% of 30W = 25.5W
* 25.5W @ 5V = 5.1A

So a 12V, 2.5A supply being fed into a 5V, 5A switching regulator with at least 85% efficiency will allow your circuit to operate more reliably.

You also need to take care with your PCB layout (assuming you are designing this for building on a PCB). Switching regulators take a certain amount of care when laying them out. You should refer to the recommended PCB layout in the datasheet for your chosen regulator and stick as closely to that as you can.

Also handling larger currents requires more thought put into your traces. This site has a handy trace width calculator.

As an example: for a 5A trace over a distance of 5cm with (standard) 1oz copper your trace should be at least 2.77mm wide. That will give a 10C temperature rise in the trace at room temperaure (25C to 35C).

---
Tags: atmega32u4, ws2812
---


# Question
Title: Unexplainable int behavior in encoder/LED project
I am trying to use a rotary encoder to cycle through the brightest versions of R, G & B. And it works! Red goes to blue just fine. Then G happens. For some reason, the int for green goes completely haywire. And it does this the same way on two Arduinos.

So my question is this: why would two, identically assigned variables treat `++` completely differently? After hours (and hours and hours) of looking, I'm completely out of possible answers.

```
#include <Encoder.h>
#include <FastLED.h>

/* Encoder */
Encoder myEnc(2, 3);
const int swPin = 4 ;
long oldPosition  = -999;

/* LEDs */
#define LED_PIN     7
#define NUM_LEDS    150
CRGB leds[NUM_LEDS];

/* RGB Loop */
volatile int cycle = 1;
volatile int brightness = 0;
volatile int r = 127;
volatile int g = 0;
volatile int b = 0;

void setup() {
  pinMode(swPin, INPUT);
  Serial.begin(9600);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  // Read from rotary encoder.
  long newPosition = myEnc.read();

  if (newPosition != oldPosition) {
    oldPosition = newPosition;
    Serial.println(newPosition); /* Sends elsewhere */
  }

  /* Will eventually move this inside the above if
   * statement so the color shift is controlled by
   * a rotary encoder.  Down here for debugging.
   */
  delay(50);
  updateColor( );
}

void updateColor(  ) {

  Serial.println(" "); // For readability.

  if ( brightness >= 127 ) {
    brightness = 1;
    if ( cycle > 6 ) {
      cycle = 1;
    } else {
      cycle++;
    }
  } else {
    brightness++;
  }

  if ( cycle == 1) {
    b++;
  }
  else if ( cycle == 2) { /* rb --> b */
    r--;
  }
  else if ( cycle == 3) { /* b --> bg */
    g++;
  }
  else if ( cycle == 4) { /* bg --> g */
    b--;
  }
  else if ( cycle == 5) { /* g --> rg */
    r++;
  }
  else if ( cycle == 6) { /* g --> rg */
    g--;
  }
  else {
    Serial.print("==================== ");
  }

  /* Debugging */
  Serial.print("brightness:");
  Serial.print(brightness);
  Serial.print("   cycle:");
  Serial.print(cycle);
  Serial.print("   r:");
  Serial.print(r);
  Serial.print(" g:");
  Serial.print(g); // goes completely bonkers
  Serial.print(" b:");
  Serial.print(b);
  Serial.println(" ");

  for (int i = 0; i <= NUM_LEDS; i++) {
    leds[i].setRGB( r, g, b );
  }

  FastLED.show();

}

```

spits out the following in the serial monitor :

```
brightness:1   cycle:1   r:127 g:0 b:1

brightness:2   cycle:1   r:127 g:127 b:2

brightness:3   cycle:1   r:127 g:32639 b:3

brightness:4   cycle:1   r:127 g:32639 b:4

brightness:5   cycle:1   r:127 g:32639 b:5

brightness:6   cycle:1   r:127 g:32639 b:6

```

Red and blue are doing exactly what I want. Green is off on Mars.

Any/all help would be enormously appreciated. Thanks in advance.

# Answer
Here:

```
CRGB leds[NUM_LEDS];

```

you are defining an array of `NUM_LEDS` objects of the `CRGB` type. Valid indices for this array range from `0` to `NUM_LEDS-1`.

Here:

```
for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i].setRGB( r, g, b );
}

```

you are accessing the array elements at indices `0` to `NUM_LEDS`. The last iteration is an out-of-bounds access, which is causing memory corruption. You should instead write

```
for (int i = 0; i < NUM_LEDS; i++) ...

```
> 3 votes

---
Tags: arduino-uno, serial, c++, rgb-led, rotary-encoder
---


# Question
Title: Unresolved reference to public function from library
I have three libraries that I've written and I'm trying to use. They're stored as follows

```
Documents
├── Some/Path/To/Folder
│   └── firmware.ino
└── Arduino
    └── libraries
        ├── error
        │   ├── error.h
        │   └── error.cpp
        ├── lmp91000
        │   ├── lmp91000.h
        │   └── lmp91000.cpp
        └── tps7a7100
            ├── tps7a7100.h
            └── tps7a7100.cpp

```

Both lmp91000.h and tps7a7100.h have `#include "../error/error.h"` and are able to access variables and functions declared in error.h and error.cpp just fine.

firmware.ino includes all three libraries as you would expect them to be included and it is able to create instances of classes defined in both lmp91000 and tps7a7100 and use their methods (which depend on error). I am also able to create instances of a struct (`ERROR`) defined in error.h from firmware.ino, however I am not able to access functions from error.h and error.cpp. Error recived is

```
firmware.ino:19: undefined reference to `LOG_E(ERROR)'

```

However when I remove the guards in error.h that error no longer appears (implying that `LOG_E` can be resolved) but I get the expected errors of multiple definitions as there are multiple `#include error.h`.

My thoughts are that because of the guards error is not being included in a location where the sketch has access to the functions, but I may be completely off on that. I know there must be a way around this, as I'm able to access Wire.h for example from firmware.ino even though that is included in lmp91000.h - how do I solve this?

firmware.ino

```
#include <error.h>
#include <lmp91000.h>
#include <tps7a7100.h>
#include <Wire.h>

lmp91000 pot(12);
tpsa7100 vreg(10,9,8,7,6,5,4);

void setup() {
    Wire.begin();
    Serial.begin(115200);
    while(!Serial);
    vreg.enable();
    pot.enable();
    ERROR misc;
    misc.errorCode = 0x50;
    LOG_E(misc);
}

void loop() {
}

```

error.h

```
#ifndef error_h_included
#define error_h_included

#include "Arduino.h"

// Error Structure
typedef struct{
    int errorCode;
    char const *errorName;
    char const *errorDesc;
    bool isFatalError;
    bool shouldRetry;
}ERROR;

// Global error types
const ERROR E_SUCCESS = {0x00, "E_SUCCESS", "Success", false, false};
const ERROR E_INVALID_ARG = {0x10, "E_INVALID_ARG", "Invalid argument passed", true, false};
const ERROR E_I2C_NACK_ADDR = {0x20, "E_I2C_NACK_ADDR", "NACK on I2C address byte", false, true};
const ERROR E_I2C_NACK_DATA = {0x21, "E_I2C_NACK_DATA", "NACK on I2C data byte", false, true};
const ERROR E_I2C_BUFF_LEN = {0x22, "E_I2C_BUFF_LEN", "Transmit Data too long for I2C buffer", true, false};
const ERROR E_I2C_ERROR = {0x23, "E_I2C_ERROR", "Undefined I2C Error", true, false};
const ERROR E_I2C_TARGET_DISABLED = {0x24, "E_I2C_TARGET_DISABLED", "Target device for I2C comms disabled", false, false};
const ERROR E_I2C_READ_ERROR = {0x25, "E_I2C_READ_ERROR", "I2C Data could not be read", false, false};
const ERROR E_I2C_WRITE_ERROR = {0x26, "E_I2C_WRITE_ERROR", "Attempting to write zero bytes to I2C bus", false, false};

// Function Definitions
bool E(ERROR error_struct);
void LOG_E(ERROR error_struct);
ERROR WireErrorDecode(int code);

#endif

```

error.cpp

```
#include "error.h"

// Error Handling Functions

// E(ERROR)
// Evaluate the successfullness of the error
// Return 0 if error is a success error
// Return >0 if error is not success error
bool E(ERROR error_struct) {
    return (int)(error_struct.errorCode & 0xF0);
}

// LOG(ERROR)
// Log the error
void LOG_E(ERROR error_struct) {
    Serial.print(error_struct.errorCode);
    Serial.print("\t");
    Serial.print(error_struct.errorName);
    Serial.print("\t");
    Serial.println(error_struct.errorDesc);
}

// WireErrorDecode(code)
// Decode Wire.EndTransmission error codes
ERROR WireErrorDecode(int code) {
    switch(code) {
        case 0:
            return E_SUCCESS;
        case 1:
            return E_I2C_BUFF_LEN;
        case 2:
            return E_I2C_NACK_ADDR;
        case 3:
            return E_I2C_NACK_DATA;
        case 4:
            return E_I2C_ERROR;
        default:
            return E_INVALID_ARG;
    }
}

```

**Update:** These errors seem to be board specific - see question here

# Answer
> 1 votes
The filename `error.h` is not a good name for a library. Some compilers and cores (such as the ESP32 and Curie cores) have a file `error.h` of their own which will be used in preference to yours.

Instead, name your library something more sensible.

---
Tags: library
---


# Question
Title: ADS1115, ZMPT101b and Arduino Uno listing program for AC measurement
I got problem in my result where my ADC read cannot give the biggest and the lowest ADC Value if I am using ADS1115. meanwhile, when I am not using ADS1115 I can get the biggest and the lowest ADC Value using a listing program that I use before. Thank u, need for help.

\]

# Answer
The ZMPT101b is a transformer which converts voltage. You can read the output with analog pin.

The ADS1115 is an analog to digital converter. It reads the analog voltage the same way as the analog pin of your Arduino does. The result then can be read over I2C as a register value. You can't read it with analogRead.

So you can use the ADS1115 to convert the analog output of the ZMPT101b.

To read the digital value from the ADS1115 with Arduino, use the Wire library or find a library for the ADS1115. For example this one.

I use ADC121 with Wire library. I initialize it in setup()

```
  const byte REG_ADDR_RESULT = 0x00;
  const byte REG_ADDR_CONFIG = 0x02;

  // initialize the Wire library
  Wire.begin();
  Wire.setClock(400000);

  // configure the ADC
  Wire.beginTransmission(I2C_ADC121);
  Wire.write(REG_ADDR_CONFIG);
  Wire.write(REG_ADDR_RESULT);
  Wire.endTransmission();

  // set the 'result' register as default
  Wire.beginTransmission(I2C_ADC121);
  Wire.write(REG_ADDR_RESULT);
  Wire.endTransmission();

```

and then in code I read the value with this function

```
unsigned short adcRead() {
  Wire.requestFrom(I2C_ADC121, 2); // request 2 bytes
  byte buff[2];
  Wire.readBytes(buff, 2); // read 2 bytes
  return (buff[0] << 8) | buff[1]; // get the result as 16 bit number
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino will not read three successive packets in the serial connection
I have written a small program to send serial commands from Python to the Arduino Micro. This is my code for both:

Python

```
import serial

ser = serial.Serial('COM5', 9600)

ser.write(b'0')
ser.write(b'1')
# ser.write(b'2')

print('done')

```

Arduino

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

void loop()
{

  while (!Serial.available()){}
  Serial.println(Serial.read()-48);

}

```

If I keep the `ser.write(b'2')` line in the Python code commented out, the code executes nearly instantly, and I am able to see both transmissions in the serial monitor. If I uncomment it, the Python code takes about 5-7 seconds to execute, and none of the data comes through the serial monitor.

I've tried different baud rates but that hasn't helped. I've also tried sending an integer rather than `b'#'`, and the same thing happens, no data is transmitted if I have all three serial commands active.

What is happening in my code? Is the serial buffer overloaded by the three successive writes and the buffer ends up flushing?

# Answer
> 1 votes
The problem is that your code works but you substract 48 from what you received.
Which if python sends a `char` with values: `'0'` `'1'` `'2'` it will result in the serially outputted values of `NUL` `SOH` `STX` which are invisible.

If python transmits the raw byte value (aka `0x00` `0x01` `0x02`) this would result in `0x00 - 48 = undefined behaviour` with a underflow (same goes for `0x01` and `0x02`)

---
Tags: serial, python, bytes
---


# Question
Title: How to program the nodeMCU through OTA using GPRS?
I'm using a NodeMCU in one of my projects. The setup is in a remote location. That place doesn't have WiFi so I'm using GPRS (GSM SIM800V) for sensor data collection to my server. Right now I need to update my new firmware to that NodeMCU.

Is it possible do OTA using GPRS (GSM SIM800V)?

# Answer
> 1 votes
Yes, it is possible, but it takes some work on your part.

I recently had to implement OTA updates for the ESP32 over an RS-485 link, and it's actually pretty simple to manage. The hard part (for you) is the communication connection.

Performing an update (assuming the flash is already partitioned and set up right for OTA updates) is a case of "starting" the update, passing the update manager the flash data, then "ending" the update:

1. `Update.begin(size)` \- This starts the upgrade process. You need to provide the expected size of the flash data at this point.
2. `Update.write(*data, length)` \- Pass a block of flash data to the updater for writing. An alternative is to read directly from a `Stream` class, which will try and read the number of bytes specified in the `size` parameter to `begin`.
3. `Update.end()` \- This will finish it all off and switch the bootloader to load from the new flash. If it worked fine it will return `true`, otherwise, it will return `false`.

Assuming the above worked, you can no reset the board with `ESP.restart()`

For added security you can also pass an MD5 hash of the data to `Update.setMD5(md5)` and the updater will check that the uploaded data matches that MD5 hash.

Of course, all this needs implementing in your program that is running on the target device *before* you try and do any OTA updates. And, of course, you need to arrange the actual upgrade channel to get the commands and data through to the target in the first place.

So:

1. Implement a method of getting the data to the target
2. Implement the updater code
3. Go to the device and upgrade the firmware
4. From that point on you should be able to use OTA updates through your own chosen mechanism.

---
Tags: arduino-uno, programming, nodemcu, gsm, sketch
---


# Question
Title: WebSocket message with Arduino MKR 1010 using WiFiNINA and ArduinoHttpClient libraries
I am trying to send a WebSocket message to a server. The example for the ArduinoHttpClient library uses WiFi101 but that will not work for the MKR 1010. So I am trying to use WifiNINA instead. The WiFi part works fine but is seems the WebSocket cannot "begin".

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

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

WiFiClient wifi;

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

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

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

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

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

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

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

}

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

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

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

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

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

}

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

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

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

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

```

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

# Answer
I needed to use port 80.

I got a hint from wikipedia:

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

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

Switched to port 80 and it works!
> -1 votes

---
Tags: wifi, mkr1010
---


# Question
Title: ESP8266 NODEMCU V3, HOW TO USE AND CONTROL V3 OUTPUT POWER
this is my very first post in here so I apologise if I am not giving you all the information that I should.

I am creating this topic to ask you help regarding how to control and use the v3 output of my Nodemcu.

I have a script which is working fine to power on and off a led by using one of the GPIO and the ground. However, my project requires to power on a small motor for about 2 seconds and then stop it. If I connect this motor to one of the GPIO and the ground I can control it but it runs very slow. If I connect the motor to the 3V output it goes fine but I can't turn it on or off. The motor requires 3V to run properly. How can I turn it on and off by powering it from that 3V output?

What am I missing?

I have a 4n25 chip which I saw in a video that has been used for a similar project however the vide is in Portuguese and I am not able to follow it properly.

Can please someone advice?

Thank you for your time,

Ade

# Answer
> 2 votes
You cannot control the "V3" output. It's a 3.3V power supply output. Think of it like a battery. It's always on and always giving power.

Instead, you need to add a "switch" to control that power that the ESP8266 can itself control, such as a MOSFET or a motor driver (H-Bridge).

---
Tags: esp8266, motor
---


title: Arduino nano / uno analog pin

text:
# Question
Title: Arduino nano / uno analog pin
I'm working on a project where I need 7 analog pins. I read the datasheet of Ardnuino Uno : 6 analog pins available. So I decided to use an arduino mega with 16 analog pin available. Then I saw the arduino nano had 8 analog pins. But when I read the datasheet, both arduino uno and nano use Atmega328 In my final project, I will not use the board but only the pdip chip (analog pins are from pin number 23 to 28). Is it possible to "convert" another pin of the pdip to be an analog pin ?

Thank you

# Answer
No, this is not possible. The datasheet of the ATmega328P states it has:

> * 8-channel 10-bit ADC in TQFP and QFN/MLF package
> * 6-channel 10-bit ADC in PDIP Package

If you want to use a bare chip, it won't be possible with a PDIP package.
> 2 votes

# Answer
A Nano and some ProMinis have all 8 analog input pins available from the 32-pin TQFP Atmega328P package. An Uno only has 6 of the 8 available in the 28-pin DIP package. Instead of the bare 28-pin DIP, use one of the 32-pin TQFP parts, on a breakout board, or as a packaged 'system' board; a Promini is the 328P with resonator and voltage regulator, connect to it with external FTDI module for programming/debugging; the Nano which goes a step further and adds a USB interface chip.
> 0 votes

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


# Question
Title: Basic if endif not working and I'm puzzled
I got this small code I'm trying things on for like an hour.

```
int receivers = 0;
#if defined(PPM_RECEIVER)
  receivers++;
#endif

```

And I just cannot get it working, It keeps returning a "'receivers' does not name a type" on line 4.

# Answer
You can't use commands like `receivers++` outside of a function. That is runtime executable code, and has to be run from inside a function. Global scope doesn't get executed in the same way as code in a function.
> 3 votes

---
Tags: arduino-nano
---


title: Switch statement cases not executing

text:
# Question
Title: Switch statement cases not executing
Overview: I am trying to use a switch statement to run different tests. A main menu is displayed on the serial monitor, and then the user is given the option to enter their menu choice in the serial monitor. The menu choice entered in the serial monitor should subsequently run the appropriate case statement.

Issues: 1. When I enter a choice the case statement for that choice does not run 2. When I enter a choice my the serial monitor scrolls through my menu 3 times displaying 49, then 13, then 10.

Questions:

1. Why are my case statements not executing?
2. Why does the serial monitor scroll three times displaying these random numbers?

```
//////////////PREPROCESSOR DIRECTIVES/////////

#include <Wire.h>

/////////////GLOBAL VARIABLES////////////////

int ADDRESS_SLAVE = 0x08;
int ADDRESS_VERSION = 0x00;
int ADDRESS_STATUS = 0x01;
int ADDRESS_ENABLE = 0x02;
int ADDRESS_CONFIG = 0x03;
int ADDRESS_RESTART = 0x04;
int ADDRESS_STARTUP_STATE = 0X05;
int ADDRESS_COMPENDISREG1 = 0X07;
int ADDRESS_COMPENDISREG2 = 0X08;
int ADDRESS_COMPENDISREG3 = 0X09;
int ADDRESS_COMPENDISREG4 = 0X0A;
int ADDRESS_FAULT = 0X0B;
int ADDRESS_FAULTMASK = 0X0C;
int ADDRESS_TEST_MODE = 0X0D;

////////////SETUP CONDITIONS/////////////////

void setup()
{
 Wire.setClock(100000);
 Wire.beginTransmission(byte(ADDRESS_SLAVE));
 Serial.begin(9600);
}

////////////MAIN FUNCTION///////////////////

void loop()
{

  int choice = 0;

  int const
            //Clock 100
            CLOCK_FREQ_P = 101,
            CLOCK_FREQ_DIV4 = 102,
            CLOCK_FREQ_DIV8 = 103,
            CLOCK_FREQ_DIV16 = 104,
            CLOCK_FREQ_DIV32 = 105,
            CLOCK_INT_SUPPLY_IBIAS = 106,
            CLK_OK = 107,

            //Bandgap 200
            BG_2p5V = 200,
            BG_MAX_LOAD = 201,
            BG_VBE = 202,
            BG_VP = 203,
            BG_VGATE = 204,
mainMenu();

   choice = menuChoice();

   switch(choice)
   {
    case CLOCK_FREQ_P :
    {
      Serial.println(F("CLOCK_FREQ_P Not yet built out"));
      while(Serial.available() > 0)
        {
           int choice = Serial.read();
        }

      delay(10000);
    }
    break;

    case CLOCK_FREQ_DIV4:
    {
      Serial.println(F("CLOCK_FREQ_DIV4 Not yet built out"));
    }
    break;

    case CLOCK_FREQ_DIV8:
    {
      Serial.println(F("FREQ_DIV8 Not yet built out"));
    }
    break;

    case CLOCK_FREQ_DIV16:
    {
      Serial.println(F("CLOCK_FREQ_DIV16 Not yet built out"));
    }
    break;

    case CLOCK_FREQ_DIV32:
    {
      Serial.println(F("CLOCK_FREQ_DIV32 Not yet built out"));
    }
    break;

    case CLOCK_INT_SUPPLY_IBIAS:
    {
      Serial.println(F("CLOCK_INT_SUPPLY_IBIAS Not yet built out"));
    }
    break;

    case CLK_OK:
    {
      Serial.println(F("CLK_OK Not yet built out"));
    }
    break;

    case BG_2p5V:
    {
      Serial.println(F("BG_2p5V Not yet built out"));
    }
    break;

    case BG_MAX_LOAD:
    {
      Serial.println(F("BG_MAX_LOAD Not yet built out"));
    }
    break;

    case BG_VBE:
    {
      Serial.println(F("BG_VBE Not yet built out"));
    }
    break;

    case BG_VP:
    {
      Serial.println(F("BG_VP Not yet built out"));
    }
    break;

    case BG_VGATE:
    {
      Serial.println(F("BG_VGATE Not yet built out"));
    }
    break;

    delay(500);
}

////////////////FUNCTIONS/////FUNCTIONS/////FUNCTIONS/////FUNCTIONS///////////////////////////

//*******************************************
//**      Function: Main Menu Display
//**      Passes: nothing
//**      Returns: nothing
//*******************************************

void mainMenu()
{
  //Prints main menu to the serial monitor
  Serial.println();
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       **         MAIN MENU        **"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println();
  Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
  Serial.println(F("\t\t\t\t\t\t **   Please type in the number of the test you want to run in the command line window at the top of the screen.   **"));
  Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
  Serial.println();
  Serial.println();
  //                                        ******************
  //                                        ***  TOP MENU  ***
  //                                        ******************

  Serial.print(F("\t\t\t CLOCKGEN \t\t\t\t BANDGAP \t\t\t GPIO "));
  Serial.println();
  Serial.print(F("\t\t\t   (1) CLK_FREQ_P \t\t\t   (8) BG_2p5V \t\t\t   (13) GPIO0_PD \t (21) GP1_N_Buff \t (29) GP2_Buff_Max \t  "));
  Serial.println();
  Serial.print(F("\t\t\t   (2) CLK_FREQ_Div_4 \t\t\t   (9) BG_MAX_LOAD \t\t   (14) GPIO0_PU \t (22) GP1_W_Buff \t (30) GP2_Buff_Min "));
  Serial.println();
  Serial.print(F("\t\t\t   (3) CLK_FREQ_Div_8 \t\t\t   (10) BG_VBE \t\t\t   (15) GP0_N_Buff \t (23) GP1_Buff_Max \t (31) GPIO3_PD ") );
  Serial.println();
  Serial.print(F("\t\t\t   (4) CLK_FREQ_Div_16 \t\t\t   (11) BG_VP \t\t\t   (16) GP0_W_Buff \t (24) GP1_Buff_Min \t (32) GPIO3_PU "));
  Serial.println();
  Serial.print(F("\t\t\t   (5) CLK_FREQ_Div_32 \t\t\t   (12) BG_VGATE \t\t   (17) GP0_Buff_Max \t (25) GPIO2_PD \t\t (33) GP3_N_BUFF "));
  Serial.println();
  Serial.print(F("\t\t\t   (6) CLK_INT_Supply_(IBias)\t\t\t\t\t\t   (18) GP0_Buff_Min \t (26) GPIO2_PU \t\t (34) GPIO3_W_BUFF "));
  Serial.println();
  Serial.print(F("\t\t\t   (7) CLK_OK \t\t\t\t\t\t\t\t   (19) GPIO1_PD \t (27) GP2_N_Buff \t (35) GP3_BUFF_Max "));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t\t\t   (20) GPIO1_PU \t (28) GP2_W_Buff \t (36) GP3_BUFF_Min "));
  Serial.println();
  Serial.println();
  //                                        *********************
  //                                        ***  CENTER MENU  ***
  //                                        *********************

  Serial.print(F("\t\t\t VBUS COMPARITOR \t\t\t\t\t\t\t VAC COMPARITOR \t\t ISNS COMPARITOR \t\t TSNS COMPARITOR"));
  Serial.println();
  Serial.print(F("\t\t\t   (37) CLK_FREQ_P \t(47) BG_2p5V \t(57) GPIO0_PD \t\t\t   (61) GP1_N_Buff \t\t  (68) GP2_Buff_Max \t\t   (74) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (38) CLK_FREQ_P \t(48) BG_2p5V \t(58) GPIO0_PD \t\t\t   (62) GP1_N_Buff \t\t  (69) GP2_Buff_Max \t\t   (75) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (39) CLK_FREQ_P \t(49) BG_2p5V \t(59) GPIO0_PD \t\t\t   (63) GP1_N_Buff \t\t  (70) GP2_Buff_Max \t\t   (76) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (40) CLK_FREQ_P \t(50) BG_2p5V \t(60) GPIO0_PD \t\t\t   (64) GP1_N_Buff \t\t  (71) GP2_Buff_Max \t\t   (77) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (41) CLK_FREQ_P \t(51) BG_2p5V \t\t\t\t\t   (65) GPIO0_PD \t\t  (72) GP1_N_Buff \t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (42) CLK_FREQ_P \t(52) BG_2p5V \t\t\t\t\t   (66) GPIO0_PD \t\t  (73) GP1_N_Buff \t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (43) CLK_FREQ_P \t(53) BG_2p5V \t\t\t\t\t   (67) GPIO0_PD \t\t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (44) CLK_FREQ_P \t(54) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (45) CLK_FREQ_P \t(55) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (46) CLK_FREQ_P \t(56) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
  Serial.println();
  Serial.println();
  Serial.println();
  //                                        *********************
  //                                        ***  BOTTOM MENU  ***
  //                                        *********************

  Serial.print(F("\t\t\t QR COMPARITOR \t\t\t ADC \t\t\t MS Driver \t\t\t AC Driver \t\t\t Active Clamp FET \t\t  V10"));
  Serial.println();
  Serial.print(F("\t\t\t   (78) CLK_FREQ_P \t\t  (84) BG_2p5V \t\t  (87) GPIO0_PD \t\t  (96) GP1_N_Buff \t\t  (100) AC_FET_LEAKAGE \t\t   (1400) V10MIN_V10_OK_FAL"));
  Serial.println();
  Serial.print(F("\t\t\t   (79) CLK_FREQ_P \t\t  (85) BG_2p5V \t\t  (88) GPIO0_PD \t\t  (97) GP1_N_Buff \t\t  (101) AC_FET_LEAKAGE_SWEEP"));
  Serial.println();
  Serial.print(F("\t\t\t   (80) CLK_FREQ_P \t\t  (86) BG_2p5V \t\t  (89) GPIO0_PD \t\t  (98) GP1_N_Buff \t\t  (102) AC_FET_RDS_ON"));
  Serial.println();
  Serial.print(F("\t\t\t   (81) CLK_FREQ_P \t\t\t\t\t  (90) BG_2p5V \t\t\t  (99) GPIO0_PD"));
  Serial.println();
  Serial.print(F("\t\t\t   (82) CLK_FREQ_P \t\t\t\t\t  (91) BG_2p5V"));
  Serial.println();
  Serial.print(F("\t\t\t   (83) CLK_FREQ_P \t\t\t\t\t  (92) BG_2p5V"));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (93) CLK_FREQ_P"));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (94) CLK_FREQ_P"));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (95) CLK_FREQ_P"));
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.println();

}

//*******************************************
//**      Function: menuChoice
//**      Passes: nothing
//**      Returns: integer for menu choice
//*******************************************

int menuChoice()
{
  int selection = 0;

  while (Serial.available() == 0);
  {
  selection = Serial.read();
  Serial.print("You entered: ");
  (int)Serial.println(selection, DEC);
  }
  return selection;
}

```

# Answer
> 2 votes
I think the issue is with the `menuChoice()` function. Try replacing it with this:

```
int menuChoice()
{
  int selection = 0;
  const byte bufferSize = 16;
  char inputBuffer[bufferSize + 1];

  if(Serial.available() > 0){
    // 50 bytes more in compile size using parseInt() vs
    // char buffer and atoi().
    // selection = Serial.parseInt();
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    selection = atoi(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
    Serial.print("You entered: ");
    Serial.println(selection, DEC);
  }

  return selection;
}

```

Of course, you could use `parseInt()` instead of the `char` buffer and `atoi()`, but the compile size is 50 bytes more.

---
Tags: atmega2560
---


# Question
Title: Frequency measuring using Arduino (AC analog input)
What I aim to do: To measure the frequency of an AC analog signal generated by an electrodynamic shaker, which has a peak voltage of 10V-- using an Arduino Uno.

What I have tried: Tried using a circuit similar to an optocoupler (using a 2N2222) transistor to take pulse input, using the `pulsein()` function. However the duration is always returning as 0.

My questions:

* Is this method an acceptable way of measuring frequency?
* What could I be doing wrong such that the time duration is always returning 0?
* Is there an easier way of carrying out this work?

Will put up the code if asked for. However it is basically just defining a few variables (for pins, duration etc), and then using the `pulsein` function.

# Answer
This project includes a frequency counter.

https://www.instructables.com/id/Oscilloscope-in-a-Matchbox-Arduino/

From the project page: This oscilloscope costs the price of an Arduino Nano (£2 and a display (£3) plus a few pence for resistors, etc. It's specification is:

* max 1M samples/second, min 1000sps
* 8-bits per sample
* DC 0-5V; AC +/- 550mV, AC +/- 117mV, AC +/- 25mV
* USB "PC scope" or built-in display
* could be battery-powered
* optional logic display
* **optional frequency meter**
* optional voltmeter
* optional signal generator

My comment: I build it, it's a nice little project and the author is an expert programmer.
> 2 votes

# Answer
> Is this method an acceptable way of measuring frequency?

Nope, not at all.

> What could I be doing wrong such that the time duration is always returning 0?

You are misusing pulsein(), it doesn't work like that; look up the documentation for it!

> Is there an easier way of carrying out this work?

Yes; there are many ways, you can research many of them. One thing you can do is make a peak detector, either in hardware or software, and then design a way to get a counts/time, which should correlate to the frequency!
> 0 votes

---
Tags: arduino-uno
---


title: LM393 Speed sensor - Counting pulses

text:
# Question
Title: LM393 Speed sensor - Counting pulses
I'm trying to calculate de rotation speed of a dc motor.

I'm using the sensor shown in the picture and a slotted disk attached to the motor. The results I was getting made no sense and after several tests I realised the following:

Most of the times I manually blocked or unblocked the sensor, two pulses were counted. That would mean that for each tooth of the slotted disk, up to four pulses were counted instead of one.

Bellow is a test code. I count pulses on the interrupt handler and reset the counter when calculating the motor speed.

Am I doing something wrong or is the sensor suffering from bouncing signals?

```
int encoderCounter = 0;
int encoderDiscSlots = 21;

int encoderPin = 19;

void encoderIncrementISR()
{
  encoderCounter++;
}

double calculateMotorSpeed(int interval)
{
  Serial.print("enc ");
  Serial.println(encoderCounter);
  double rpm = (encoderCounter*1.0/encoderDiscSlots)*60000/interval;

  encoderCounter = 0;
  return rpm;
}

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

  pinMode(encoderPin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(encoderPin), encoderIncrementISR, RISING);
}

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

  delay(1000);
  double rpm = calculateMotorSpeed(1000);
  Serial.print("rpm ");
  Serial.println(rpm);
}

```

The sensor uses the LM393 IC from TI, a spec sheet can be found here

# Answer
> 2 votes
I've done some more search on the interwebs and found someone (in Spanish) describing the same problem. That person owns an oscilloscope and could confirm that there is some bouncing on the data signal both going up and down.

The hardware solution presented is to place a 100 nF capacitor between the signal pin and ground.

I've tried it and it works.

---
Tags: arduino-mega, sensors
---


# Question
Title: WiFi or Bluetooth to communicate between several Arduinos and a Raspberry Pi
So I want to set up a network of outdoor sensors (temperature and humidity) connected to an Arduino (and at some point a second or third Arduino further away with its own sensors). Then I'd like this Arduino to wirelessly transmit this data to a Raspberry Pi running some sort of server that can receive the data and then upload it to the cloud. I'm assuming WiFi is the best method to do this because of range and the number of devices at once? Would I just have to get each Arduino a WiFi module and what kind of range can I expect from this setup?

# Answer
I would also suggest using WIFI (ESP8266) as you need to create a local network in which all devices will communicate to single host connected to the same network. If range will be issue you can use LORAWAN network for the same. LORAWAN provide high network range and if industrial gateway is used you can connect 10000 nodes(arduino in your case) communicating to the single server at a time.Else WIFI will the good.
> 0 votes

---
Tags: wifi, communication, wireless
---


# Question
Title: Usbasp Arduino Uno Bootloader Flash Error - Win 10
I'm trying to flash an Arduino Uno using usbasp but i'm getting the following error,I have checked all the connection and voltage using multimeter but still this error:

```
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/bin/avrdude -CC:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cusbasp -Pusb -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

**I have tried different three other `Usbasp` but still same error**

# Answer
> 2 votes
The problem was with the Arduinos i have received from AliExpress All of them are using WAVGAT AVGA 328P-AU chips. I flasthed other Atmel MEGA 328P chip based Arduinos using USbasp and it's working fine. But i dont know how to flash those WAVGAT AVGA 328P-AU chips.

---
Tags: arduino-uno, bootloader, flash, usbasp
---


title: Press one button then another?

text:
# Question
Title: Press one button then another?
Let's say we have two buttons - button 1 and button 2. What I need to do is to do something (like turn LED on) when button 1 is press, then button 2 is pressed. I can do it realy simple by just using two boolean variables, but how can we tell button 1 was the first pressed button?

# Answer
> 2 votes
A nice solution is to use a state variable. In C/C++ (thus Arduino) you can use an enum variable for that.

```
enum EState
{
  // Button 1 and 2 are not pressed
  NoButtonsPressed,

  // Button 1 is pressed, button 2 is not pressed
  FirstButtonPressed,

  // Both buttons are pressed
  BothButtonsPressed
};

EState _state;

void setup() {
  // put your setup code here, to run once:
  _state = NoButtonsPressed;
}

void loop() {
  // put your main code here, to run repeatedly:
  switch (_state)
  {
  case NoButtonsPressed:
    if (digitalRead(1) == HIGH)
    {
      _state = FirstButtonPressed;
    }
    break;

  case FirstButtonPressed:
    if (digitalRead(1) == HIGH)
    {
      // Button 1 is still pressed, ignore second button.
    }
    else if (digitalRead(2) == HIGH)
    {
      // Button 1 is not pressed, button 2 is pressed.
      _state = BothButtonsPressed;
    }
    break;

 case BothButtonsPressed:
   // Switch on LED
   digitalWrite(2, HIGH);

   // Reset state.
   _state = NoButtonsPressed;
   break;

 default:
   // Other state, illegal.
   break;
  }
}

```

In every state you can define exactly what needs to be done. Because of the loop function being ran continuously, you just need to handle one state (change) at a time.

Additional notes:

* Your requirements are not fully complete (like when to switch off the LED), probably when button 2 is released (which I don't check for), you can add a new state for this.
* I did not take debouncing of buttons into account; you might need to do this especially if you check for releasing buttons. On the official Arduino website there is a good article about it.
* I haven't tested the sketch.

---
Tags: programming, led, button
---


title: Ways to add pins in an arduino

text:
# Question
Title: Ways to add pins in an arduino
I'm making a project for school where I'm using flex sensors and converting that into words on an LCD (similar to the signing glove if you're familiar with that). I ran into a problem since the Arduino I'm using doesn't have enough pins for all of my flex sensors and my LCD monitor.

I'm considering getting another Arduino with more pins but I might not have time to order it since my project is due in a couple of days. I was thinking about connecting two arduinos but I'm not sure if that would work (first year coding/engineering student) Any other suggestions as to how I can create more pins?

Your input is greatly appreciated!

The Arduino I'm using is a sparkfun redboard (it only has 6 analog pins and a separate place to plug in the LCD monitor which I connected to where it says ISP f you look on the link you will see what I'm talking about SparkFun RedBoard - Programmed with Arduino).

I'm using four flex sensors

LCD:

# Answer
This can be done with the existing board. LCD can be driven by only with the digital pins. Check the below link for the wiring diagram.

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

Since there are 6 Analog pins available, all flex sensors can be easily connected.
> 1 votes

# Answer
This seems like a 1602 display. Note there are also I2C modules that connect to a 1602 making it possible to use it with only I2C wires (and VCC/GND).

See I2C-LCD-interface for a description, although there are many (similar) ones.

For the flex sensors you have 6 analog pins (hope that is enough). If not, than you need an external ADC (analog digital converter). Or connect a second Arduino and use I2C/SPI/Serial to transport the information from one Arduino to Another.
> 0 votes

---
Tags: pins
---


title: Speed Control of Brushless DC Motor

text:
# Question
Title: Speed Control of Brushless DC Motor
I cannot understand the code of controlling the speed of brushless dc motor using ESP8266 WiFi Module.

I found it in- https://ubidots.com/blog/speed-control-for-brushless-motors-with-an-esp8266-2/

The part that I cannot understand is-

```

float btof(byte * payload, unsigned int length) {

  char * demo = (char *) malloc(sizeof(char) * 10);

  for (int i = 0; i < length; i++) {

    demo[i] = payload[i];

  }

float value = atof(demo);

  free(demo);

  return value;
}

// Callback to handle subscription

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

{

    value = btof(payload, length);

      value = map(value, 0, 1023, 0, 180);

//Map the 0-100 values from the slider to the 0-180 to use the servo lib.

 ESC.write(value);

//Send the value (PWM) to the ESC

}

```

Please help me with the code!

# Answer
1. `Callback function` must be data send from server to the ESP.
2. `Payload` is the data byte sent from server.
3. `Length` is the size of data in bytes.
4. `BTOF` is basically byte to float converter which converts all the data byte received into single floating variable and return that floating point value.
5. `ECS.write` must be the function that write the value to the servo motor controller H-bridge IC. It belongs to servo library.
6. Value range that can be mapped into this ECS.write is between 0-180 so `map` function will use that will convert the `floating point data` received from `btof` function.
7. Basic definition of `map()` function:

`Map function` maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.

Syntax:

```
map(value, fromLow, fromHigh, toLow, toHigh)

```

Then `ECS.write(value)` will write that mapped value to servor motor controller H-Bridge.
> 1 votes

---
Tags: esp8266, arduino-ide, motor
---


# Question
Title: Getting two trinkets to talk to each other via the serial pins
I'm trying to make a quick proof of concept of two trinket M0s talking to each other via their RX and TX pins and I'm not able to get it working.

I uploaded sender and receiver sketches to two trinkets:

```
//sender.ino
char state[10] = "hello";

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

void loop()
{
    Serial.write(state, 5);
    delay(1000);
}

```

```
//receiver.ino
char state[10];

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

void loop()
{
    Serial.println("reading bytes");
    Serial.readBytes(state, 10);
    Serial.println(state);
    delay(1000);
}

```

After the uploads I wired the two trinkets together, jumping the RX of the first to the TX of the other and TX of the first to the RX of the other. I also connected their grounds to have a common ground.

I plugged the sender into a battery and the receiver into my computer. The problem I'm running into is that when I look at the serial monitor for the receiver instead of getting the expected "hello" I'm getting broken strings of "TestingOpen":

I double checked the pinout diagram and guide for the Trinket M0 to make sure I was using the correct RX/TX pins (pin 3 for RX, 4 for TX) and it all seems fine but obviously something is still going wrong.

Anyone know what I'm missing or misunderstanding?

# Answer
1) you should use `if (Serial.available())` before starting to read with readBytes. now you print random memory

2) readBytes is blocking. it waits for the next character until a timeout. default timeout is 1 second. after "hello" was received it waits a second. you could use readBytesUntil and some 'separator' character for example '\n' (new line)

3) readBytes returns the count of bytes read. you should use it to terminate the buffer

```
void loop()
{
  if (Serial.available()) {
    Serial.println("reading bytes");
    size_t l = Serial.readBytesUntil('\n', state, 10);
    state[l] = 0;
    Serial.println(state);
  }
}

```
> 0 votes

---
Tags: serial, adafruit
---


# Question
Title: Reset Button not working + Can't Upload code , What is wrong?
I was testing and debugging a code I wrote for a robot with 3 stepper motors on (**Arduino Uno + CNCShield V3 + a4988 stepper drivers**). I want to disable drivers at will. so I bypassed EN pin on 2 of a4988s to pin12 and pin13 of Arduino. (by defalut all EN pins of drivers are are connected to pin8 ) everything was ok but suddenly the Reset button is not working and I can't upload new codes to Arduino! I get this error:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
.
.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83
Problem uploading to board.

```

but Arduino still is working with the last code that was uploaded to it!!! have I fried my Arduino? and Why is this happening?

# Answer
Try manually resetting the board:

* Before uploading, run Verify.
* Hold the reset button and click Upload.
* Release the reset button.

If that worked, your board's reset isn't fried, it just isn't receiving a reset via the serial cable. If it failed, either part of the board or MCU may be damaged; something attached to the board may be inhibiting the reset signal; or the software may have disabled the board's reset pin. In the latter case, see the Arduino StackExchange article, How do I repurpose Arduino's reset button, for how this can happen and how to undo it if it has.

> Is here anything wrong with using pins 12 and 13?

I'm not familiar with stepper driver, but at a quick glance at its data sheet, and it's logic being 3.3v & 5 v compatible, I don't see any problem with connecting any of its logic to any of Arduino's logic pins (almost all of them). Since the driver also has a motor drive-voltage input for driving your motors, accidentally connecting an Arduino pin to a driver pin (or anything else) carrying the drive-voltage could - probably would - damage at least the connected pin driver in the MCU, and possibly other parts of it as well.

If your Arduino has a socketed Atmega chip, and since you already know another Arduino works as you expect it to, replacing the Atmega chip will be the quickest, cheapest & easiest fix. Just go over your wiring and make sure no motor drive voltages are connected to the Arduino board.
> 2 votes

---
Tags: arduino-uno, uploading, reset, stepper-motor
---


# Question
Title: How would you add Arduino WiFi Module using I2C or serial interface?
I am new to Arduino prototyping. I bought an Arduino Automatic Smart Plant Watering Kit 2.0 thinking it was a shield to use with my Arduino Uno WIFI Rev 2. However, it turns out to be a specially designed Arduino board with all of the components integrated together.

While the system works as designed, my goal is to stream the data to IBM Watson Studio, or some other third-party SaaS.

I welcome feedback to understand how it might be possible to integrate the ESP8266 WIFI module using either the I2C or Serial interface. Here is the sample code: https://www.elecrow.com/download/watering\_kit.zip I used a Raspberry Pi to get access to the data and use it in a web/mobile application but I'd like to eliminate this element, if possible.

# Answer
> 0 votes
You would connect the ESP8266 to the serial port. The normal way of working with an ESP98266 is to issue AT command (like an old Hayes modem) through a serial connection. Since you have one of those available on your board it is a simple matter to just wire it directly to it.

Just follow any of the myriad of ESP8266 + Arduino tutorials, substituting the pins in the examples for your serial pins, and use the `Serial1` object instead of the `SoftwareSerial` class that you have to use on an Uno that lacks extra serial ports.

---
Tags: esp8266, wifi
---


title: Tinkercad but offline?

text:
# Question
Title: Tinkercad but offline?
I have some issues with network and would like to work with arduino everywhere. I use Tinkercad which is great, but I would like to installit to my laptop and work without using WiFi. I couldn't find any "offline tinkercad" but maybe there are any similar programs where you can program AND write code inside.

# Answer
The best replacement (but keep in mind that Tinkercad is prob the best for code AND hardware sim) would be Yenka. They offer a "block style" language but you can go in depth with the hardware more than most programs.

Here is a ref image:
> 1 votes

---
Tags: arduino-uno, software
---


# Question
Title: Display not showing output - Arduino Wattmeter
I have been playing with this code for some time now, I am able to show the results in an 16X2 LCD display, but I am not able to do it in an OLED.

here is the code

```
    #include <SPI.h>
    #include <Wire.h>
    #include "U8glib.h"  //Library for display

    U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total

    int x = 0;
    int row = 0;
    float voltage = 0.1;

      void setup() {
       Serial.begin(9600);
       pinMode(A4,INPUT_PULLUP);
       pinMode(A5, INPUT_PULLUP);
      }

      void draw(void) {
       u8g.setFont(u8g_font_fub14r);
       {

       u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( Bat_Volt,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);

    }
    }

     void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }

      float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      float power = (voltage*current); //calculate power

     u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

    }

```

The function of the code is to read data from a "ACS712 - 30A Range Current Sensor Module" and a "Voltage Detection Sensor Module". Display is a "0.96 inch 128x64 OLED Display Module - SPI/I2C - 7 Pin ", it is converted to I2C, and working with other codes. Board : Arduino Uno Max input voltage will be 12.8V, DC. The code is supposed to display the voltage on top, ampere in the middle, and watt usage at the bottom. But it is not working when edited for OLED display.

Someone please make this a working code. I am new to C+ and coding , so need detailed help.

Here is the code that worked with 16X2 LCD

```
#include <LiquidCrystal.h>
#include <Wire.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

/*The circuits
 * LCD RS pin to digital pin 12
 * LCD enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4                                                             21333333
 * LCD D6 pin to digital pin 3
 *
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * 10K resistor
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 */

byte lightning[8] = {
  B00001,
  B00110,
  B01100,
  B11000,
  B00011,
  B00110,
  B01100,
  };

int index = 0; //size of array
const int number_of_readings = 200; //total number of readings arduino takes before it averages
const int current_zero = 510; //initial value of current from arduino with 0 amps
int current_reading[number_of_readings]; //create array for current_reading
int voltage_reading[number_of_readings]; //create array for voltage_reading

float R1=30000; //resistance of R1 in voltage sensor
float R2=7500; //resistance of R2 in voltage sensor
float current_average = current_zero; //initial value of current average
float current_total = 0; //initial value of current_total
float voltage_average = 0; //initial value of voltage_average
float voltage_total = 0; //initial value of voltage_total

void setup (){
  Serial.begin (9600);
  lcd.begin(16,2); // size of LCD
  lcd.createChar(6,lightning); //create charecter named lightning

  //STARTUP MESSAGE
  lcd.setCursor (3,0); //set cusror to row 0, column 3
  lcd.print(" "); //lcdprint
  lcd.print("Arduino"); //lcdprint
  lcd.setCursor(1,1); //set cursor to row 1, column 1
  lcd.write(6); //lcd write charecter 6 (lightning bolt)
  lcd.print("Power Meter"); //lcd.print
  lcd.write(6); //lcd write charecter 6 (lightning bolt)
  delay(5000); //delay by 5 seconds
  lcd.clear();  //clear lcd screen
  }

void loop() {
  voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
  voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
  current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
  current_total = current_total + current_reading[index]; // add current to current_total
  index = index + 1;

  if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
    current_average=current_total/number_of_readings;
    voltage_average=voltage_total/number_of_readings;
    Serial.print("Current average=");
    Serial.print(current_average);
    Serial.print("   Voltage average=");
    Serial.println(voltage_average);
    current_total=0;
    voltage_total=0;
    index=0;

  }
  float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
  float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
  float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
  float power = (voltage*current); //calculate power

  lcd.clear(); //print voltage, current, and power values to LCD screen
  lcd.setCursor(0,0);
  lcd.print(voltage);
  lcd.print("V");

  lcd.print (" ");
  lcd.print(current);
  lcd.print("A");

  lcd.setCursor(0,1);
  lcd.print(power);
  lcd.print("W");
  delay(1);

}

```

# Answer
In your Sketch

```
void draw(void)
{
   u8g.setFont(u8g_font_fub14r);
   u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( Bat_Volt,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);
}

```

**current**, **power**, **Bat\_Volt** are local variables define in `loop` function. **Bat\_Volt** in not even defined in your sketch that's why they are not printing anything in `draw` function.

Initialize then as `global variable` in your sketch and in place if **Bat\_Volt** you had use voltage here `float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read` in your sketch.

Correct that to.

Your code after edit:

```
#include <SPI.h>
#include <Wire.h>
#include "U8glib.h"  //Library for display

U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

int index = 0; //size of array
const int number_of_readings = 200; //total number of readings arduino takes before it averages
const int current_zero = 510; //initial value of current from arduino with 0 amps
int current_reading[number_of_readings]; //create array for current_reading
int voltage_reading[number_of_readings]; //create array for voltage_reading

float R1=30000; //resistance of R1 in voltage sensor
float R2=7500; //resistance of R2 in voltage sensor
float current_average = current_zero; //initial value of current average
float current_total = 0; //initial value of current_total
float voltage_average = 0; //initial value of voltage_average
float voltage_total = 0; //initial value of voltage_total
float voltage = 0.0,current_mV = 0.0,current = 0.0,power = 0.0;

int x = 0;
int row = 0;
float voltage = 0.1;

  void setup() {
   Serial.begin(9600);
   pinMode(A4,INPUT_PULLUP);
   pinMode(A5, INPUT_PULLUP);
  }

  void draw(void) {
   u8g.setFont(u8g_font_fub14r);
   u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( voltage,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);
}

 void loop() {
  voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
  voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
  current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
  current_total = current_total + current_reading[index]; // add current to current_total
  index = index + 1;

  if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
    current_average=current_total/number_of_readings;
    voltage_average=voltage_total/number_of_readings;
    Serial.print("Current average=");
    Serial.print(current_average);
    Serial.print("   Voltage average=");
    Serial.println(voltage_average);
    current_total=0;
    voltage_total=0;
    index=0;

  }

  voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
  current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
  current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
  power = (voltage*current); //calculate power

 u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

}

```
> 1 votes

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


title: DC motor phototransistor control

text:
# Question
Title: DC motor phototransistor control
So basically I have a circuit with a phototransistor, and want to convert the phototransistor value into a PWM signal that can control the speed of the motor. The code I came up with is below, however it does not work. What have I done wrong in my code? I am using an l293d chip.

```
int photoTran = A1;
int reading = 0;
int forward=2;
int backward=3;
int motorspeed=0;

void setup(){
  pinMode(photoTran,INPUT);
  Serial.begin(9600);
  pinMode (backward, OUTPUT);
  pinMode (forward, OUTPUT);
}

void loop(){
  lcd.setCursor(0,0);
  reading = analogRead(photoTran);
  lcd.print(reading);
  lcd.print("  ");
  delay(100);
{
  if (reading<30){
    digitalWrite(backward,HIGH);
    digitalWrite(forward,LOW);
    motorspeed = map(reading, 30, 1023, 0, 255);
    analogWrite(backward,motorspeed);
  }
  else {
    digitalWrite(backward,LOW);
    digitalWrite(forward,HIGH);
    motorspeed = map(reading, 30, 400, 0, 255);
    analogWrite(forward,motorspeed);
  }
  }
}

```

# Answer
> 1 votes
`analogRead()` returns an integer between 0 and 1023. Using 30 and 400 in the `map()` function, then passing in a value outside of that range will cause strange results. Here is a sketch to illustrate my point.

```
void setup(){

  Serial.begin(9600);

  // Prints -20 to 684
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 400, 0, 255));
  }
  Serial.println();

  // Prints -7 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 1023, 0, 255));
  }
  Serial.println();

  // Prints 0 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 0, 1023, 0, 255));
  }
}

void loop(){}

```

# Answer
> 1 votes
If you are using l293d you must control the voltage on its ENABLE PIN rather than controlling it on other INPUT PINS (l293d). Here is simple tutorial on controlling the Motor using L293d. here.

And @VE7JRO is right about `map()` function as your are passing the values that are out of range please take care of that part as well.

---
Tags: arduino-uno, pwm, l293d
---


# Question
Title: Compute SHA256 of string and output to string
In my Arduino project I want to compute the SHA256 hash of a string and store the result to a string, and do this recursively many times (i.e. compute hash of hash of hash etc...). So my goal is to have a *reliable* function as follows:

```
String h(String input) {
...
return output;
}

```

where for example h("abc") would return "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".

I downloaded this library (from Tools-\>Manage libraries, it is also in github) and then ran the example in TestSHA256.ino which passes all the checks. However I'm stuggling to make my function work since the library doesn't have a specific example on how to compute and return a SHA256 hash.

I have been looking in function testHash\_N() in TestSHA256.ino, which appears to create a hash (from struct TestHashVector data) and compare it with the precomputed hash (from struct TestHashVector hash\[\]).

The hash seems to be computed in lines 89-96 in TestSHA256.ino. I just want to take the actual hash string result, so for testVectorSHA256\_1 in the example, I would need to have a string = "ba7816bf....15ad" as the result.

I understand that this is related to memory referencing in Arduino but I'm not experienced so I'd be grateful if you helped me with this.

EDIT: My code snippet so far is as follows, but it doesn't output the correct hash..

```
#include <Crypto.h>
#include <SHA256.h>
#include <string.h>

#define HASH_SIZE 32
#define BLOCK_SIZE 64

char hex[256];

char *hashvalue;

SHA256 sha256;

byte buffer[128];

char *btoh(char *dest, uint8_t *src, int len) {
  char *d = dest;
  while( len-- ) sprintf(d, "%02x", (unsigned char)*src++), d += 2;
  return dest;
}

char* h(Hash *hash, char* hashvalue)
{
    size_t size = sizeof(&hashvalue);
    size_t posn, len;
    size_t inc = sizeof(&hashvalue);
    uint8_t value[HASH_SIZE];

    hash->reset();
    for (posn = 0; posn < size; posn += inc) {
        len = size - posn;
        if (len > inc)
            len = inc;
        hash->update(&hashvalue + posn, len);
    }
    hash->finalize(value, sizeof(value));

    return(btoh(hex, value, 32));
}

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

    bool tmp;
    char *testvalue = "abc";
    Serial.println(h(&sha256,*testvalue));

}

void loop()
{
}

```

# Answer
The main trick is to understand how the Arduino String class works. You can find the source code in your installation of the Arduino IDE or on github.

The basic pattern you are looking for is:

```
String h(String& input) {      // Pass String by reference to avoid copying
  char output[OUTPUT_MAX];
  char* data = input.c_str();  // Access to internal buffer
  ...
  return String(output);       // Return a String object of the output
}

```

Cheers!
> 0 votes

# Answer
I suggest the following function. That replaces a string by its hash. It's done in place in order to save memory. Make sure the buffer you give it is at least 65 bytes long. **Warning**: not tested.

```
#include <Crypto.h>
#include <SHA256.h>

#define HASH_SIZE 32

SHA256 sha256;

/*
 * Replace a string by its hash, in place.
 * `data' should point to a buffer at least 65 bytes in length.
 */
hash_in_place(char *data)
{
    uint8_t value[HASH_SIZE];

    sha256.reset();
    sha256.update(data, strlen(data));
    sha256.finalize(value, sizeof(value));

    // Convert to hex into the original buffer.
    data[0] = '\0';
    for (size_t i = 0; i < HASH_SIZE; i++) {
        data += sprintf("%02x", value[i]);
    }
}

```
> 0 votes

---
Tags: string, pointer
---


title: Power supply while using a shield

text:
# Question
Title: Power supply while using a shield
Sorry if this is a dumb question, I'm new to Arduinos. I'm planning to use a MOVI voice shield with SparkFun's RedBoard Turbo (3.3v). The RedBoard Turbo requires a power supply under 6VDC, but the MOVI website recommends a power supply of 9VDC to the Arduino, because the MOVI can't have its own power supply. Will this destroy my RedBoard? Or is this safe and just something you have to do when using shields? Thank you.

The product website says: "A 7V to 16V 500mA external power supply that powers MOVI™ through the Arduino board. The power consumption of both boards is just above what the USB port can provide. If you don't have already one, this 9V adapter from Adafruit will work perfectly."

# Answer
Although I have not used either SparkFun's RedBoard Turbo or the MOVI voice shield, reading the specifications, which you can find on their respective web sites, it would appear that they have incompatible power requirements. The SparkFun's RedBoard Turbo board web page says

*The barrel jack connection on the RedBoard Turbo has a lower input voltage than most Arduino development boards. Make sure that you are using a power supply below 6V. Please be aware that the RedBoard Turbo is also a 3.3V device and not a 5V one like the original RedBoard.*

Whilst the MOVI voice shield PDF manual (page 7) says

*What you don’t see in Figure 1 is a power supply jack. MOVI is powered through the Arduino board that needs to be powered using an external power supply. The external power supply should provide between 7V and 16V and at least 500mA current. During tests we usually used either 9V or 12V. Battery packs with this specification work as well.*

So the one needs less than 6V whilst the other more than 7V. I don't know if you can break the power connection between the two boards and feed the MOVI from a separate supply (9V is very common in the Arduino world) or you may have to swap your SparkFun for an Arduino that runs on 5V and uses a 9V supply.

The gotcha is that Arduino boards, their clones and code compatible boards such as the ESP32 etc fall into 2 different groups, those that run on 3.3V and those that use 5V, and you must be very careful you don't over voltage the latter.

I haven't delved into the specifications further, but you will almost certainly find that the logic levels used by the two boards are also incompatible. One will be using 0 & 5V whilst the other 0 & 3.3V. Connecting a 5V logic output to a 3.3V logic input is not conducive to long life and happiness for the latter.
> 1 votes

---
Tags: shields
---