# Question
Title: How can I run the arduino IDE 1.8.9 on debian testing as regular user?
When I start the arduino IDE as regular user from my debian testing system, I get a crash right after the splash screen:

```
Temp/arduino-1.8.9/arduino                                                              :)
Picked up JAVA_TOOL_OPTIONS:
java.lang.NullPointerException
        at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:679)
        at processing.app.Base.onBoardOrPortChange(Base.java:1317)
        at processing.app.Base$12.actionPerformed(Base.java:1544)
        at processing.app.Base.rebuildBoardsMenu(Base.java:1494)
        at processing.app.Base.<init>(Base.java:275)
        at processing.app.Base.main(Base.java:151)
Temp/arduino-1.8.9/arduino  7,28s user 0,50s system 183% cpu 4,243 total

```

When I start it with `sudo` I can use everything regularly. There are quite a few bug reports mainly in the archlinux community about a similar issue, where they suggest to install a package `arduino-avr-core` to solve it. But I assume, the reason why it happens for me, is different, since it runs fine with root privileges, and we do not have such a package in debian. Debians arduino IDE from the repos is way to old to use it these days with modern boards.

My Groups: `tty uucp dialout cdrom floppy sudo audio dip video plugdev systemd-journal netdev bluetooth lpadmin scanner docker`

The file permissions are fine for the ide and the arduino data directory.

The permissions for the usb device are also correct, just in case:`crw-rw----+ 1 root dialout 188, 0 Mai 4 11:42 /dev/ttyUSB0`

My Java environment:

```
java --version                                                                          :)
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+1-Debian-1)
OpenJDK 64-Bit Server VM (build 11.0.3+1-Debian-1, mixed mode, sharing)

```

Maybe someone ran into the same problem as well?

# Answer
It turned out, that the current Arduino IDE is using a directory `~/.arduino15` for data. I was not aware of the existence of it. The comments to my question made that clear. I tried to delete the `~/Arduino` and `~/.arduino` direcory several times, but to no avail. Deleting `~/.arduino15` indeed fixed the issue.
> 1 votes

---
Tags: arduino-ide, linux
---


title: Serial input help

text:
# Question
Title: Serial input help
Hey guys I have a LED strip with 6 LEDS (I control these through Kinect & processing. It sends 1,2,3,4,5,6 to Arduino. This seems to work fine.)

In Arduino LED0,LED1,LED2,LED3,LED4 work perfectly but the last one don't work. it doesn't light up at all.

Anyone know what's going on?

```

#include <FastLED.h>

#define LED_PIN     13
#define NUM_LEDS    6

CRGB leds[NUM_LEDS];

void setup() {

  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  Serial.begin(9600);

}

void loop() {

  if (Serial.available() > 0) {
int incomingByte = Serial.read();

  //1
if(incomingByte=='1'){
  leds[0] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}

 //2
 if(incomingByte=='1'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[1] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
  if(incomingByte=='4'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}

  //3
   if(incomingByte=='1'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[2] = CRGB(255, 0, 0);
  FastLED.show();}
   if(incomingByte=='4'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}

  //4
   if(incomingByte=='1'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
    if(incomingByte=='4'){
  leds[3] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}

  //5
   if(incomingByte=='1'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[4] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}

  //6
   if(incomingByte=='1'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();
if(incomingByte=='2'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[5] = CRGB(255, 0, 0);
  FastLED.show();}

}
  }
}

```

here's the processing code:

```
float x = 100;
float y = 50;
float w = 150;
float h = 80;

import org.openkinect.freenect.*;
import org.openkinect.processing.*;
import processing.serial.*;

// The kinect stuff is happening in another class
KinectTracker tracker;
Kinect kinect;
Serial myPort;

void setup() {
  size(512, 424);
  kinect = new Kinect(this);
  tracker = new KinectTracker();
  String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw() {

  tracker.track();
  tracker.display();

  PVector v1 = tracker.getPos();
  fill(50, 100, 250, 200);
  noStroke();
  ellipse(v1.x, v1.y, 50, 50);

   //1
    if (v1.x > 0 && v1.x < 50 ){
    println('1');
    //rect(0,200,200,200);
    myPort.write('1'); }
    //println('0'); }

    //2
  if (v1.x > 50 && v1.x < 100){
    println('2');
    myPort.write('2'); }
 //3
   if (v1.x > 100 && v1.x < 150 ){
    println('3');
    myPort.write('3'); }

    //4
   if (v1.x > 150 && v1.x < 200 ){
    println('4');
   myPort.write('4'); }

    //5
   if (v1.x > 200 && v1.x < 250 ){
    println('5');
    myPort.write('5'); }

    //6
   if (v1.x > 250 && v1.x < 300 ){
    println('6');
    myPort.write('6'); }

}

```

# Answer
> 0 votes
Your problem lies in the position of the closing bracket of the first if statement for LED 6:

```
//6
if(incomingByte=='1'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();         // here the closing bracket is missing
if(incomingByte=='2'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[5] = CRGB(255, 0, 0);
  FastLED.show();}

} // this is the missing closing bracket
  }
}

```

This means, that this whole block will only be executed, when `incomingByte` has the value `'1'`. This also means, that the last if statement will never be executed. Correct the position of the marked closing bracket and it should work.

---

Besides that, your code is a very complicated way of doing this. Why not simply switching the `incomingByte`? Also, to write less code and making it more understandable, use a function to turn all LEDs to off ("resetting" them):

```
void reset_LEDs(){
    for(int i=0;i<NUM_LEDS;i++){
        leds[i] = 0;
    }
}

void loop(){
if (Serial.available() > 0) {
    int incomingByte = Serial.read();

    switch(incomingByte){
        case '1':
            reset_LEDs();
            leds[0] = CRGB(255, 0, 0);
            break;
        case '2':
            reset_LEDs();
            leds[1] = CRGB(255, 0, 0);
            break;
        ...
    }
    FastLED.show();
}
}

```

When you stay with such easy conditions, you can even optimize more:

int incomingByte = Serial.read() - '0'; //Convert ASCII character value to decimal int value, by subtracting the ASCII value of zero

```
if(incomingByte > 0 && incomingByte <= NUM_LEDS){ //Test, if the incomingByte lies between 1 and NUM_LEDS including
    reset_LEDs();
    leds[incomingByte - 1] = CRGB(255, 0, 0); // -1 because array counting starts with 0, we start counting with 1
    FastLED.show();
}

```

For both versions, you save time, because you we only call \`FastLED.show()´ once, when a change happens, not multiple times.

---
Tags: arduino-uno, serial, led, processing-lang
---


# Question
Title: There's an error I don't know how to fix
I basically have a bread board with an rgb led and a peizo buzzer with a photocell.

I have the codes for both. If I put a code for the rgb, it works. If I put the code for the peizo, it works. Once I paste both codes onto it it says there's an error because "void setup" and "void loop" are already defined. What do I do to get both things to work?

rgb led code:

```
/*
Adafruit Arduino - Lesson 7. RGB Fader
*/
int redLEDPin = 11;
int greenLEDPin = 10;
int blueLEDPin = 9;
int redSwitchPin = 7;
int greenSwitchPin = 6;
int blueSwitchPin = 5;
int red = 0;
int blue = 0;
int green = 0;

void setup()
{
  pinMode(redLEDPin, OUTPUT);
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);
  pinMode(redSwitchPin, INPUT_PULLUP);
  pinMode(greenSwitchPin, INPUT_PULLUP);
  pinMode(blueSwitchPin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(redSwitchPin) == LOW)
  {
    red ++;
    if (red > 255) red = 0;
  }
  if (digitalRead(greenSwitchPin) == LOW)
  {
    green ++;
    if (green > 255) green = 0;
  }
  if (digitalRead(blueSwitchPin) == LOW)
  {
    blue ++;
    if (blue > 255) blue = 0;
  }
  analogWrite(redLEDPin, red);
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(10);
}

```

peizo code:

```
int speakerPin = 12;
int photocellPin = 0;

void setup()
{
}

void loop()
{
  int reading = analogRead(photocellPin);
  int pitch = 200 + reading / 4;
  tone(speakerPin, pitch);
}

```

# Answer
Putting all other possible issues aside such as pin and timing conflicts.

Rename the sketch `setup()` and `loop()` functions, for instance, `rgb_led_setup()` and `rgb_led_loop()`, and `peizo_setup()` and `peizo_loop()`, then rewrite:

```
void setup() {
  rgb_led_setup();
  peizo_setup();
}

void loop() {
  rgb_led_loop();
  peizo_loop();
}

```

Cheers!
> 2 votes

---
Tags: arduino-uno, loop
---


# Question
Title: NodeMCU burned, did I something fundamental wrong?
I have a NodeMCU where I connected a LED strip (WS2812b, which operates at 5V).

NodeMCU is powered via USB 5V. The used power adapter can supply 2.5A max.

I don't have a separate power supply for the LED strip yet, so I connected it to VIN/GND of the NodeMCU.

That worked.

Yesterday, I took the NodeMCU (without led strip) to my PC and uploaded an updated sketch. After that, back in the living room, I connected the NodeMCU with the led strip and the USB power supply. I didn't need an ambilight at the moment so I left it off. After 5 minutes, I smelled something burned. As you can see in the second image, the component below ground is burned.

I had this setup successful running for a week (with ambilight turned on for several hours) and had no issues at all.

Did I something fundamental wrong? Any guess, why it works flawless and then suddenly burned after just 5minutes?

Any tip/suggestion is very appreciated!

The white component on the right is a DHT22 temperature sensor and has been added for completeness.

The resistor and LED on the right are not used, they were just plugged in from a previous setup.

Best regards

Casper

# Answer
Yes, you did something fundamentally wrong.

The component that blew up is a diode. It is designed to protect the USB from voltage being injected into the board.

That diode can handle an absolute maximum of 1A.

Any fault on your LED strip connection (a short to ground) will cause that diode to vacate the premises. As yours did.

The purpose of the VIN pin (as the label suggests) is as a voltage *input*. It's not really designed to provide power to other devices, especially as the ESP8266 itself can take more than half that 1A power budget when communicating. You should not use VIN for powering anything more than maybe a couple of low power sensors. LED strips are a big no-no.
> 3 votes

# Answer
Something happened to me yesterday. I had made sure that the diode & regulator could handle the stress of 14 V ( this unit is installed in a voat).

The diode blew as soon as the ignition was turned on. However I noticed that the 10 uF. capacitor was still smoldering away. That should not have happened.

I removed both faulty components & tested the board. All OK! Replaced the diode and the capacitor with a 10uF/20VW diode and the board works fine with 14.4 V input (when battery is charging).

So, I reckon the prpblem is that the capacitor has insufficient voltage rating(6V?) and goes short circuit. The schotky diode will try and pass AMPS and it fails.

Solution replace the 10uF de-coupling capacitors with capacitors of known rating.

There is no real way of knowing what rating capacitors were used in the manufacture. Lee
> 1 votes

---
Tags: esp8266, usb, nodemcu, ws2812
---


# Question
Title: ESP8266 I2C datasheet pins not the same as several examples
According to espressif datasheet of the ESP8266 it uses MTMS (I2C\_SCL) and GPIO2(I2C\_SDA) for I2C.

However in several examples I've seen the typically use is GPIO(4&5) or GPIO(0&4) to connect to the I2C.
I guess all method works? but what is the real difference?

# Answer
> 2 votes
Many modules don't have the right pins for I2C available. Thus it was decided that the sensible option would be to use a bit-banged implementation of I2C using software only.

Also GPIO2 has a special meaning for booting, and using it is risky at best, and should be avoided.

Doing it 100% in software has the advantage that any pin combination can be used for I2C.

---
Tags: esp8266, i2c
---


# Question
Title: Nodemcu ESP12-E (ESP8266), Can I reprogramming when the UART pins are defined as GPIO?
I wonder if there may be any problems using the pins that the UART are using as GPIOs, if now I want to be able to reprogram the circuit? (Of course I will detach the ESP12-E from the mainboard before so)

# Answer
> 1 votes
Sure, you *can* use the UART pins as general purpose IO pins - however, it's far from ideal - for one simple reason:

* The ROM issues messages on the UART at boot time.

This means that when you power the chip up whatever is connected to the UART TX pin will receive pulses of HIGH and LOW.

That may or may not be a problem, depending on what is connected. It's something you need to bear in mind though.

---
Tags: esp8266, programming, pins, uart
---


title: how does serialEvent work?

text:
# Question
Title: how does serialEvent work?
I have come across several examples about serialEvent() function, which look like this:

```
void serialEvent(){
  if(Serial.available()){
    \\do something
  }
}

```

The serialEvent() function is called when data is available, so which is the necessity of the `if` (or `while`) structure since that would be always `true`?

*(In several cases I have excluded the `if` structure, and the code works fine)*

# Answer
> 7 votes
As far as I understand, using an if statement wouldn't make any difference, but using a while statement would.

The serialEvent() function is executed within each execution of your loop() function if there is data available, so it would be something like:

```
while (true)
{
    loop();
    if(data_available)
        serialEvent();
}

```

If you only have one byte of information in the buffer, then you wouldn't have any problem at all.

But if you want to read multiple bytes at the same time, you would have to wait until the `loop()` is executed again to read the next byte.

You will solve that problem if you write your  `serialEvent()`  like this:

```
void serialEvent()
{
    while (Serial.available())
    {
        // do something
    }
}

```

That way, you will read all the information available at once and then return to the loop.

# Answer
> 1 votes
It's a burdon how incomplete and hidden a lot of things are in the IDE of Arduino.

It took me five hours to discover how the `serialEvent()` function works for other ports (as `serialEvent2()` for the serial-port #2.

It's the same with how the function itself works. I still don't know... As an example just insert a delay in the above answer and it proves that: "That way, you will read all the information available at once and then return to the loop." is NOT true.

```
void serialEvent()
  {
    while (Serial.available())
      {
        // do something
      }
    delay(1000);
  }

```

---
Tags: serial
---


# Question
Title: My Arduino got stuck and continuous looping in if condition
I'm using RTC and when the if condition is true the Time gots stuck and the condition keeps looping. Please help

Here is my code:

```
// CONNECTIONS:
// DS1302 CLK/SCLK --> 5
// DS1302 DAT/IO --> 4
// DS1302 RST/CE --> 2
// DS1302 VCC --> 3.3v - 5v
// DS1302 GND --> GND
#include <Servo.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

ThreeWire myWire(4,5,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);
int servoPin = 3;
Servo Servo1;
void setup ()
{
    Serial.begin(57600);
    Servo1.attach(servoPin);
//    Serial.print("compiled: ");
//    Serial.print(__DATE__);
    Serial.println(__TIME__);

    Rtc.Begin();

    RtcDateTime compiled = RtcDateTime(__TIME__);
    printDateTime(compiled);
    Serial.println();

    if (Rtc.GetIsWriteProtected())
    {
        Serial.println("RTC was write protected, enabling writing now");
        Rtc.SetIsWriteProtected(false);
    }

    if (!Rtc.GetIsRunning())
    {
        Serial.println("RTC was not actively running, starting now");
        Rtc.SetIsRunning(true);
    }

    RtcDateTime now = Rtc.GetDateTime();
    if (now < compiled)
    {
        Serial.println("RTC is older than compile time!  (Updating DateTime)");
        Rtc.SetDateTime(compiled);
    }
    else if (now > compiled)
    {
        Serial.println("RTC is newer than compile time. (this is expected)");
    }
    else if (now == compiled)
    {
        Serial.println("RTC is the same as compile time! (not expected but all is fine)");
    }
}

void loop ()
{
    RtcDateTime now = Rtc.GetDateTime();

    printDateTime(now);
    Serial.println();
    delay(5000);

//here is my problem>>>>

    if(now.Hour() == 22 && now.Minute() == 40)
    {
      Servo1.write(0);
      delay(1000);
      Servo1.write(90);
      delay(1000);

    }

//////////////////////

    delay(5000);

}

#define countof(a) (sizeof(a) / sizeof(a[0]))

void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];
//%02u/%02u/%04u
    snprintf_P(datestring,
            countof(datestring),
            PSTR("%02u:%02u:%02u"),
//            dt.Month(),
//            dt.Day(),
//            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}

```

# Answer
> 2 votes
What is being brought to your attention is the following part of your code...

```
//here is my problem>>>>

if(now.Hour() == 22 && now.Minute() == 40)
{
  Servo1.write(0);
  delay(1000);
  Servo1.write(90);
  delay(1000);
}

```

In this code you use an "if" statement and ask: if the now.Hour is equal 22 AND if the now.Minute is equal 40 then write a 0 to your servo then delay for 1000 then write a 90 to your servo and wait another 1000

What is being brought to your attention is that until now.Hour changes or until now.Minute changes your write 0, delay, write 90, delay will continue on and on and on until now.Hour changes (which will take a while) or now.Minute changes. Since minutes are 60 seconds long your code will repeat for all of those 60 seconds...

If you were to change your code to include, oh, lets say now.Second() (like this)--

```
if(now.Hour() == 22 && now.Minute() == 40 && now.Second() == 00)

```

Then your code will repeat over and over until now.Second changes (which will take 1 second).

By the time your loop gets back to the "if" statement now.Second will no longer be 00 and it will not be "stuck" for you...

---

As has been brought to my attention, your 5 second delay will be a problem, so you might find that changing it will allow the now.Second "fix" to work.

In the following part of your code change delay(5000)

```
void loop ()
{
    RtcDateTime now = Rtc.GetDateTime();

    printDateTime(now);
    Serial.println();
    delay(5000);
}

```

to something like delay(1000) or so.

That way it will only wait 1 second before dropping out of the loop and checking the loop with the newly added now.Second(). This will make the printDateTime(now) happen every second instead of every 5 seconds, but it shouldn't get "stuck".

Hopefully this helps you to better understand how time (and its parts) work.

---
Tags: arduino-uno, rtc
---


# Question
Title: why sound appears between VCC and GND pins in esp8266 module?
When I use esp8266 as **STATION** mode and connect a speaker between VCC(3.3v) and GND pin a sound appears like "doop doop". what is this sound? I test this in version 01 and 12 of esp8266 module and this appear in both versions. maybe you ask me why I connect speaker to this pins. problem is that when I use pwm of esp8266 for playing a sound, this sound ("doop doop") appear to it also. What is problem? How can I fix this?

# Answer
> 0 votes
It's called "noise" and is to be expected. Wi-Fi devices are generally very electrically noisy - and the ESP8266 is no exception.

---
Tags: esp8266, wifi
---


title: Can Arduinos keep a 500mu timer?

text:
# Question
Title: Can Arduinos keep a 500mu timer?
I need to output a serial message on a 500 microsecond interval (10 bytes), can be a little slower but no more than 1 milisecond between messages.

Can it be done with an Arduino? I know there is a delayMicro(), but not sure if it has the resolution.

# Answer
It's not related to the delayMicro, but to the max speed of the Serial/UART driver, which is not documented, but according to some people it can reach 500 kbps.

However, 10 bytes, each 500 us (2000 Hz) means 10 * 11 (including some stop/start bit) * 2000 = 220.000 bits, so you have some headroom left. Maybe there is also some timing overhead.

Anyway, probably the only way to go is using an interrupt, and expect the Uno is not able to do anything else.

A better option might be to send less or send smarter (i.e. not 10 bytes, but maybe some compressed/binary form if not already thought about).
> 1 votes

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


# Question
Title: Generating variable frequency of 3 phase SPWM
I got a sample of program to generate 3 phase SPWM from this Controlling output frequency of 3 Phase SPWM Inverter. As far as I understood, the frequency generated is constant. My question is how can I make it a variable frequency generated? I am using Arduino mega right now.

# Answer
> 1 votes
I've edited the code in that post to my latest code! I suggest you take a look at the signal on proteus scope, but first try to filter all signals with 1K ohm resistor and 0.37uF capacitor connected in series. Put your scope probe at the end of resistor. Hope that will help!

---
Tags: arduino-mega
---


# Question
Title: Cannot upload to Robotdyn Mega 2560 PRO MINI?
I get this error trying to upload `avrdude: stk500v2_ReceiveMessage(): timeout`

It is Robotdyn Mega 2560 PRO MINI and a Robotdyn CH340 which I have connected like this:

I installed the CH340 drivers from here https://sparks.gogo.co.nz/ch340.html and I can see it in the device manager. Connecting the Mega 2560 Pro Mini lights up the `L` and `On` LED but when pressing upload (testing with simple examples as Blink) I get the error and neither RX or TX lights up.

I have tried everything I can think of. What am I doing wrong?

I have confirmed that it is connected to the correct COM-port and I use these settings:

```
Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

```

I have also tried many different USB-cables, short and long, and USB 2.0 and USB 3.0 ports. I use Windows 10 64-bit.

# Answer
> 1 votes
Try placing a 100nf capacitor on RST. That is usually required on an FTDI programmer.

See Edgar's post - https://arduino.stackexchange.com/users/47431/edgar

---
Tags: uploading, avrdude, error
---


title: Applying 5v to analogWrite Pin

text:
# Question
Title: Applying 5v to analogWrite Pin
I am controlling a motor with an Arduino Nano, that motor is controlled by Cytron MD-10c motor controller.

i want to wire a momentary switch in parallel with the analog output PIN from the Arduino and PWM input on the MD-10c, the switch will connect the 5v output from Arduino to the PWN input on the MD-10c. Basically an override to go full power.

Is there any risk of damage with this sort of wiring with the switch?

# Answer
Yes, depending on the current that will flow.

If your PWM output pin is connected to 5V without a current limiting resistor, nothing will happen during the `HIGH` phases of the PWM, but you will short the input pin during the `LOW` phases.

According to the manual of your motor controller, you should be able to use a current limiting resistor to prevent this. Since the ATMega328P on your Arduino Nano can sink a maximum of 40 mA, that resistor should be at least 125 Ohms. A resistor larger than 1 kOhm should work fine.

The other option would be installing a diode between your Arduino Nano and the motor controller. This does not require the use of a current limiting resistor. The motor controller would still work, since the minimal voltage for the pin state to be detected as `HIGH` is 3V (), much lower than the ~4.3V you're left with after a diode.
> 2 votes

---
Tags: arduino-nano
---


# Question
Title: One Arduino collects data, several other Arduinos use the data. What is a simple way to do this?
I am looking for a way to exchange a few bytes of data from one Arduino to two or more additional Arduinos. It's a one way communication and speed is not a problem. 10Hz is fast enough.

**Data Collector Arduino:** I have one Arduino with SPI and I2C shields which collects and analyzes data from a CAN-BUS in a motorcycle. The CAN-BUS supplies lots of information but I filter it down to few info like which lights are on, intake temperature, motor RPM, which gear.

**Light Control Arduino:** This Arduino should know which lights are on. Depending on low beam, high beam, indicators, etc. it will control additional lights which are not part of the original bike.

**Motor Control Arduino:** This Arduino should know the current RPM, gear, etc. and work with that data.

**The question is how do I "transfer" the data from the data collector to the other Arduinos?** If it would be a little simpler I would connect some digital pins which the data collector would write and the others would read. But there are not enough pins for my needs and why use 10 pins when maybe 2 are enough.

All the Arduinos use SPI and I2C connected devices so I don't think it's a good idea to use SPI or I2C for communication between the Arduios.

I guess Serial communication would work with 2 Arduinos but not with 3 or even more. Maybe I could use multiplexing or something like that?

Maybe I could let the data collector Arduino write data into some kind of shared memory and the other Arduinos could read it?

**What do you suggest? I am sure there are simple solutions out there but I didn't find anything. I don't mind any extra ICs.**

Before someone suggest to do all in one Arduino: Maybe it would be possible. But I really like to keep the modules (Arduinos) separate and I want to be able to add others later if I want to. Then I only want to change the software of the collector Arduino and don't touch the others.

# Answer
It is possible to send out data from one Arduino to multiple others at once via serial (UART). You simply connect the TX of your master Arduino to the RX of all the slave Arduinos. All receiving Arduinos will get the same data with that. You only need 1 pin (for the connection sender TX to the multiple RX). This is a bit limited to the number of slaves and the speed, but that doesn't seem to be an issue here (since you only have a few).

This is a 1-way communication, since at any line there must not be more than 1 TX (sender). If you have more than 1 TX on a line, you will burn your hardware as soon as both TX send out data simultaneously.

I remember some sites that stated it to be possible to also do multiple sender UART, when you adhere to a protocol and put in some safety hardware (I think they used diodes and current limiting resistors). But that is somewhat out of scope here. If you really need a 2-way communication, you maybe should rethink the whole structure of your solution. As Juraj suggested in his comment, it might then be easier to unite the functions to less Arduinos.

---

Be sure, that the Arduinos share the same ground. This is needed for any communication, when you don't utilize extra hardware (like an optocoupler).
> 2 votes

# Answer
You can do it simply by addition of extra RX and TX pins by use of library like Software Serial Library. For reference you can go here https://www.arduino.cc/en/Tutorial/TwoPortReceive . By using this library you can increase number of ports in master arduino and you probably can give command to other slave arduino commands through master arduino. In this way each arduino can communicate with each other.
> 0 votes

---
Tags: communication
---


# Question
Title: Connection of a DS18B20 on a Arduino pro mini
I'm actually trying to connect a DS18B20 sensor to a homemade board build with a ATmega328P processor running with a power of 3.3V and at 8 Mhz.

In order to get the address I wired the board as the following schematic on the pin 5 of my board.

To power the sensor and the pull up resistor I use the VDD output of my board which provides 3.3V.

For the code part I uploaded this:

```
// This sketch looks for 1-wire devices and
// prints their addresses (serial number) to
// the UART, in a format that is useful in Arduino sketches
// Tutorial:
// http://www.hacktronics.com/Tutorials/arduino-1-wire-address-finder.html

#include <OneWire.h>

OneWire  ds(5);  // Connect your 1-wire device to pin 5

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

void discoverOneWireDevices(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  Serial.print("Looking for 1-Wire devices...\n\r");
  while(ds.search(addr)) {
    Serial.print("\n\rFound \'1-Wire\' device with address:\n\r");
    for( i = 0; i < 8; i++) {
      Serial.print("0x");
      if (addr[i] < 16) {
        Serial.print('0');
      }
      Serial.print(addr[i], HEX);
      if (i < 7) {
        Serial.print(", ");
      }
    }
    if ( OneWire::crc8( addr, 7) != addr[7]) {
        Serial.print("CRC is not valid!\n");
        return;
    }
  }
  Serial.print("\n\r\n\rThat's it.\r\n");
  ds.reset_search();
  return;
}

void loop(void) {
  // nothing to see here
}

```

When I make it run on an Arduino Uno card I can get the address of the sensor but when I make it run on my card I only obtain this:

> Looking for 1-Wire devices...

That's it.

Anyone got a idea why it's working on an Arduino Uno but not on my card?

# Answer
> 1 votes
I finally made it work, thx @domen.

I looked at the other part of the schematic and found I was using the wrong pin - I have two LDO and the one I was using was deactivated for sensor.

Thanks all for your help.

---
Tags: sensors, arduino-pro-mini, ds18b20, 1-wire
---


# Question
Title: How to increase the serial port's data throughput
I have an array of numbers that will be subtracted from the ADC readings of a 50 Hz sine wave. Using `Serial.begin(57600);`, I can only output 25 samples per sine wave cycle, or about 1,250 samples per second. my questions are:

1. how fast the increent of array number moves with y++ in my int sinus\[\]? because when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)
2. how to increase the speed the increment of y++ in my array?

```
int sinus[] = {
    70, 72, 83, 92, 108, 132, 157, 182, 207, 230, 243, 255, 255,
    255, 250, 238, 217, 193, 169, 143, 118, 98, 88, 77, 72, 80
};
int dataSensor;
int hasil[26];
int datasensor2;
int dataBaru;
int x;
int y;
int intPin = 2;
int output;
int output2;
int toggle;
int toggle2;
int z;

void setup() {
    TCCR1A = 0b00000010;
    TCCR1B = 0b00011100;
    TCCR0A = 0;  //disable millis, delay and mciros
    TCCR0B = 0;
    ICR1 = 3200;

    Serial.begin(57600);

    pinMode(A1, INPUT);
    pinMode(A0, INPUT);
    pinMode(A2, INPUT);
    pinMode(intPin, INPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);

    attachInterrupt(0, genJeah, RISING);
}

void genJeah() {  //intrupsi rising
    y = 5;
}

void loop() {
    dataSensor = analogRead(A0);
    toggle     = digitalRead(A1);
    toggle2    = digitalRead(A2);
    dataBaru = map(dataSensor, 0, 1023, 0, 255);

    for (x = 0; x < 25; x++) {
        hasil[x] = sinus[x];
    }
    // for (x=0; x<100; x++){

    output = sinus[y] - dataBaru;
    Serial.println(output);
    y++;
    if (y > hasil[26]) {
        y = 0;
    }
}

```

# Answer
If you are looking for throughput then stop sending the ASCII conversion of numbers and just send the numbers. In other words, use `Serial.write()` rather than `Serial.print()`: you can send ~25k integers per second with a 52k baudrate.

As you are actually remapping the ADC output to a single byte, that means you can easily achieve a 48k/s throughput with this simple change.

If you are also looking for low latency please consider the USB connection is actually packet based, not stream based, which means you will receive the data in chunks, no matter how frequently you write. You can speed it up a bit flushing the channel, at the cost of throughput.
> 2 votes

# Answer
> how fast the increment of array number moves with y++ in my int sinus\[\]?

Incrementing an `int` is fast enough. Even on a slowish Uno, `y++` will take less than one microsecond to execute, so you can do it a million times per second if you want...

> when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)

Your `loop()` is doing *more* than `y++`, no it's no wonder it takes more time!

There are two slow functions there:

* `analogRead()` takes about 110 µs
* `Serial.println()` is initially fast, but once the output buffer is full, it runs at the speed of the serial port.

The limiting factor here is `Serial.println()`. You are printing 4.6 bytes on average per sample (2.6 printable characters, plus CR and LF). Each byte is worth 10 bits on the wire (one start bit, 8 data bits and one stop bit). That is 46 bits per sample at 57,600 bits per second. The ratio of these numbers gives the 1,250 samples per second you experienced.

> how to increase the speed the increment of y++ in my array?

It's very hard to answer this question because you did not explain what you are actually trying to achieve. If I naively take the question at face value, the simplest option is to just repeat `y++` several times per loop iteration:

```
y++;
y++;
y++;
y++;

```

This can obviously be optimized into

```
y += 4;

```

and the compiler may even be able to figure out this optimization by itself.

But maybe what you don't care so much about speeding up `y++`, and instead you want to process more data samples per second? If this is the case, then you can speed up the loop by speeding up the serial port:

```
Serial.begin(115200);

```

by printing only every other sample (or one sample every *N*):

```
static bool print_this_sample;
if (print_this_sample) {
    Serial.println(output);
}
print_this_sample = !print_this_sample;

```

by printing one sample every so often:

```
static uint32_t last_print_time;
if (millis() - last_print_time >= PRINT_PERIOD) {
    last_print_time += PRINT_PERIOD;
    Serial.println(output);
}

```

by printing the samples in binary (first make sure they fit in a byte):

```
Serial.write((byte) output);

```

Now, what *I* suspect, is that you actually want to get your processing synchronized with the 50 Hz mains. If this is the case, you will have to completely rethink your program, and reason about the timings: at what specific time do you want to take each sample? The Arduino timing functions (`millis()` and `micros()`) should help.

As you see, half of this answer is me making guesses about what you may want to achieve. This is a sign of a *very badly* written question. Normally it is your job to explain that in detail. Please, rewrite the question and provide all the necessary background to help us understand your project, and the difficulties you are facing.
> 0 votes

---
Tags: timers, array, speed
---


# Question
Title: Mega code not compiling on Wemos Mega board
Hi I have some code that I'm trying to port from a Mega 2560 R3 to a Wemos Mega.

```
#include "SoftPWM.h"
#include ESP8266WiFi.h

// Outputs to PWM & H bridge direction
// PWMs:
// DC_pwm, left_pwm, right_pwm = 3, 4, 5
int pwm_out[] = {3, 4, 5};
const int num_pwm = sizeof(pwm_out) / sizeof(pwm_out[0]);

// H bridge direction control:
// dc_1, dc_2, left_1, left_2, right_1, right_2 = 6, 7, 8, 9, 10, 11
int dir_pins[] = {6, 7, 8, 9, 10, 11};
const int num_dir_pins = sizeof(dir_pins) / sizeof(dir_pins[0]);

// Variable for reading pin inputs
int from_r_pi_pwm = 0;
int from_r_pi_dir = 0;

void setup() {

  // Inputs from Raspberry Pi
  Serial.begin(38400);

  // Set up PWM pins
  SoftPWMBegin();
  for (int i = 0; i < num_pwm; i++)
  {
    SoftPWMSet(pwm_out[i], 0);
  }

  // Set up H bridge direction pins
  for (int i = 0; i < num_dir_pins; i++)
  {
    pinMode(dir_pins[i], OUTPUT);
    digitalWrite(dir_pins[i], LOW);
  }
}

void loop() {

  // Check input from R Pi & send it to the H bridges
  while (Serial.available() < 2){}

  if (Serial.available()) {
      // read the incoming bytes:
      from_r_pi_dir = Serial.read();
      from_r_pi_pwm = Serial.read();
      Serial.print("Serial in: directions - ");
      Serial.print(from_r_pi_dir);
      Serial.print(" PWM - ");
      Serial.print(from_r_pi_pwm);
      Serial.println();
  }

  // Set direcions on H bridges
  for (int i = 0; i < num_dir_pins; i++)
  {
    digitalWrite(dir_pins[i], bitRead(from_r_pi_dir, i));
    Serial.print("pin ");
    Serial.print(dir_pins[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(dir_pins[i]));
    Serial.println();
  }

  // PWM to motors
  for (int i = 0; i < num_pwm; i++)
  {
    analogWrite(pwm_out[i], from_r_pi_pwm);
    Serial.print("pin ");
    Serial.print(pwm_out[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(pwm_out[i]));
    Serial.println();
  }
}

```

This compiles and runs fine on a Mega & is my go to code for setting up pwm & h bridges.

So when I was playing with WiFi I selected the Wemos R1 board from the programmer & everything worked fine but if I try that with this code I get,

```
#include <avr/io.h>
                    ^
compilation terminated.

exit status 1 Error compiling for board WeMos D1 R1.

```

So after a bit of searching I found that I should be selecting `Arduino/Genuino Mega 2560` but now the upload keeps timing out,

```
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
An error occurred while uploading the sketch

```

Anybody come across this before?

**Edit #1:** As per the comment below I tried setting DIP switches 1 & 2 ON and all the rest OFF (I also tried 1, 2, 3 & 4 ON and the rest OFF) but still the same compliation error if I select Wemos board.

If I select the Mega 2560 I get `ESP8266WiFi.h: No such file or directory` which is a new error!

# Answer
The Wemos/Mega board and IDE setup is complex and not for the faint hearted. Here is the table for the DIP switch setting:

```
1=ON  2=ON  3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (ATmega2560<->ESP8266)
1=OFF 2=OFF 3=ON  4=ON  5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=ON  8=OFF (USB<->ESP8266 (Update firmware or sketch))
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=OFF 8=OFF (USB<->ESP8266 (communication))
1=OFF 2=OFF 3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (All independent)

```

Table DIP switch Special Solution:

```
1=ON 2=ON 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <-> ATmega2560<-> ESP8266)
USB converter CH340G connect to RX0/TX0 of ATmega2560
ESP8266 connect to RX3/TX3 of ATmega25

```

https://arduino-esp8266.readthedocs.io/en/latest/index.html for ESP8266 documentation.

Set the Additional Boards URL to http://arduino.esp8266.com/stable/package\_esp8266com\_index.json in preferences

Under Tools select Board then Board Manager, then install the esp8266 by ESP8266 Community

The Arduino IDE setup requires understanding what board setting and communication setting to use to build and upload a sketch.

Under Tools select Board then select the "Arduino/Genuino Mega or Mega 2560"

Set the DIP switches on the actual board to `1=OFF 2=OFF 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)`

That was the DIP switch and USB setup.

Ref. https://forum.arduino.cc/index.php?topic=578430.0

The error `ESP8266WiFi.h: No such file or directory` is easy. The file name should be a string: `#include "ESP8266WiFi.h"`.
> 1 votes

---
Tags: arduino-mega, compilation-errors
---


# Question
Title: Can i use a sparkfun rfid qwiic without an id-xxla?
Sparkfun rfid qwiic

id-20la

I am using an Arduino UNO R3.

You should assume that i don't know anything. If yes can you give some information about how to do it? Thanks for any help.

# Answer
> 0 votes
No. It is not an RFID reader. It just interfaces to an RFID reader. You need an RFID reader to read RFID tags. That Sparkfun board just controls the reader and reads the data from it.

---
Tags: arduino-uno, arduino-ide, rfid
---


# Question
Title: Strange artifact in writing to serial while executing loop
Hope you can see this.

https://gist.github.com/DevilWAH/60ad144d2858f53845ac2e80f84bb070

The main file in this is "morse-led-rfid" which is taking reading data of an RFID tag and then displaying the text as Morse code on to a APA102 / Dotstar LED strip.

The issue is when the function updatestrip(tempbuffer\[i\]); is called.

```
Serial.println(F("\n**Start Reading**\n"));

  for (uint8_t i = 1; i < 15; i++)
  {
   if (i != 3 && i!= 7 && i != 11 && i != 15 ) // Skip the non data blocks
    {
     readblock (i, key);
       for (uint8_t i = 0; i < 16; i++)
         {
      updatestrip(tempbuffer[i]);
      Serial.write(tempbuffer[i]);
        }
    }
  }

```

This is what I am calling to scroll the LED strip and write the letter in morse. if in the code snip it above i comment out "updatestrip...." then i get the txt from the RFID tag printer to serial as i would expect.

as a soon as i un comment it, the strip displays the morse code but the serial output gets garbled, it misses letters, prints reversed "?'s" and repeats its self?

Good output = "My Bunny is the best" Bad output = "?Bunny is the ?t" (question marks reversed)

Further investigation i found if i leave it uncommented but go all the way to the bottom of the "more-strip" sheet and comment out the "else statement in the shiftLED function" the serial again displays correctly, but of course the led don't :)

```
void shiftLED() // shift all LED up 1
  {
    for(uint16_t i = ledCount; i > 0; i--)
    {

      if ((colors[i - 1].red == 0 ) && (colors[i - 1].green == 0 ))
       {
          colors[i] = cblack;
        }
      else if (i > 19 && i < 40)
      {
        colors[i] = cred;
      }
     // else
     // {
     //   colors[i] = cgreen;
     // }
     // }

 }

```

Can any one suggest why the else statement a few function down is affecting the "serial.write(tempbuffer\[i\])" in the main loop?

# Answer
In your code `colors` is declared as

```
rgb_color colors[ledCount];

```

This means that the very first iteration of this cycle in `shiftLED`

```
for (uint16_t i = ledCount; i > 0; i--)
{
  // access colors[i]
}

```

will access `ledCount[ledCount]` which is obviously out of bounds (and will actually *write* into that location!). The behavior is undefined after that.

Using unsigned types for "backward" array iteration requires a bit of skill. The common idioms are

```
for (uint16_t i = ledCount; i > 0;)
{
  --i; // do this ASAP

  // access colors[i]
}

```

or

```
for (uint16_t i = ledCount; i-- > 0;)
{
  // access colors[i]
}

```

or

```
// Careful: this technique is not usable with unsigned types
// narrower than `unsigned int`
for (uint16_t i = ledCount - 1; i != -1; --i)
{
  // access colors[i]
}

```

This is assuming that you want to iterate over the whole array: from `[ledCount - 1]` all the way back to `[0]`.

But if you intended to iterate back to `[1]` and stop short of `[0]` (which is apparently the case), then a simple fix for your cycle would be

```
for (uint16_t i = ledCount - 1; i > 0; i--)
{
  // access colors[i]
}

```

I.e. simply start from `ledCount - 1`, not from `ledCount`.
> 2 votes

---
Tags: serial, rgb-led, led-strip, functions
---


# Question
Title: Motor isnt spinning when using L298N motor controller
I have a L298 motor controller connected to a motor with a 6 volt power sources. the motor however isn't spinning any ideas I'm using a esp 8266 node mcu board. I would like to use pwm but for right now I'm just trying to get it to work so I disabled the pwm.

```
//int d0 = 16;
const int d0 = 16;
const int d4 = 2;

//=======================================================================
//                    Power on setup
//=======================================================================
void setup() {
  Serial.begin(115200);
  pinMode(d0,OUTPUT);
  //pinMode(d1,OUTPUT);
  pinMode(d4,OUTPUT);
}

//=======================================================================
//                    Main Program Loop
//=======================================================================
void loop() {
  //PWM Value varries from 0 to 1023
  Serial.println("10 % PWM");
  //analogWrite(d0,102);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("20 % PWM");
  //analogWrite(d0,205);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("40 % PWM");
  //analogWrite(d0,410);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("70 % PWM");
  //analogWrite(d0,714);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("100 % PWM");
  //analogWrite(d0,1024);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

}

```

# Answer
> 2 votes
You need two supply voltages for this board to work: motor supply, which goes directly to your motor (up to 35V for this L298N board, depends on what your motor needs), and logic supply of 5V, which powers the board's logic chips. If the motor supply voltage is between 7V and 12V, you can derive 5V logic supply from motor supply by enabling this board's built-in linear regulator.

* The actual motor power supply should be connected to the `VCC` terminal of the L298N board you have in your picture. This is the **leftmost** terminal in the block of 3 in the picture (sometimes it is labeled `+12V` instead of `VCC`). In your case it is not connected to anything at all. This is already wrong.
* It is not clear what the purpose of the red wire is in your picture.

In your comments you mention different voltages of motor power supply (6V in one place, 9V in another...). If you are feeding this board 9V through the red wire, you are doing it wrong. The rightmost terminal in the block of 3 is the `5V` pin. Don't attempt to feed more than 5V to that pin.

If you'll be using the red wire to supply 5V logic power **to** the L298N board from an external source, then you need to disable this board's own linear regulator - remove the jumper that is shown above the 3-terminal block.

If you'll decide to use it to supply 5V logic power **from** the L298N board (e.g. to your Arduino), then you have to keep the jumper.

In any case, the leftmost terminal has to be connected to motor power supply.

---
Tags: esp8266, nodemcu, hardware, software, l298n
---


# Question
Title: Restoring all fuse bits on AtMega328P-PU
I'm worked with Low Fuse bits in AVRDUDEPROG 3.3. Fuses was non-inverted. And by mistake I enabled SUT1 and SUT0, when SUT0 was enabled. And when I programmed avr, it shows me error that avrdude.exe: initialization failed, rc=-1. I have read I can restore it with Avr Fuse Doctor, but I can't buy or make with pcb. Can I recover avr with:

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

int main(void) {
    DDRB = 0xFF;
    while(1) {
        PORTB ^= 0xFF;
    }
}

```

and load it to another avr and connect it to broken avr?

Can I make doctor on breadboard or Can I do it with usbasp/isp?

Can I load a new bootloader in it?

# Answer
The following is from: https://www.allaboutcircuits.com/projects/atmega328p-fuse-bits-and-an-external-crystal-oscillator/

"The two bits to be avoided unless you are absolutely certain you know what you are doing are bit7, the RSTDISBL (external reset disable) bit and bit 5, the SPIEN (Serial Peripheral Interface Enable) bit. Disabling either one is often the cause for "bricked" Atmel µCs; "leave them alone" is good advice."

According to the article SUT0 and SUT1 are clock start up time related bits. It doesn't seem as though it is necessary to use anything special to change them.

You will find the information at the website very usefu. I know I have.

The High Voltage (other names too) programmer you have mentioned should not be necessary if you only changed the SUT0 and SUT1 fuses.

HOWEVER, if you did change the SPIEN or RSTDISBL fuses, you should either get one of the special programmers or just purchase another 328P microprocessor.

If you search the internet for "AVR High Voltage programmer" you will find many ideas for how to build one.

This link :https://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer/71 provides good information.
> 1 votes

---
Tags: avr, avrdude, fuses, error
---


title: Why my servo motor is always on?

text:
# Question
Title: Why my servo motor is always on?
Why my servo motor is always on?

```
#include <Servo.h>

Servo myservo;

int pos = 0;

void setup() {

pinMode(2, INPUT);
myservo.attach(9);

}

void loop() {

  if (digitalRead(2) == LOW) {

    for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(15);
    }

    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(15);
    }
  }
  else {
    myservo.write(0);
    delay(15);
  }
}

```

# Answer
> 1 votes
It looks like you need to enable the pull-up resistor on D2. As written D2 is left floating and most likely is a low voltage relative to ground. Enabling the pull up resistor will force the pin high until you flip the switch.

---
Tags: servo, button
---


# Question
Title: MXCHIP IoT DevKit too many initializers for 'unsigned char [0]
**Question**

Trying to call the Display `draw` API using the sample code for the azure logo bitmap sample code. I'm unable to reach a point where I can the API because breaks when constructing the bitmap char arrays in my `BMPManager` class. I'm also testing custom bitmaps using this pixelcraft tool.

> In file included from /Users/gregorydegruy/Code/GitHub/\_mr.u/mxchip/Main.ino:5:0: sketch/srcsrc/BMPManager.cpp:4:2371: error: too many initializers for 'unsigned char \[0\]' unsigned char AzureBMP\[\] = {0,0,0,0,0,0,0,0,0,0,0,0, . . .

**Main**

```
void loop()
{
    Screen.print("start prgm...");
    delay(1000);
    Screen.draw(0, 0, 128, 8, bitMapManager.get_azure_bitmap());
    delay(5000);
    Screen.draw(0, 0, 128, 8, bitMapManager.get_nintendo_bitmap());
}

```

**BMPManager**

```
class BMPManager
{
    private:
        unsigned char AzureBMP[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,192,192,224,240,56,12,192,240,224,192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,224,224,224,224,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,224,248,252,254,255,255,63,15,3,64,248,254,255,255,255,255,255,252,248,224,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,240,252,127,31,3,3,15,127,254,240,192,0,0,0,0,8,28,28,28,28,156,220,252,124,60,28,0,0,0,252,252,248,0,0,0,0,0,0,252,252,248,0,0,0,0,252,252,252,112,56,28,28,28,0,128,224,240,248,28,28,12,12,28,248,248,240,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,224,248,252,255,255,255,255,63,15,3,0,0,0,0,0,0,3,7,15,31,63,127,255,255,255,255,255,252,240,224,128,0,0,0,0,0,0,64,112,124,127,31,7,7,7,7,7,7,7,7,31,127,126,120,64,0,96,112,120,126,127,103,99,97,96,96,96,0,0,0,63,127,127,240,224,224,96,96,56,127,127,127,0,0,0,0,127,127,127,0,0,0,0,0,0,15,63,127,123,243,227,227,227,227,99,99,35,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,8,8,8,8,8,12,12,12,12,12,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        unsigned char NintendoSwitchBMP[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, 0xc0,0xc0,0xe0,0xe0,0xf0,0xf0,0xf8,0xf8, 0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8, 0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8, 0x00,0x00,0x00,0x00,0xf8,0xf8,0xf8,0xf8, 0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8, 0xf8,0xf8,0xf0,0xf0,0xe0,0xe0,0xc0,0xc0, 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xc0,0xf0,0xfc,0xff,0xff, 0xff,0xff,0x7f,0x1f,0x0f,0x07,0x87,0x83, 0x83,0x81,0x81,0x81,0x81,0x81,0x01,0x01, 0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xfc,0xf0,0x80,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0x0f,0x00,0x00,0xfe,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x78, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xc0,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0x00,0x00,0x00,0x00,0x01,0x03,0x03, 0x07,0x07,0x07,0x07,0x03,0x03,0x01,0x00, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x7f,0x3f,0x3f, 0x3f,0x3f,0x7f,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xf1,0xc0,0x80,0x80,0x00, 0x00,0x80,0xc0,0xc0,0xf1,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xf0,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x01,0x0f,0x1f,0xff,0xff, 0xff,0xff,0xfe,0xf8,0xe0,0xe0,0xe0,0xc0, 0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0, 0x80,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0x01,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0x1f,0x0f,0x01,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01, 0x03,0x03,0x03,0x07,0x0f,0x0f,0x0f,0x1f, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x00,0x00,0x00,0x00,0x1f,0x1f,0x1f,0x1f, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x1f,0x0f,0x0f,0x0f,0x07,0x03,0x03,0x03, 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};

    public:
        BMPManager() {}
        unsigned char* get_azure_bitmap() {
            return AzureBMP;
        }
        unsigned char* get_nintendo_bitmap() {
            return NintendoSwitchBMP;
        }
};

```

# Answer
> 1 votes
In C++ you are not allowed to declare non-static member arrays with unspecified size (empty `[]`). Supplying an in-class *brace-or-equal* (BoE) initializer for such non-static member array does not override this rule

```
struct S
{
  int a[] = { 1, 2, 3 }; // <-- ERROR: `[]` array declaration is not allowed here
};

```

If you really need these arrays as *non-static* members of the class, you will have to explicitly specify their size (which is `1024` in your case). Once you do that, you will also be able to BoE initializers for them right inside the class definition

```
class BMPManager
{
private:
  unsigned char AzureBMP[1024] = { /* whatever */ };
  unsigned char NintendoSwitchBMP[1024] = { /* whatever */ };
  ...
};

```

The `=` is optional.

---

However, the real question in this case is whether you really need these arrays as non-static (and non-const) members of the class. Do you really need independent instances of these arrays in each instance of `BMPManager` class? Are these arrays supposed to be modifiable?

If you really need independent instances of such arrays in each object, then you will have to do what's shown above.

But if you don't need independent arrays in each object (which would probably also imply that the arrays are not supposed to change) then the proper way to go about it would be to declare them as `static` members

```
class BMPManager
{
private:
  static unsigned char AzureBMP[];          // static const ?
  static unsigned char NintendoSwitchBMP[]; // static const ?
  ...
};

```

and then define them in one of the `.cpp` files as

```
unsigned char BMPManager::AzureBMP[] = { /* whatever */ };
unsigned char BMPManager::NintendoSwitchBMP[] = { /* whatever */ };

```

Note that in this case you will not be able to use BoE initializers directly in class definition. The initializers are supplied at the point of static member definition in `.cpp` file.

This can be done much more compactly in C++17, but I'd guess that you are using Arduino IDE, which still sticks to C++11.

---

Also, make them `const`, if appropriate.

Looking at the documentation at IoT DevKit web site you linked I see that it contains a number of ridiculous typos making it almost unusable. It is quite possible that you will run into problems with their library if you properly use const-correctness in your code.

---
Tags: arduino-uno, iot, bit
---


# Question
Title: LCD Display 128x64 weird pin, C86 (input)
I got some LCD display from my friend. Base on the model number (TopWay LM6023) printed on product, I found the data sheet from google. According to the datasheet, it is a 128\*64 LCD display, but I am confusing the pin out does not same/similar to the famous one. I read the datasheet, there are C86 pin. I have no idea what’s that, and how to make it work. I created a github repo, I am wonder if someone could help to write an example code and wiring to Arduino UNO.

Moreover, I also would like to know what is 6800 & 8080 interface, is it Arduino UNO can simulate ? If yes, any reference?

# Answer
> 1 votes
Unfortunately driving a graphic LCD is not as easy as driving one of the most popular type HD44780 LCD's.
Back to the subject:
If the state on this pin is HIGH then you shall use Motorola's 6800 interface, when state on C86 is LOW, use Intel's 8080 interface.
Depending on your selection you would have to keep the communication standard. For 8080 interface refer to point 3.3.1 of you datasheet, for 6800 see point 3.3.2.
Note: If you are struggling, try to search for the libraries using controller's name: LM6023A or one of the S1D15300 or S1D16700
Also, consider number of pins available on your Arduino. It may be that you can drive this LCD with Arduino Uno using serial interface only. (See this link)

---
Tags: lcd
---


title: Is new without a delete acceptable?

text:
# Question
Title: Is new without a delete acceptable?
I know it is not a good practice to use the `new` command to dynamically create data, however, if I would never use the `delete`, would it result in memory gaps/other problems?

**Background**

The reason I need to create instances dynamically, is that I want to test my application first on a PC. And I want for several classes to have more properties for the PC version than for the Arduino version (for example, to store names, or information for the PC GUI to display). The PC version classes will be inherited from the Arduino (real) classes, but with added properties.

In some classes I need to build up a list, and I cannot use a type with hardcoded values to fill an array.

Example:

I have a LightSetup class that has a list of Pars (which are LED lights):

```
class LightSetup
{
protected:
    Par* _pars[NR_OF_PARS];

```

Par is the Arduino/real version, to fill in these I need:

```
LightSetup::LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        _pars[n] = new Par(1 + 8 * n);
    }
}

```

In the PC version, instead of new Par, I use new TestPar. And in the header I cannot define it without a pointer like this:

```
    Par _pars[NR_OF_PARS];

```

Otherwise it cannot contain TestPar instances.

# Answer
Sure. Using `new` or `malloc` to set things up initially is really no different to static allocations. There is nothing inherently bad with using `malloc` or `new`, only in using it repeatedly with `free` or `delete`.

Allocating a block of heap memory and keeping it allocated for the rest of eternity does not cause heap fragmentation. It's only repeated allocation and deallocation of variable sizes (such as `String` causes) that start to create problems. Allocating at the start of your program and leaving it allocated, as long as you don't allocate *too much*, of course, is not a problem.
> 2 votes

# Answer
In the destructor you would need

```
LightSetup::~LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        delete _pars[n];
    }
}

```

and every time you replace a \_pars you need to delete the old one. This can be done automatically by using unique\_ptr.

However for your purpose it sounds like a `#if` is better suited to differentiate at compile time which type you actually store inside that array.

```
#if ON_ARDUINO
    Par _pars[NR_OF_PARS];
#else
    TestPar _pars[NR_OF_PARS];
#endif

```
> 3 votes

---
Tags: programming, memory-usage, memory
---


# Question
Title: Arduino Uno unable to detect serial port on MAC os Mojave 10.14.2
Ive upgraded to Mojave. I've never used Arduino before. I was given Arduino Uno. Arduino Uno does not find any serial ports... can't load Blink example (the first step)

In blind frustration, I tried the three ports available... None of work.

I've loaded the CH34x\_Install\_V1.4.pkg to no avail.

How do I get a serial port package that will enable serial ports in general (and more importantly for arduino)

thx, Bruce On a related Note: the list of things that Mojave broke is long! To solve many problems, re-install xcode FIRST!!! and read articles on apache, there is a "new and improve" apache server embedded in mojave.

# Answer
> 2 votes
If you are using a genuino or genuine Arduino, the most common cause of this is using a USB *power only* cable to connect rather than a data cable. (You only need the CH34x\_Install\_V1.4.pkg if you are running an Arduino clone based on that chipset)

If I ran the world, the USB standard would include some way to distinguish whether it's power only or power and data without having to test it with a multimeter. I know, I know, that's crazy talk.

---
Tags: arduino-uno, mac-os
---


# Question
Title: Is code in a class repeated for each instance?
I haven't needed classes before in programming for Arduino, but I now have a good use case. I'm not sure I grasp how this will affect code space, though.

Currently I have a struct that holds the properties of an object, and common code that iterates over an array of 12 of that struct. It's fairly compact.

It would be cleaner to wrap the operations on the struct in a class and act on an array of 12 of that class. Essentially the current struct would become private data of the class.

Will all the code in the class be repeated in each instance, or is the compiler clever enough to avoid such repetition?

Any clarifications welcome. C++ is not my main language.

# Answer
No, it is not repeated. Unless you are using templates, each method of each class is stored only once in the compiled program. Or even not stored at all if the optimizer notices it is not used.

Just to demystify the classes a bit, you can consider them as a kind of “syntactic sugar” over an “object oriented” programming pattern. The following C++ code:

```
class MyClass {
public:
    int aMember;
    long anotherMember;
    int aMethod(short);
};

int MyClass::aMethod(short theParameter)
{
    return aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    objects[1].aMethod(42);
}

```

is interpreted by the compiler as being roughly equivalent to this C code:

```
typedef struct {
    int aMember;
    long anotherMember;
} MyClass;

int MyClass_aMethod(MyClass *this, short theParameter)
{
    return this->aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    MyClass_aMethod(&objects[1], 42);
}

```

Can you spot the differences and the similarities?
> 1 votes

# Answer
No, the code is not repeated for each instance. Instance methods are like functions. There is only one copy of the code.

There's a dispatch table that maps method calls to their implementations. (Actually, that's standard C++. I don't know for sure how it's implemented in the Arduino C++ compiler)
> 1 votes

---
Tags: class, struct
---


title: AnalogWrite problem

text:
# Question
Title: AnalogWrite problem
I have connected DRV8835 with 2 DC motors with 11 power supply. Arduino nano.

When I for loop like i from 0 to 1024 for analogWrite(i,Motor1) for the DC Motor1 it's accelerating from 0 to 200 and it's stopping. When I becomes 250 it's starting at higher speed. When it becomes 500 it's stopping again. And 550 we have our power again.

Now I tried to run analogWrite(1000, \***) but it's not working. When I change the value from 1000 to 1005 it's not working again. But at 1024 we have the maximum speed and it is working?

```
 #define LEFT_PWM 9
 #define RIGHT_PWM 10
 #define LEFT_DIR 5
 #define RIGHT_DIR 6

void setup() {
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(LEFT_DIR, HIGH);
  analogWrite(LEFT_PWM, 1000);
}

```

# Answer
> 1 votes
`analogWrite` has the following prototype

```
void analogWrite(uint8_t, int);

```

which means that its first parameter has `[0, 256)` range and follows the rules of modulo arithmetic, with `256` as the modulo. If you supply arguments outside of `[0, 256)` range, they will be interpreted `% 256`. `1000` is the same as `232` (`1000 % 256 == 232`), `500` is the same as `244`, `550` is the same as `38` and so on.

This is not fully consistent with the symptoms you describe (if your description is accurate), which might imply that something else is a factor here. Are sure you are using your DRV8835 in `PHASE/ENABLE` mode (pin 11 pulled high)?

---
Tags: analogwrite
---


title: HC-05 connecting to Arduino

text:
# Question
Title: HC-05 connecting to Arduino
I have been looking through StackExchange, and searching on the web and cannot find an answer to my issue.

Setup: Arduino Nano 168 HC-05 VERSION:3.0-20170601

I am trying to connect my Android phone to my Nano to control an output. I have found tons of varying examples, but they all basically boil down to MIT App Inventor to create app to connect via BT and send data to the Nano to control.

After many attempts with no results, I attempted the following:

```
#include <SoftwareSerial.h>

int light=8;
int Received=0;
int light_state =0;

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup(){

  Serial.begin(38400);
  pinMode(light,OUTPUT);
  BTSerial.begin(38400);

}

void loop(){
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.write(BTSerial.read());
 }

 if(BTSerial.available()>0) {
    Received = BTSerial.read();
 }

if (light_state == 0 && Received == '1') {
    digitalWrite(light,HIGH);
    light_state=1;
    Received=0;
  }
if (light_state ==1 && Received == '1') {
    digitalWrite(light,LOW);
    light_state=0;
    Received=0;
  }
}

```

So, when I run the MIT app on my phone to connect to the HC-05 the status LED on the HC-05 changes. Before I connect, the status LED flashes fast. After I connect, it flashes slow.

I have the serial monitor open on my laptop monitoring the Nano. The HC-05 connects via pins 10 & 11. When the phone connects to the HC-05, the data printed on the serial monitor is garbage.

⸮x⸮x⸮⸮x⸮x⸮x⸮⸮xxxxxx⸮x⸮⸮xx⸮⸮xxx⸮⸮

That is what I get.

The app is set to transmit a "1" via BT to the Nano. When I press the button to send the 1, no data comes across. But every time I pick the HC-05 and tell the app to connect to the unit, I get that same string of data above.

Thank you in advance for your help.

# Answer
This issue has been resolved. There was an issue with the parity and stop bits.

When setting up for arduino comms, remember, baud rate, 1 stop bit, 0 parity bits.
> 1 votes

---
Tags: arduino-nano, bluetooth, hc-05, android
---


# Question
Title: Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature
I'm trying to program an Attiny85 chip using an Arduino Uno as an ISP following this two tutorials: Instructables: Program an ATtiny With Arduino and Programming an ATtiny w/ Arduino 1.6 (or 1.0) but every time I try to upload the sketch I get this error message:

```
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

```

I have tried different Arduino boards/changing port and different ATtiny chips but the results are all the same. I have also checked the wiring multiple times and it seems to be correct.

This is the full error message (on verbose mode):

```
     avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM7
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATtiny85
     Chip Erase delay              : 400000 us
     PAGEL                         : P00
     BS2                           : P00
     RESET disposition             : possible i/o
     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    12     4    0 no        512    4      0  4000  4500 0xff 0xff
       flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          2    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

     avrdude: AVR device initialized and ready to accept instructions

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

     avrdude done.  Thank you.

```

# Answer
> 1 votes
Try connecting the RESET pin of the Attiny85 to GND the second before you hit "program".

In my experience, the Arduino does not always send the RESET signal when it should (or on the pin that you think it would send it).

In these cases, manually resetting the Attiny by connecting the RESET pin to ground makes it programmable.

You can keep RESET low during the whole programming process, but if you keep it low for many minutes before programming the chip, it might not always work. In those cases, set RESET high for a moment before setting it back low, and the Attiny should be good for another round of programming.

And of course, when you want the Attiny to start doing what you have programmed it to do, you have to pull RESET high again.

# Answer
> -1 votes
This error (in particular the `0x000000`) *usually*, but not always, means that the ATtiny has the fuses set for an external oscillation, but there is no functioning oscillator:

```
avrdude: Device signature = 0x000000

```

You probably need to add an external oscillator, i.e. a 16 MHz crystal, and a couple of 22 pF ceramic capacitors:

However, as this Engbedded Atmel AVR® Fuse Calculator shows, there are a number of permutations that could be set:

So, instead of using a crystal, you may need to provide an external clock:

These schematics come from What's the schematic to share one crystal with two micros?

---
Tags: arduino-uno, attiny
---


# Question
Title: I want my arduino mega to read from all 4 serial ports at the same time, running sequentially through each one
I currently have the code running through Serial1, which works exactly as I want it to:

```
int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
  Serial.println("Arduino is ready");
}

void loop(){

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.print("Reader 1: "); //read out any unknown tag
  Serial.println(tagString1);

  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

```

However, I want to add serial0, 2, and 3 as well. there are 2 main questions I have 1) is it possible to have copy paste this section of the code:

```
    while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.print("Reader 1: "); //read out any unknown tag
  Serial.println(tagString1);

  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
}

```

while changing some of the variable names to connect the other serial ports? I saw something here, but don't know how to implement it, or if it even would work for me.

and 2) since I am routing the incoming data through serial0, Is it possible to have this code working on it as well?

# Answer
> 3 votes
The Arduino already reads from the 4 serial ports at the same time. Or at least as close to “at the same time” as possible with a single CPU: every time a byte is received at one port, an interrupt is triggered that reads the byte from the UART and puts it into a buffer. You can then get it from the buffer using `Serial.read()`.

What you now have to do is move the bytes from these buffers (which belong to the Arduino hardware serial library) into you own buffers for further processing. You can do this by checking the ports sequentially and processing each one in turn. Everything will be fine as long as you do not have blocking code in there. If you do block, then you run the risk of having one of the library buffers overflow. The code you posted is non-blocking, so you are fine.

> is it possible to have copy paste

You should avoid programming by copy-and-paste. It's not that it won't work (it will), but you would be creating a maintenance nightmare. Instead, put the code you would want to copy-paste into a function, and call that function as many times as required. For example:

```
void handlePort(Stream &port, const char *readerName, char *tagString)
{
    boolean reading1 = false;
    while (port.available() > 0) {
        int readByte1 = port.read(); //read next available byte

        if (readByte1 == 2) reading1 = true;
        if (readByte1 == 3) reading1 = false;
        if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
            tagString[index] = readByte1;
            index++;
        }
    }
    Serial.print(readerName); //read out any unknown tag
    Serial.print(": ");
    Serial.println(tagString);

    clearTag(tagString); //Clear the char of all value
    resetReader(); //reset the RFID reader
    }
}

```

And you call it in `loop()`:

```
handlePort(Serial1, "Reader 1", tagString1);
handlePort(Serial2, "Reader 2", tagString2);
...

```

---
Tags: serial, arduino-mega, uart
---


title: Morse Interpreter-Microphone Problem

text:
# Question
Title: Morse Interpreter-Microphone Problem
I am working on a morse interpreter. I can now use light-sensor and a regular key as input device and want to add a mic to the system. I recieve the input convert it to text and show it on nokia 5110 lcd. And also whilst input, an led and a buzzer turns on and off simultaneously. When I use mic the led works just as it should but I do not get any correct input to the lcd. I attached Out and Gnd pins of mic just as I would attach the key and vcc to 5v.

The following is the code which I use

```
#define RST 12
#define CE  11
#define DC  10
#define DIN  9
#define CLK  8

#include "font.h";

unsigned long signal_len,t1,t2; //time for which button is pressed
int inputPin=2; //input pin for push button
int ledPin=4; //output pin for LED
String code=""; //string in which one alphabet is stored

void LcdWriteString(char *characters){
  while(*characters) LcdWriteCharacter(*characters++);
}

void LcdWriteCharacter(char character){
for(int i=0;i<5;i++) LcdWriteData(ASCII[character-0x20][i]);
LcdWriteData(0x00);
}
void LcdWriteData(byte dat)
{
  digitalWrite(DC, HIGH); //DC pin is low for commands
  digitalWrite(CE, LOW);
  shiftOut(DIN, CLK, MSBFIRST, dat); //transmit serial data
  digitalWrite(CE, HIGH);
}
void LcdWriteCmd(byte cmd)
{
  digitalWrite(DC, LOW); //DC pin is low for commands
  digitalWrite(CE, LOW);
  shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
  digitalWrite(CE, HIGH);

}
void setup()

{
  Serial.begin(9600);
  pinMode(inputPin, INPUT_PULLUP); //internal pullup resistor is used to simplify the circuit
  pinMode(ledPin,OUTPUT);

    pinMode(RST, OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(DC, OUTPUT);
  pinMode(DIN, OUTPUT);
  pinMode(CLK, OUTPUT);
  digitalWrite(RST, LOW);
  digitalWrite(RST, HIGH);

  LcdWriteCmd(0x21);  // LCD extended commands
  LcdWriteCmd(0xA9);  // set LCD Vop (contrast)
  LcdWriteCmd(0x04);  // set temp coefficent
  LcdWriteCmd(0x14);  // LCD bias mode 1:40
  LcdWriteCmd(0x20);  // LCD basic commands
  LcdWriteCmd(0x0C);  // LCD normal video

  for(int i=0;i<504;i++)LcdWriteData(0x00);
}

void loop()
{
NextDotDash:
  while (digitalRead(inputPin) == HIGH) {}
  t1 = millis();                            //time at button press
  digitalWrite(ledPin, HIGH);               //LED on while button pressed
  while (digitalRead(inputPin) == LOW) {}
  t2 = millis();                            //time at button release
  digitalWrite(ledPin, LOW);                //LED off on button release
  signal_len = t2 - t1;                     //time for which button is pressed
  if (signal_len > 50)                      //to account for switch debouncing
  {
    code += readio();                       //function to read dot or dash
  }
  while ((millis() - t2) < 500)           //if time between button press greater than 0.5sec, skip loop and go to next alphabet
  {
    if (digitalRead(inputPin) == LOW)
    {
      goto NextDotDash;
    }
  }
  convertor();                          //function to decipher code into alphabet
}
char readio()
{
  if (signal_len < 150 && signal_len > 20)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (signal_len > 150)
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}
void convertor()
{
  static String letters[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                             ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "E"
                            };
  int i = 0;
  if (code == ".-.-.-")
  {
    Serial.print(".");        //for break
    LcdWriteCharacter(".");
  }
  else
  {
    while (letters[i] != "E")  //loop for comparing input code with letters array
    {
      if (letters[i] == code)
      {
        Serial.print(char('A' + i));
        LcdWriteCharacter(char('A' + i));
        break;
      }
      i++;
    }
    if (letters[i] == "E")
    {
      Serial.println("");  //if input code doesn't match any letter, error
      LcdWriteCharacter("");
    }
  }
  code = "";                            //reset code to blank string
}

```

# Answer
> I attached Out and Gnd pins of mic just as I would attach the key and vcc to 5v.

This can't work. Unlike the key, the microphone is an analog device that will output a continuously varying analog signal. If you expose it to a pure tone it will output a sine wave. If you sing a note in front of it, it will pick not only the sine but also a lot of harmonics. In any case, it will also pick the ambient noise.

What you need to do is somehow determine the amplitude of the sound signal, then compare that to some threshold in order to decide whether the amplitude is high enough to be considered “on”. You could use a diode-based peak detector and a comparator. Doing all this in code is kind of tricky. You may want to take a look at this sound-level meter sketch, but note that a software peak detection could be simpler than the true-RMS intensity detection implemented in that sketch.
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: Arduino Nano and SIM800L on Battery Power
I'm very new to Arduino and everything related but I'm highly interested to learn more. However, I've run into a problem right in the beginning.

I want to build some sort of portable emergency/notification button. One pushes the button and an SMS is sent or an HTTP call made to a server. I want to base this project on the Arduino Nano as it's quite small and therefore easily transportable. To have GSM/GPRS connectivity I found the SIM800L which seems quite suitable to what I have in mind. Now to the big question, how to power the Arduino Nano as well as the SIM800L on an portable power source, preferrably only one power source. From my understanding, the SIM800L requires a peak current of 2A when doing handshakes and sending signals. Is there any way I can power the SIM800L through the Arduino Nano, like Battery -\> Arduino Nano -\> SIM800L, or do I need to connect both the Arduino Nano and the SIM800L to the battery? Regarding the lifespan, for now it would be sufficient if I could press the button a few times and afterwards it'd stop working.

# Answer
Check out

> Thin battery to power arduino micro with nRF8001?

Also, I found a 6v battery (A544) at Menards that is about the same diameter as a AA, but is considerably shorter. It has 178 mAh capacity.

I haven't taken the time to test it, but I would guess it wouldn't have as much of a temperature issue.

It's not as small as the CR2032 in the above mentioned link, nor is it flat, but it's an option.

You might consider an Arduino Beetle. They are really super incredibly tiny and still 16mHz. I can't get any more info from where I'm at, but I'd believe they would use even less power than a Nano/Micro.

I found an Instructable that shows how to use a Beetle, a rechargeable 3.7v LiPo battery, and an HC-06 Bluetooth module. Sounds like it's equivalent to what you're looking for.

http://www.instructables.com/id/Beetle-Minimize-Your-Arduino-Projects/
> 1 votes

# Answer
I did use a big electrolytic polarized capacitor in parallel with the sim800l power pins (like 470uF 16v) on an uno. It will handle the power on peak :)
> 0 votes

# Answer
When you are using a Arduino nano for your project you wont be able get the 2A current draw form the board.You have to use a external power source like a battery.You have to find a better battery with a considerable Ahs.
> 0 votes

---
Tags: power, arduino-nano, gsm, battery
---


title: Using Servo on Timer3 on a Leonardo

text:
# Question
Title: Using Servo on Timer3 on a Leonardo
I would like to use the Radiohead library and control a servo from the same Leonardo board.

Now the Radiohead library occupies `timer1` and therefore cant be used together with the `servo` library. (It does offer to use `timer2` which the Leonardo does not have.)

Are there any other Servo libraries that use `timer3` or `timer4` which the Leonardo has?

I have already tried:

# Answer
> 1 votes
I wonder if you could use this PWM version of the Servo library written for the Arduino MEGA? Looking at the code, it looks like you would have to remove the "else if (pin == 44)" and "else if (pin == 45)" blocks of code in the attach() and detach() functions in Update Servo\_Hardware\_PWM.cpp. Just guessing here. I haven't tried it out.

https://github.com/dadul96/Arduino-Servo-Hardware-PWM-Library

# Answer
> 1 votes
You could try manually sending the servo pulses with something like:

```
digitalWrite(SERVOPIN,HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(SERVOPIN,LOW);

```

As long as the duration of the pulses is consistent, it doesn't matter if they don't occur regularly.

Downsides will be that there may be jitter if there are interrupts running, although there is the advantage that this will work on just about any pin.

If you are looking for a simple proof of concept, this may enough to test it out.

# Answer
> 1 votes
In file `ServoTimers.h`in standard Arduino Servo library change the timer

```
#elif defined(__AVR_ATmega32U4__)
#define _useTimer3
typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t;

```

on Windows the file `ServoTimers.h` is located in `C:\Program Files (x86)\Arduino\libraries\Servo\src\avr`

---
Tags: servo, pwm, arduino-leonardo
---


# Question
Title: Serial.available is working only for the first time
I am working on RFID. I am sending data through serial monitor and the Serial.available is not identifying the data after the first time, its working perfectly fine only once after reopening the comport.

I have tried all the possible changes I could do in the code. I want that when I run this code, then after entering the data in serial monitor it should show "Scan the mifare card" and after scanning the card it should perform read or write action.

```
#include <SPI.h>//include the SPI bus library
#include <MFRC522.h>//include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 9 //reset pin
MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
MFRC522::MIFARE_Key key;//create a MIFARE_Key struct named 'key', which will hold the card information

void setup()
 {
        Serial.begin(9600);        // Initialize serial communications with the PC
        SPI.begin();               // Init SPI bus
        mfrc522.PCD_Init();
        //while (! Serial); // Wait untilSerial is ready - Leonardo
        //Serial.println("Enter data");
 }

String incomingStr;
byte blockcontent[16];
int count=0;
String arr2[6];
int arr3[6];
int u2=0;
String arr[16];
int arr1[16];
int u=0;
int y;
char action;
//int newc=0;

void loop()
{
 // Serial.println("bahar");
  if (Serial.available())
    {
      doReceive();
      int newc=0;
      while(newc==0)
       {
         if ( ! mfrc522.PICC_IsNewCardPresent())
            {
               if(count==0)
                   {
                       Serial.println("Scan your mifare card %");
                       count++;
                   }
            }
        else
            {
               newc=1;
            }
       }

     if ( ! mfrc522.PICC_ReadCardSerial())
       {
         return;
       }
     if(action=='%')
       {
         doWrite();
       }
     else if(action=='$')
       {
         doRead();
       }
     else if(action=='^')
       {
         for (byte i = 0; i < mfrc522.uid.size; ++i)
           { // read id (in parts)
              Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
              Serial.print(mfrc522.uid.uidByte[i], HEX);
           }
         Serial.print("*");
       }
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
  Serial.flush();
   }
}

void doReceive()
{
   incomingStr = Serial.readString();
   int sto=incomingStr.indexOf(')');
   action=incomingStr.charAt(sto+1);
   y=sto+2;
   for(int j=0;j<sto;j++)
    {
      if(incomingStr.charAt(j)!= ' ')
       {
         //Serial.print(incomingStr.charAt(j));
         //arr[u]=arr[u].concat(incomingStr.charAt(j));
         arr2[u2]+=incomingStr.charAt(j);
       }
     else
       {
         //Serial.println(arr[u]);
         u2++;
       }
    }
  for(u2=0;u2<6;u2++)
    {
      arr3[u2]=arr2[u2].toInt();
      key.keyByte[u2]=arr3[u2];
      //Serial.println(key.keyByte[u2]);
    }
 }
void doWrite()
{
  int block=1;
  for(int i=0;i<incomingStr.length();i=i+16)
  {
    if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
      {
        block=block+1;
      }
    for(int u=0;u<16;u++)
      {
        blockcontent[u]=0;
        //Serial.println(arr1[u]);
      }
    String s1=incomingStr.substring(y+i,y+16+i);
    s1.getBytes((char *) blockcontent, 30);
    writeBlock(block, blockcontent);
    block=block+1;
  }
  Serial.println("Data written successfully*");
}
void doRead()
{
  int block=1;
  for(int i=0;i<4;i++)
    {
      if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
        {
          block=block+1;
        }
      byte readbackblock[18];
      readBlock(block, readbackblock);//read the block back
      //Serial.print("Block contains: ");
      for (int j=0 ; j<16 ; j++)//print the block contents
        {
           Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
        }

     //Serial.println();
     block=block+1;
    }
  Serial.println("*");
 }

```

# Answer
First of all try to add these debugging prints here to see if this while loop is becoming infinite:

```
  while(newc==0)
   {
     if ( ! mfrc522.PICC_IsNewCardPresent())
        {
           if(count==0)
               {
                   Serial.println("Scan your mifare card %");
                   count++;
                   **Serial.println("test0")*
               }

        }
    else
        {
           newc=1;
           **Serial.println ("newc=1")**
        }
   }

```
> 1 votes

# Answer
`arr2` have size `6`. Have you made sure that here

```
...
for(int j=0;j<sto;j++)
{
  if(incomingStr.charAt(j)!= ' ')
   {
     arr2[u2]+=incomingStr.charAt(j);
   }
 else
   {
     u2++;
   }
}
...

```

you are not writing beyond the bounds of that array?

Moreover, you never explicitly set the initial value of `u2` before starting this cycle - whatever was left in global variable `u2` from the previous uses will serve as the staring value for this cycle.

Judging by cursory examination of the rest of your code, only the very first call to `doReceive` will begin this cycle with `u2 == 0`. After that every time you call `doReceive`, you will start this cycle with `u2 == 6`, definitely overflowing the array and destroying the content of adjacent memory locations. The behavior is undefined.

I guess it is a "global variables strike again" kind of situation. Why on Earth is `u2` made a global variable???

It is quite possible that you can "fix" your code by simply adding `u2 = 0;` before the above cycle. But even after that the code will remain in a rather precarious state.
> 0 votes

---
Tags: arduino-uno, rfid
---