title: What motor to move a small telescope?

text:
# Question
Title: What motor to move a small telescope?
i just bought a hobby telescope, it works well for being nothing much than a toy, the very problem is that the gesrs that should keep it stable are all plastic and very hard to tighten while keeping it steady.

So I thought to let the gears wide open and move it with arduino: you point the object manually then with 4 buttons move it by small steps.

I've tried to use a couple of servos i had at home, mg90s 2kg 180°; while 180° is enough for the purpose, first i don't think 2kg is enough for the X axis motor, second one is not very precise (using the default library). I know I can achieve better results calibrating the pulse manually, but maybe is better if I use better motors.

What motors (and why) would you reccomand? Servo or stepper?

Being for a hobby the budget is low, so very max 50$?

# Answer
> 3 votes
I wouldn't use a servo for this. You don't have very fine control over the angle with a servo. Also with a typical telescope the focus is more on rather slow and precise movements, instead of fast ones.

Instead I would use a stepper motor. Depending on your exact requirements, these can be rather cheap to rather expensive.

Here also the mechanics come into play. The motor should not be attached directly to the axis, but instead through some gears (the axis of the telescope having the larger gear). That will allow for smaller, more precise movements and also lower the needed torque for the motor. Of course this depends on your actual telescope hardware, meaning if you can put a gear right to the axis. If not, you could limit the motor driven movement a bit and install a level, which then could be pushed or pulled by a nut on a threaded rod, which gets driven by the servo motor. This would be rather easy to implement, though you may need to correct for the different rotation behavior, when you get to the outer sides of the movement (for the actuator being linear, while the resulting movement is circular), by some mathematics in your code.

Since you want to keep your costs very low, you might wanna use the 28BYJ-48 stepper motor (including the fitting driver). In terms of stepper motors they are rather bad, but they are really really cheap and - depending on the gear ratio/level length/thread pitch - it might not matter that much for you. You could always update to a better stepper motor in the future.

---
Tags: motor, servo, stepper-motor
---


title: Serial monitor window opens frozen

text:
# Question
Title: Serial monitor window opens frozen
My serial monitor window opens frozen, without any output or possibility to input, or even activate the window. Sketch is very simple, but behavior is same even with empty sketch, so I assume problem is not in sketch. I also checked if sketch is uploaded correctly by uploading simple sketch with blinking diode, which worked.

Same behavior with Arduino Nano and Uno.

I tried to reinstall IDE, uninstalled, removed and reinstalled serial driver (ch340) with no success.

I can see Serial monitor window only on windows taskbar, it won't activate after click.

Until now I haven't had any significant problems with IDE or serial monitor for years.

# Answer
> 1 votes
Try updating the java. Also check whether the device manager shows the USB serial port without any yellow warning sign on it. If there is a current short in the usb port that specific port will be off for safety, restarting the computer should resolve that problem.

# Answer
> 1 votes
Unfortunaltely, nothing worked, and after hours of trying and googling I reinstalled windows, and now Serial Monitor works correctly.

---
Tags: serial, ide
---


# Question
Title: Cannot receive IR codes after sending IR on same Arduino (I have irrecv.enableIRIn();)
I have two Arduinos with identical wiring, they will (hopefully) end up being laser guns for my younger cousins.

When they both have a sketch which simply toggles lights when the correct IR code is received, everything works as it should. see the code here:

// Start of sketch 1

```
#include <IRremote.h>
IRsend irsend; //Setup the IR transmitter
int receiver = 8; //initialize pin 13 as receiver pin.
IRrecv irrecv(receiver); //create a new instance of receiver
decode_results results;

// declare consants
const int trigger = 13;
const int greenLight = 7;
const int yellowLight = 2;
const int timeBetweenTransmittion = 800;

// declare variables
bool toggleGreen = true;
bool toggleYellow = true;
long int previousTransmittion = 0;

// put your setup code in here, to run once:
void setup()
{
  pinMode(trigger, INPUT_PULLUP);
  Serial.begin(9600); // send code at 9600 bits per second
  irrecv.enableIRIn(); // start the receiver
}

// put your main code in here, to run repeatedly:
void loop() {
  if (not digitalRead(trigger) && millis() > previousTransmittion + timeBetweenTransmittion) // if the button is pressed and it's been enought time since the last transmittion
  {
    Serial.println("send!");
    irsend.sendNEC(1367857, 32); // send the code
    irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
    previousTransmittion = millis(); // set the record for latest transmittion to the currnt time

    // toggle the yellow light
    digitalWrite(yellowLight, toggleYellow);
    toggleYellow = not toggleYellow;
  }

  if (irrecv.decode(&results)) { // if we have received an IR signal
    Serial.println (String(results.value, HEX)); //display HEX results
    if (String(results.value, DEC) == "1367857")
    {
      Serial.println("correct code");
      // toggle the green light
      digitalWrite(greenLight, toggleGreen);
      toggleGreen = not toggleGreen;
    }
    irrecv.resume(); // it stops the receiver when something's received so we muct resume the ir receiver
 }
}

```

// End of sketch 1

The receiver is on pin 8 and, button on pin 13 and transmitting LED is always on pin 3.

No issues there.

However, when I use the same concepts on a larger-scale project, a strange problem occurs. Once one of the Arduinos has sent some IR, the receiver no longer works. After every line of code which sends IR, I follow it with `irrecv.enableIRIn();`, and after every time it receives code I have the line `irrecv.resume();`. I can't work out what the problem is. It's very long, but the full code is below:

// Start of code 2

```
// include the library code:
#include <LiquidCrystal.h> // For the LCD
#include <IRremote.h> // For the IR communication
#include <PCM.h> // For the audio output

const unsigned char gunShot[] PROGMEM = {}; // In the program this contains a huge array of notes, I removed them to save space

const unsigned char gunClick[] PROGMEM = {}; // In the program this contains a huge array of notes, I removed them to save space

// Declare consants for pins
const int rs = A0, en = A1, d4 = A2, d5 = A3, d6 = A4, d7 = A5; // State constants for all the pins used for the LCD
const int trigger = 13;
const int redLight = 7;
const int magReader1 = 9;
const int magReader2 = 10;
const int speaker = 11;
const int healButton = 12;
const int receiver = 8;
const int muzzle = 2;

// Declare constants for gameplay
const int timeBetweenShots = 800; //(in 1000ths of a second)

const int healAmount = 100;

const int medicAmmo = 16;
const int assultAmmo = 31;
const int sniperAmmo = 1;

const int medicDamage = 30;
const int assultDamage = 23;
const int sniperDamage = 75;

const int playerNumber = 4;

// Declare all valiables
int timesKilledByTeam1 = 0; // I would loved to have used an array here, but for some reason an array broke the program
int timesKilledByTeam2 = 0;
int timesKilledByTeam3 = 0;
int timesKilledByTeam4 = 0;
int timesKilledByTeam5 = 0;
int timesKilledByTeam6 = 0;
int timesKilledByTeam7 = 0;
int timesKilledByTeam8 = 0;

String receivedCode = ""; // Store the received code in a string variable
bool gameDone = false;

bool semiCanShoot = true;
bool gunShouldClick = true;

int health = 100;
int gameMode = 1; // 1=TDM, 2=FFA, 3=LTS, 4=LPS
bool respawn = true;
int teamOrPlayer = playerNumber;
int loadStatus; // 0 is no mag, 1 is mag1, 2 is mag2

int mag1Ammo; // Current ammo in mag1
int mag2Ammo; // Current ammo in mag2
int maxAmmo; // Ammo in one mag for the selected class
int damage; // Damage this player is inflicting per shot

long int timeOfFlash = 0;
long int timeOfMuzzle = 0;
long int timeOfLastShot = 0;
long int loopTimer = 0;

int gameStartTime; // In seconds so no need for long int
//int secondsRemaining;
int gameDuration;

int playerClass = 0; // 0=Medic, 1=Asult, 2=Snipr

int shootCode;

IRsend irsend; //Setup the IR transmitter
IRrecv irrecv(receiver); //create a new instance of receiver
decode_results results;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void SetupClass()
{
    switch (playerClass)
    {
        case (0):
          maxAmmo = medicAmmo;
          damage = medicDamage;
          break;
        case (1):
          maxAmmo = assultAmmo;
          damage = assultDamage;
          break;
        case (2):
          maxAmmo = sniperAmmo;
          damage = sniperDamage;
          break;
    }
    mag1Ammo = maxAmmo;
    mag2Ammo = maxAmmo;
}

// Define subroutines
//void QuickDisplayUpdate(int ammo, int secondsRemaining, int loadStatus, int health) // During a game, to save unnecessary computation, only update the things that might have changed during the game
void QuickDisplayUpdate()
{
    lcd.setCursor(11,0);
    if((gameDuration - (millis() / 1000 - gameStartTime)) / 60 < 10)
    {
      lcd.print("0");
      lcd.setCursor(12,0);
    }
    lcd.print(String((gameDuration - (millis() / 1000 - gameStartTime)) / 60));

    lcd.setCursor(14,0);
    if((gameDuration - (millis() / 1000 - gameStartTime)) % 60 < 10)
    {
      lcd.print("0");
      lcd.setCursor(15,0);
    }
    lcd.print(String((gameDuration - (millis() / 1000 - gameStartTime)) % 60));

    lcd.setCursor(7,1); // Put the / in as it might have been removed from a previous "Reload!"
    lcd.print("/");

    lcd.setCursor(0,1);
    if (loadStatus == 0) lcd.print("Reload!");
    else if (loadStatus == 1)
    {
      lcd.print("Mag" + String(loadStatus) + ":");
      lcd.setCursor(5,1);
      if (mag1Ammo < 10)
      {
        lcd.print("0");
        lcd.setCursor(6,1);
      }
      lcd.print(String(mag1Ammo));
    }
    else
    {
      lcd.print("Mag" + String(loadStatus) + ":");
      lcd.setCursor(5,1);
      if (mag2Ammo < 10)
      {
        lcd.print("0");
        lcd.setCursor(6,1);
      }
      lcd.print(String(mag2Ammo));
    }

    lcd.setCursor(13,1);
    if(health < 100)
    {
      lcd.print(" ");
      lcd.setCursor(14,1);
      if(health < 10)
        {
          lcd.print(" ");
          lcd.setCursor(15,1);
        }
    }

    lcd.print(String(health));
}

void FullDisplayUpdate(int teamOrPlayer)
{
    lcd.clear();
    lcd.setCursor(0,0);
    switch (gameMode)
    {
        case (1):
          lcd.print("TDM");
          break;
        case (2):
          lcd.print("FFA");
          break;
        case (3):
          lcd.print("LTS");
          break;
        case (4):
          lcd.print("LPS");
          break;
    }

    lcd.setCursor(3,0);
    lcd.print(String(teamOrPlayer));

    lcd.setCursor(5,0);
    switch (playerClass)
    {
        case (0):
          lcd.print("Medic");
          break;
        case (1):
          lcd.print("Asult");
          break;
        case (2):
          lcd.print("Snipr");
          break;
    }

    lcd.setCursor(11,0);
    if((gameDuration - (millis() / 1000 - gameStartTime)) / 60 < 10)
    {
      lcd.print("0");
      lcd.setCursor(12,0);
    }
    lcd.print(String((gameDuration - (millis() / 1000 - gameStartTime)) / 60) + ":");

    lcd.setCursor(14,0);
    if((gameDuration - (millis() / 1000 - gameStartTime)) % 60 < 10)
    {
      lcd.print("0");
      lcd.setCursor(15,0);
    }
    lcd.print(String((gameDuration - (millis() / 1000 - gameStartTime)) % 60));

    lcd.setCursor(0,1);
    if (loadStatus == 0) lcd.print("Reload!");
    else if (loadStatus == 1)
    {
      lcd.print("Mag" + String(loadStatus) + ":");
      lcd.setCursor(5,1);
      if (mag1Ammo < 10)
      {
        lcd.print("0");
        lcd.setCursor(6,1);
      }
      lcd.print(String(mag1Ammo));
    }
    else
    {
      lcd.print("Mag" + String(loadStatus) + ":");
      lcd.setCursor(5,1);
      if (mag2Ammo < 10)
      {
        lcd.print("0");
        lcd.setCursor(6,1);
      }
      lcd.print(String(mag2Ammo));
    }

    lcd.setCursor(8,1);
    if (maxAmmo < 10)
    {
      lcd.print("0");
      lcd.setCursor(9,1);
    }
    lcd.print(String(maxAmmo));

    lcd.setCursor(11,1);
    lcd.print("H:" + String(health));

}

void Play()
{
  gameDone = false; // When the game starts, the game isn't done

  FullDisplayUpdate(teamOrPlayer); // Fully update the display before the game starts

  // Setup the shoot code
  if(damage > 9) shootCode = (String(teamOrPlayer) + String(damage) ).toInt();
  else shootCode = (String(teamOrPlayer) + "0" + String(damage)).toInt();

  // Wait until either a start or cancel code is recieved
  Serial.println("wait");
  receivedCode = "";
  //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
  while (receivedCode.length() != 2 && receivedCode.length() != 4)
  {
    if (irrecv.decode(&results))
    {
      receivedCode = String(results.value, DEC); // Store the received code in a variable when we have received an IR signal
      irrecv.resume(); // Remove the code
    }
  }

  Serial.println("code: " + receivedCode);

  gameStartTime = millis() / 1000; // Set the game start time in seconds

  if (String(receivedCode) == "50") // If the received code was starting code (50) then play
  {
      Serial.println("strt, dur: " + String(gameDuration) + "team: " + String(teamOrPlayer));

      while (gameDone == false) // Repeat until the game is done
      {
          //Serial.println("Game loop");

          CheckForIR(); // Check for an IR code as often as possible

          if (playerClass == 0) // Only check for heal button if they are a medic
          {
            if (not digitalRead(healButton) && millis() > timeOfLastShot + timeBetweenShots) // If they are pressing the heal button and it's been enought time since last shot
            {
                Serial.println("heal bttn");
                if (loadStatus == 1 && mag1Ammo == maxAmmo) // If mag1 is in and it's full
                {
                    Serial.println("heal 1");
                    irsend.sendNEC((String(teamOrPlayer) + "00").toInt(), 32); // Send the heal code
                    //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
                    digitalWrite(muzzle, 1); // Turn on the muzzle flash
                    timeOfMuzzle = millis(); // Set the time of the muzzle turning on
                    //startPlayback(healShot, sizeof(healShot)); // Play  heal sound
                    mag1Ammo = 0; // Empty the current mag
                }
                else if (loadStatus == 2 && mag2Ammo == maxAmmo) // If mag2 is in and it's full
                {
                    Serial.println("heal 1");
                    irsend.sendNEC((String(teamOrPlayer) + "00").toInt(), 32); // Send the heal code
                    //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
                    digitalWrite(muzzle, 1); // Turn on the muzzle flash
                    timeOfMuzzle = millis(); // Set the time of the muzzle turning on
                    //startPlayback(healShot, sizeof(healShot)); // Play  heal sound
                    mag2Ammo = 0; // Empty the current mag
                }
            }
          }

          CheckForIR();

          if (not digitalRead(trigger) && (millis() > timeOfLastShot + timeBetweenShots)) // If the trigger is pulled and it's been long enough since last shot
          {
              Serial.println("sht bttn");
              if (loadStatus == 1 && mag1Ammo > 0) // If mag1 is in and it has ammo
              {
                  if (playerClass != 0 || semiCanShoot == true) // They can shoot if they are on full auto or if semi can shoot
                  {
                      Serial.println("1 sht");
                      irsend.sendNEC(shootCode, 32); // Send the shoot code
                      irrecv.enableIRIn(); // Start the receiver
                      digitalWrite(muzzle, 1); // Turn on the muzzle flash
                      timeOfMuzzle = millis(); // Set the time of the muzzle turning on
                      mag1Ammo = mag1Ammo - 1; // Reduce ammo of current mag by one
                      semiCanShoot = false; // Once they have shot, they cannot shoot again if on semi mode
                      startPlayback(gunShot, sizeof(gunShot)); // Play shot
                      Serial.println("1 sht done");
                  }
              }

              else if (loadStatus == 2 && mag2Ammo > 0) // If mag2 is in and it has ammo
              {
                  if (playerClass != 0 || semiCanShoot == true) // They can shoot if they are on full auto or if semi can shoot
                  {
                      Serial.println("2 sht");
                      irsend.sendNEC(shootCode, 32); // Send the shoot code
                      irrecv.enableIRIn(); // Start the receiver
                      digitalWrite(muzzle, 1); // Turn on the muzzle flash
                      timeOfMuzzle = millis(); // Set the time of the muzzle turning on
                      mag2Ammo = mag2Ammo - 1; // Reduce ammo of current mag by one
                      semiCanShoot = false; // Once they have shot, they cannot shoot again if on semi mode
                      startPlayback(gunShot, sizeof(gunShot)); // Play shot
                      Serial.println("2 sht done");
                  }
              }

              else if (gunShouldClick) // (If no mag in OR no ammo in the mag that's in) AND gun should click
              {
                  Serial.println("clik");
                  startPlayback(gunClick, sizeof(gunClick)); // Play click sound
                  gunShouldClick = false; // Gun shouldn't click again until they releace trigger
              }
              timeOfLastShot = millis(); // Update the time of last shot
              Serial.println("shot done");
          }

          CheckForIR();

          // Check for if the gun should click again and if player can shoot again if on semi mode
          if (digitalRead(trigger)) semiCanShoot = true; // If they are not holding the trigger, they can shoot again if on semi mode
          if (digitalRead(healButton) && digitalRead(trigger)) gunShouldClick = true; // If they are not holding the trigger or the heal button, the gun should click again when they do hold it again

          CheckForIR();

          // If the LEDs have been on for long enough, turn them off
          if (millis() > timeOfFlash + 50) digitalWrite(redLight, 0); // Turn off the red LEDs if they have been on for enough time
          if (millis() > timeOfMuzzle + 50) digitalWrite(muzzle, 0); // Turn off the muzzle if it's been on for enough time

          CheckForIR();

          if (millis() > loopTimer + 250) // Some things need to be done less often, so do that to save time so IR receive checks can be done more frequently
          {
              loopTimer = millis();

              QuickDisplayUpdate(); // Quick update the display after every loop

              CheckForIR();

              // Update the loadStatus variable depending on the mag detector inputs
              if (!digitalRead(magReader1) && digitalRead(magReader2))
              {
                  loadStatus = 1;
                  mag2Ammo = maxAmmo; // Refil mag2 if mag one is in
              }
              else if (!digitalRead(magReader2) && digitalRead(magReader1))
              {
                  loadStatus = 2;
                  mag1Ammo = maxAmmo; // Refil mag1 if mag two is in
              }
              else loadStatus = 0;

              CheckForIR();

              // Check to see if the game has reached the time limit
              if (gameDuration - (millis() / 1000 - gameStartTime) < 1)
              {
                Serial.println("tm up");
                gameDone = true;
              }
          }

      } // Game is done

  } // If the received code wasn't the starting code then cancel the game and return to waiting menu
}

void CheckForIR()
{
  //Serial.println("check");
  //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
  if (irrecv.decode(&results)) // If there is a code
  {
      receivedCode = String(results.value, DEC); // Store the received code in a string variable
      Serial.println(receivedCode);
      irrecv.resume(); // Remove the code
      if (receivedCode.length() == 3) // If the received code has length 3, we have been shot
      {
          Serial.println ("shot"); //display shot code
          if (receivedCode.substring(0,1) != String(teamOrPlayer)) // Only continue if the shooter is on another team
          {
              Serial.println ("another team");
              digitalWrite(redLight, 1); // Turn on the red lights
              health = health - (receivedCode.substring(1, 3).toInt()); // Reduce health by incoming damage, if it's an enemy heal it won't have an effect
          }
          else if (receivedCode.substring(1, 3).toInt() == 0)
          {
            Serial.println("heal");
            health = health + healAmount; // Heal if they are a teammate and they are doing 0 damage
          }

      }

      if (health > 100) health = 100; // Set back to 100, cannot be on over 100 health
      else if (health < 1)
      {
          Serial.println ("died");
          switch(receivedCode.substring(0,1).toInt()) // Increment's the killer's kills by one
          {
            case (1):
              timesKilledByTeam1++;
              break;
            case (2):
              timesKilledByTeam2++;
              break;
            case (3):
              timesKilledByTeam3++;
              break;
            case (4):
              timesKilledByTeam4++;
              break;
            case (5):
              timesKilledByTeam5++;
              break;
            case (6):
              timesKilledByTeam6++;
              break;
            case (7):
              timesKilledByTeam7++;
              break;
            case (8):
              timesKilledByTeam8++;
              break;
          }

          health = 100; // Reset the health
          mag1Ammo = maxAmmo; // Refil the mags
          mag2Ammo = maxAmmo;

          // Update the LCD
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("You died!");
          lcd.setCursor(0,1);
          lcd.print("Return to base");

          if (respawn == false) gameDone = true; // If playing one life gamemode, end game
          else // Otherwise wait until respawn code is recieved
          {
              //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
              while ((receivedCode != "50") && (gameDuration - (millis() / 1000 - gameStartTime) > 1)) // Keep looking for IR siginal until it's 50 or the time's up
              {
                  //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
                  if (irrecv.decode(&results)) // if we have received an IR signal
                  {
                      receivedCode = String(results.value, DEC); // Store the received code in received code variable
                      irrecv.resume();
                  }
              }
          }
          FullDisplayUpdate(teamOrPlayer); // Reset the LCD to gameplay mode

      }
  }
}

void setup()
{
  lcd.begin(16, 2); // Set up the LCD's number of columns and rows
  Serial.begin(9600); // Send code at 9600 bits per second
  irrecv.enableIRIn(); // Start the receiver
  pinMode(trigger, INPUT_PULLUP);
  pinMode(magReader1, INPUT_PULLUP);
  pinMode(magReader2, INPUT_PULLUP);
  pinMode(healButton, INPUT_PULLUP);
}

void loop() // Repeat while looking for game (between games)
{
    Serial.println("\nlp");
    digitalWrite(redLight, 1); // Turn on the lights to show player isn't playing at the moment

    // Print waiting screen to LCD
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Awaiting start");
    lcd.setCursor(0,1);
    lcd.print("Player: " + String(playerNumber));

    //irrecv.resume();//  NOT YET TESTED
    //irrecv.enableIRIn(); // sending ir stops the receiver so start the receiver again
    while (not irrecv.decode(&results)) // wait until we have received an IR signal
    {
        // Transmit previous game data while we wait
        //Serial.println("wait");
    }

    receivedCode = String(results.value, DEC); // Store the received code in a string variable
    Serial.println(receivedCode); //display results
    irrecv.resume();

    if (receivedCode.length() == 4) // It was a sucessfull transmission if the recieved code was 4 characters long
    {
      playerClass = receivedCode.substring(3, 4).toInt(); // Set the class to the recieved class
      Serial.println("clss: " + String(playerClass));
      SetupClass();

      gameDuration = 180 * (receivedCode.substring(1,2).toInt() + 1); // Set the time remaining and game duration to the received time
      Serial.println("tm lft" + String((gameDuration - (millis() / 1000 - gameStartTime))) + ", gameDuration: " + String(gameDuration));

      // Reset the death counter as a new game is starting
      int timesKilledByTeam1 = 0;
      int timesKilledByTeam2 = 0;
      int timesKilledByTeam3 = 0;
      int timesKilledByTeam4 = 0;
      int timesKilledByTeam5 = 0;
      int timesKilledByTeam6 = 0;
      int timesKilledByTeam7 = 0;
      int timesKilledByTeam8 = 0;

      health = 100;

      switch (receivedCode.substring(0, 1).toInt()) // Do operations based on the received game mode
      {
          case (1): // TDM
            Serial.println("TDM");
            gameMode = 1;
            teamOrPlayer = receivedCode.substring(2, 3).toInt();
            respawn = true;
            Play(); // Call play with received team and respawn on
            break;

          case (2): //FFA
            gameMode = 2;
            Serial.println("FFA");
            respawn = true;
            teamOrPlayer = playerNumber;
            Play(); // Call play with player number and respawn on
            break;

          case (3): // LTS
            gameMode = 3;
            Serial.println("LTS");
            respawn = false;
            teamOrPlayer = receivedCode.substring(2, 3).toInt();
            //Play(); // Call play with received team and respawn off
            break;

          case (4): // LPS
            gameMode = 4;
            Serial.println("LPS");
            respawn = false;
            teamOrPlayer = playerNumber;
            //Play(); // Call play with player numebr and respawn off
            break;

          default:
            Serial.println("Unknown Gamemode");
            break;
      }

    }

}

```

// End of code 2

I know this code is a mess, I should not be using global variables and there should be more subroutines, but I wrote most of it before remembering about them :/

If I run the sketch and don't "shoot" on that reset, the code works fully as intended, but the "times killed by player x" variables section I haven't got to yet.

Extra information which I don't think is relevant:

There is a third Arduino which allows you to choose a code and send it, or send the code "50". This is the "base" which someone must return to in order to respawn, as it's the only thing which can send the code "50". The codes it can send are explained below:

It sends a 4-digit number, but it's read as 4 separate numbers, for example, consider the code "rspq". The r is the game mode (1=team respawn, 2=free for all, 3=last team standing, 4=last player standing), s is the duration of the game (time(s) = 3 * (s + 1), resulting in possible times of 3,6,9...30), p is the team that that player is on (when playing a team game)(when not playing a team game it just uses the player ID stored on that particular gun) and q is the class (1=medic, 2=assault, 3=sniper).

There is a lot to say so if you have any questions just ask.

Any help/ideas would be appreciated, thanks in advance.

# Answer
> 1 votes
It would appear that the audio aspect of my larger program was interfering with the IR receiver, as every time I send IR I also play a sound. It was the sound which was stopping the receiver, not the IR transmitter. When I removed the sound from the sketch, it worked as intended. Thanks timemage for your help.

---
Tags: arduino-uno, ir
---


# Question
Title: Can a 12V sensor connected to a 5V output signal of an Arduino Uno
I am doing a project for object detection. But my problem is I'm using a 12V photoelectric OMRON sensor to connect with 5V Digital PWM port 3 on Arduino using normal coding. Do I need an extra circuit to step down the voltage to 5V? Can it work because the only connection between the sensor and Arduino is the output signal, the VCC and Ground are from external power. Link to the datasheet Please help me

# Answer
My favorite solution for such an application is to use an optoisolation module. In this case, the signal can have a voltage of 12 V and the output of the optoisolation module can be connected to the input of the Arduino, where the input is configured as INPUT\_PULLUP. Example of the optoisolation module:

In this way it is possible to connect other types of sensors and switches and the solution is universal also for other development kits, e.g. with 3V3 logic.
> 1 votes

# Answer
For one, you need to connect the two grounds together.

Secondly, the 12V signal will indeed fry your Arduino. Lower the voltage to just below 5V, using a voltage divider circuit. You could for example use a combinations of a 2.2kOhm and a 1.5kOhm resistor, to get around 4.9V.
> 0 votes

---
Tags: arduino-uno, programming, sensors, project
---


# Question
Title: I'm getting an error while uploading my code to esp8266 via an arduino (FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error)))
```
Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 257316 bytes (26%) of program storage space. Maximum is 958448 bytes.

Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Reghunaath A A\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.2/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

_

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

```

I'm getting the above stated error message while I'm trying to upload a code to esp8266 via an arduino(I've removed the ATMEGA32 from my arduino). Sometimes it gets uploaded without a problem(very rarely) but mostly the upload fails. I connected rx of arduino to rx of esp and same for tx too. 3.3v of arduino to enable and vcc of esp. graund of arduino to ground of esp and gpio0.

The code that I'm trying to upload:

```
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forevervoid lop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

```

My settings:

EDIT: Also, I want to add one more thing when the message box says "Connecting........\_____.....\_" during that time if i reset the esp the code starts uploading

# Answer
> 1 votes
You need to set esp 8266 to flash mode.
Please connect en PIN to Gnd pin.
Then flash again.

---
Tags: esp8266, wifi, arduino-uno-wifi, esp
---


# Question
Title: L293D to change the direction current and amplify it - Temperature-Stabilizer
I have a question about my project. I'm going to make a temperature-stabilizer. To make this, I think I should use a TEC with a H-bridge and a LM35. First of all, I tried to make a H-bridge by myself, I have only used four NPN transistors and It didn't go well. Then I bought L293D motor driver - not the module one, tried it and it works well. But as datasheet says, it's output current is max 600mA. But this current doesn't make TEC work efficiently. So that, I need to amplify the current. But I don't want to buy high amp motor drivers, hardwares are to expensive in my city. Of course I'll if there's no another way.

Arduino will be used to get temperature values from LM35 and give the H-bridge voltage, control the current direction when necessary. I learned how to use transistors to amplify but if I'll change the direction, it won't work. But I don't know how to make this circuit.

**The algorithm that I thought using is this:**

**The scheme that I thought using in this:**

What should I do to solve my problem? Thank you for all.

**Resources:**

1. My Tec1-12706 Datasheet: http://www.thermonamic.com/TEC1-12706-English.pdf
2. LM35 Datasheet - (I have LP package): https://www.ti.com/lit/ds/symlink/lm35.pdf
3. L293D Datasheet: https://www.ti.com/lit/ds/symlink/l293.pdf
4. The transistor method to amplify: https://www.youtube.com/watch?v=WZD9RZoMhVE

# Answer
> 1 votes
I am interested on this as I have the same issue. What about using a FET or MOSFET to amplify the current that the LM293D provides?

---
Tags: arduino-uno, motor, temperature-sensor, temperature
---


# Question
Title: What happens when you call malloc()/free()/new/delete?
So I understand that generally speaking, dynamic allocation should be avoided. My question isn't how or why, but *what* happens when you call a function that allocates memory?

On Windows or Linux, when a program allocates memory, a whole bunch of stuff happens, things like virtualisation and security related features that have no relevance to arduino, and the bit that I'm interested in, memory management:

There will be some code, that will look at the alignment and size requirements of the allocation request, look at the pool of memory it has access to, find a space big enough, make a note of the allocation (which also uses some amount of memory) and then return a pointer to the allocated space back to the calling function.

Is there a custom malloc implementation for each device, or does it come with the arduino toolchain (and does that mean Arduino has a different implementation from Teensy, or avr from sam?), or is there some magical default implementation supplied by the compiler? What kind of memory overhead is incurred with every allocation? How easy is it to override this functionality and implement your own (out of morbid curiosity or tendency towards masochistic endeavours)?

# Answer
There are some hardware-specific abstractions (they mostly define the maximum memory available), but otherwise these are functions are implemented by the C/C++ runtime (on arduinos an implementation called "NewLib") and usually "just work". You might want to take a look at this question, where quite a bit of background is given on the SAM implementation of the hardware abstractions (because it's broken).

And yes, of course using malloc/free has some considerable overhead, which is one reason why it's not the recommended way of allocating memory on microcontrollers. But the logic behind it is mostly the same whether there's 2k of memory or 2G. And the *memory model* of modern microcontrollers (at least the 32 bit ones) is very similar to the one seen in 32 bit Windows or Linux apps.
> 2 votes

---
Tags: memory, avr-toolchain
---


# Question
Title: Is it possible to write data to a fat file system on SPI flash using an arduino?
I have an SPI flash based mp3 module and was wondering whether its possible to write to the flash chip using a microcontroller(arduino). the IC supports FAT16/FAT32 file systems. I have researched arduino and the fat file system but they are all in relation to SD cards which operate differently as far as i understand. Is it possible to write data to a fat file system on SPI flash using an arduino?

# Answer
> 0 votes
The first and most important problem is not the filesystem. Currently on the board the USB port is connected to the internal MCU, which in turn is connected via SPI to the flash chip. The internal MCU is the master on the SPI bus. But the SPI bus does not support multiple masters on one bus. So just connecting the external MCU to the SPI lines as master would not work.

I see 2 possible ways to go here:

* You can unsolder the flash chip from the board and add a fitting multiplexer chip, which can switch the SPI lines between the two masters. That effectively gives you only one master on the SPI bus at any time. This way would be rather hacky and difficult for a beginner. It might also be important to keep an eye on the capacitance of the bus, since it might run with rather high speed. A too high capacitance (for example through using a breadboard) might result in erroneous communication.

Then you could use one of the FAT libraries. I don't know them in detail, but I think you could also use them for a simple SPI flash chip. You just would need to implement the lower level access functions, that the FAT library needs.
* Or you could try to use a USB host board with your external MCU and try to write data through the USB port. I don't have much experience with USB host boards, so I cannot really tell you, if and how exactly this is possible with the available hardware (the board will most likely implement an USB interface like a simple flash USB stick).

All in all I think, this would be rather hacky. Your board is not really made for changing the data through another microcontroller. Depending on what exactly you want to achieve, you might want to go to a different hardware setup.

---
Tags: spi, fat
---


# Question
Title: How to unbrick an Arduino Mega+ESP8266 Wifi
I have a Jaycar XC4421 - Arduino Mega + Wifi which I think have somehow managed to screw up the boot loader.

I have an XC4627 USP-ISP Programmer (and the XC4613 adaptor) which I have previously used to successfully burn boot loaders and update sketches in the past using the Arduino IDE.

However, on this occasion, after trying to reset the bootloader from the IDE, i can no longer upload sketches from the IDE using the inbuilt "upload" function of the IDE (I get timeouts) nor can I upload the sketch using the USB-ISP Programmer.

The symptoms as they currently stand with the USB connected to the 2560 (switches 3 & 4 on, all others off):

* If I burn the bootloader (selected board in IDE is "Arduino Mega or Mega 2560"), this appears to work, but uploading sketches still does not work. After burning the bootloader, the builtin LED blinks at an odd cycle of roughly 400ms off, 400ms on, 200ms off, 200ms on.
* The board is recognised in the IDE and appears as COM12
* If try to upload the "blink" sketch (ctrl-U), I get timeout messages (see transcript below)
* If I connect the USB-ISP and upload the blink sketch (ctrl-shift-U), the upload appears to work, but the sketch is never run (i.e. the builtin LED doesn't blink).
* After uploading the blink sketch (via the USB-ISP programmer) the aforementioned odd blinking of the builtin LED completely stops (i.e. no blinking at all).
* There is no hardware other than the USB-ISP programmer connected to the ICSP pins on the Arduino.
* If I reset the DIP switches so that just 5 & 6 are on (USB-\>ESP) I am able to interact just fine with the "AT program" that was originally supplied on ESP side of the board.

My suspicion is that the Arduino Mega 2560 bootloader code is not completely compatible with the Arduino Mega + WiFi board. I don't think that suspicion makes much sense, but I'm out of ideas!

Where can I get the correct bootloader for this device? Alternatively, how can I correctly unbrick this?

Transcript from "upload blink sketch" showing timeout:

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_481876\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_481876\Blink.ino
Using board 'mega' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Using core 'arduino' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Warning: Board arduino:avr:ATmega328p-8 doesn't define a 'build.board' preference. Auto-set to: AVR_ATMEGA328P-8
Detecting libraries used...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE
"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521\core\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a
Linking everything together...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega2560 -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/..\\arduino_cache_341521\\core\\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a" "-LC:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155" -lm
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.eep"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.hex"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf"
Sketch uses 2684 bytes (1%) of program storage space. Maximum is 253952 bytes.
Global variables use 194 bytes (2%) of dynamic memory, leaving 7998 bytes for local variables. Maximum is 8192 bytes.
C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cwiring -PCOM12 -b115200 -D -Uflash:w:C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:i

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

         System wide configuration file is "C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM12
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
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

avrdude done.  Thank you.

An error occurred while uploading the sketch

```

Transcript from "Upload blink sketch using programmer":

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_753905\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_753905\Blink.ino
Using board 'mega' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Using core 'arduino' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Warning: Board arduino:avr:ATmega328p-8 doesn't define a 'build.board' preference. Auto-set to: AVR_ATMEGA328P-8
Detecting libraries used...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE
"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521\core\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a
Linking everything together...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega2560 -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/..\\arduino_cache_341521\\core\\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a" "-LC:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155" -lm
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.eep"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.hex"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf"
Sketch uses 2684 bytes (1%) of program storage space. Maximum is 253952 bytes.
Global variables use 194 bytes (2%) of dynamic memory, leaving 7998 bytes for local variables. Maximum is 8192 bytes.
C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -Uflash:w:C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:i

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

         System wide configuration file is "C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

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

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 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
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

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

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9801 (probably m2560)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: reading input file "C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex"
avrdude: writing flash (2684 bytes):

Writing | ################################################## | 100% 1.69s

avrdude: 2684 bytes of flash written
avrdude: verifying flash memory against C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:
avrdude: input file C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex contains 2684 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 1.43s

avrdude: verifying ...
avrdude: 2684 bytes of flash verified

avrdude done.  Thank you.

```

# Answer
Well after "working" on this all day, it turns out that the solution was to use the "Arduino as an ISP" solution as described on the arduino.cc website.

Why the USB-ISP solution did not work is not immediately obvious as I have used it successfully before - just not with this board!

FWIW, the blinking sequence I observed when burning the bootloader via the USB-ISP programmer also occurred after loading the bootloader via the "Arduino as ISP" solution. I don't know if the sequence was identical, but it certainly was similar. I then tried uploading the blink sketch using the "inbuilt" upload (ctrl-U) and the inbuilt LED blinked "correctly" at a 1s on 1s off cycle as per the standard blink sketch is programmed to do.

Oh well, hopefully this "answer" will help others.
> 1 votes

---
Tags: arduino-mega, bootloader
---


title: Multiple IR Sensors with Arduino

text:
# Question
Title: Multiple IR Sensors with Arduino
I am fairly new to working with sensors and Arduino. I am working on a project using Max MPS to control the volume of three audio files. There will be three framed photos, each having its own IR sensor and audio file. So when someone gets closer to the sensor, the volume of the corresponding file gets louder. Is this doable? The samples I have seen with the board I have and an IR sensor only use one. I'm assuming I'll be able to use the breadboard I have to add more sensors like I've done in the past with photocell sensors but I have yet to test it since it's in the mail. Just hoping to get ahead of any issues I may face and see if I should order any other equipment.

I ordered 3 of these IR sensors and this is the Arduino kit I am working with.

Sorry if I may not be describing it in enough detail, but thanks in advance!

# Answer
technically yes, there is no reason you can't do that project but the issues will come in how complex you wish to make system. For example, it shouldn't be too hard to hook up the three sensors to three analogue Pins on the Arduino and then have the Arduino constantly loop to check the voltage of the sensors, from which, you would tell it to 'do something' when one of the IR sensors voltage is above or below a certain value. What you then choose to do is up to you, if it's just to turn on a light then it can be done fairly quickly once you have all the components. For controlling the Audio in the file, I personally have no experience with this.

What might be better is first checking to see if you can Adjust the audio in one of your files using an Arduino (you may need to use bluetooth or have something on your PC communicate with your Arduino via UART through the USB).

Generally, with new projects, it's a good idea to figure out a solid plan for exactly what you want to do, so I would write down in detail what you want the system to do and then go through each part to see if it's possible
> 3 votes

---
Tags: arduino-uno, sensors, ir, audio
---


# Question
Title: Is it bad practice to multitask without timing constraints
Going through resources such as several things at the same time and with some greatly appreciated assistance on here I'm finally getting a grasp on how to multitask a microcontroller.

Most examples use the millis() approach to nonblocking programming. However, even in the link above the button state is being polled every loop (from what I understood).

So what confuses me is: is it bad practice to write functions, which poll sensor(s) and input(s) without timing constraints, i.e. at every iteration of loop?

Is this still consider nonblocking programming?

I've written some mock code to better illustrate what I mean. Thank you very much for reading through.

```
void loop() {
    Button();
    Sensor();
    LED();
    // ...
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state == LOW) {
    // ...
  };
};

void Sensor() {
  // Read sensor
  int sensor_state = analogRead(sensor_pin);
  if (sensor_state >= 150) {
    // ...
  };
};

```

# Answer
Like often, the answer is: It depends.

Generally it is non-blocking programming, when you do only short things on each loop. What exactly can be considered short depends on the situation, meaning, what else you want to do.

For example: You are reading an analog value on every loop. The `analogRead()` will take about 100us (reference). I assume, that your sensor value is rather slow (so the time of signal above 150 would be rather long). Also you are reading a button with `digitalRead()`. The read takes about 3.6us (reference). So in total you have a loop of - lets say - 150us (with overhead and `loop()` iteration included). But the event, that you want to catch - the button press - will be in the ballpark of 100ms, which is a factor 667 greater, than the total time of your `loop()` (when no event happened). So in relation to the shortest event (the button press) all the reads can be considered non-blocking. (Though you could still get blocking through the code inside the if statements. Thats on you to investigate)

Non assume, that you don't have a button, but a digital signal, and you want to sense pulses down to 80us. Then your `analogRead()` would take too long and you could miss a pulse event. In this case `analogRead()` might be considered blocking.

So, to check if you are really using non-blocking code, you would need to ask yourself: Am I giving every code part enough time to execute right and to catch all the intended events? If yes, then you are non-blocking. If no, then you are blocking.

---

As a side note: Often polling is described as bad, but it really depends on the situation. In your case you poll the inputs sequentially, so every input gets polled at the same (total) rate at which your `loop()` runs. You are doing nothing else, so why should you lower the processing time by not use polling? The saved time cannot be used better on a microcontroller (in contrast to a PC, where the saved CPU time could be given to a different program).
> 5 votes

# Answer
If you are running off battery, then you should consider having the microcontroller sleep as much as possible, and not poll the sensors more often than needed. AFAIK, the Arduino core library provides no facility for managing sleep, but some third-party libraries are available for that purpose.

If you project runs off mains power, then there is no point in adding the complexity of sleep management. Unless your sensors are really slow, polling them at each loop iteration is generally fine. Specifically, for a push button, the documentation of the Bounce2 library states that the button update method should be called on every loop iteration.
> 2 votes

---
Tags: sensors, timers, input, threads
---


title: What is the baud rate for Wiegand?

text:
# Question
Title: What is the baud rate for Wiegand?
I am attempting to develop an Arduino project that can identify the bit format of a card (26-bit being the most common but not the only one).

This a library sets the serial to be 9600 baud. https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary

This documentation says the data bit width is about 100us and the "inter pulse" or the time between the data bit is 20-100us. https://docs.tibbo.com/taiko/ser\_wiegand\_mode

I don't understand how these match up? Also, Wiegand isn't even really serial. It uses two inputs - One input is for the on bits and another input is for the off bits.

# Answer
> 1 votes
Wiegand doesn't have a baud rate as such. It's an edge-based input protocol where it looks for HIGH to LOW transitions on two different input lines.

There are certain timing requirements, in that you can't send data faster than the receiver is capable of receiving and pulses have to be wide enough for the receiver to read, and there is a minimum time for the gap between messages, but other than that there is no defined baud rate.

# Answer
> 1 votes
Just tested my **HID multiCLASS SE RP40 920P** with an oscilloscope.

Time between pulses: ~ 2 ms

Pulse duration: ~ 40 us

Measured a few different events, they seemed very consistent.

---
Tags: baud-rate
---


# Question
Title: How can I send and receive data from an Arduino MEGA 2560 and Python?
Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. \[Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.\]

Arduino:

```
int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received
}

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';

              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    Serial.print(cnt);
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED
                    }
              }

          }
}

```

Python code:

```
import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
    print('Hello')
    dat.write(1)
    print('Works')

```

# Answer
> 1 votes
Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like `dat.write(b'1')` and then receive it on the Arduino using `Serial.readString()`. I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The%20easiest%20way%20is%20to,Arduino%20IDE)" If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.

# Answer
> 1 votes
try with Firmata, it is a protocol that establishes serial communication between the computer with Arduino. All you have to do is have the Firmata on Arduino Board, and pyFirmata plugin available to talk with Arduino from Python on your machine.

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


# Question
Title: Is it possible for the Arduino's digital pin mode to flip from OUTPUT to INPUT unexpectedly?
I have an Arduino project (data logger intended to sample 100 samples per second for months) with firmware that is too long to post. It mostly works as supposed to, but I have a confusing issue I can't figure out: rarely, the indicator LEDs (driven by digital pins) stop working. By rarely, I mean if I run 20 devices for two weeks, maybe one will develop the issue, so it's very hard to test empirically but it's frequent enough that it matters. I know it's not a hardware problem because they start again after a reset. The device apparently continues working fine apart from the LED issue when this happens.

I have three hypotheses:

1. There's a logic problem in my firmware code. I'm skeptical because the relevant block of code is pretty simple.
2. A memory overflow or some similar problem causes the program to fail at this one particular task but not others. I'm a little skeptical because the device reports free stack in the metadata every second and it's always over 40 bytes; I may be misunderstanding memory use though.
3. Somehow, the digital pin (4) driving the LED gets flipped from OUTPUT to INPUT. There's definitely no `pinMode(4, INPUT)` command anywhere in my code though, so if this is happening it's not my code doing it.

Let's suppose it isn't #1. Considering #2: is it likely that a weird memory issue is causing a very specific failure while not affecting core functions of the device?

Considering #3, is there anyway the register setting a pin to INPUT or OUTPUT could be flipped unexpectedly? It sounds crazy to me but I want to rule it out.

The platform is similar to the Arduino Pro (3.3V, 8 MHz, ATMEGA328p) and I'm running the current IDE version (1.8.13). Thanks for any help.

# Answer
> 2 votes
The fact that it is possible to set them incorrectly is why, in some projects where I'm concerned about this, I'll add a small series resistance to an inbound signal. Should the pin become `OUTPUT` and driven in an opposing direction to the signal, the resistance serves to prevent a short through both devices. The possibility is always there, whether you have an outright bug, or instability, or flash corruption.

With `pinMode` the opportunity to accidentally set your port to the wrong direction is maybe a bit worse than for code that directly manipulates the data direction register. `pinMode` calls typically don't get inlined, because `pinMode` on the Arduino is a fairly complicated function at runtime for what it actually does. So, there's this generic code that can be jumped to that will set various ports to either direction, as opposed to smaller chunks of code that contain instructions that set specific ports to specific settings.

`INPUT` roughly takes your digital pin out of the circuit. And `INPUT_PULLUP` sort of does that, with the exception that internal to the AVR there's going to be 20k - 50k of resistance going to "5V". Knowing that, you can test your hypothesis three. When you find your project in the state where the LED isn't lit, take some some resistance (say 1K) and use it to pull the pin toward "5V". Then pull it to GND. Watch the voltage at the pin with a meter. Based on what you have attached and what you see for a voltage, you can determine whether it has entered the `INPUT` or `INPUT_PULLUP` state. You'll also be able to see if it's just being driven to whatever state you're calling "not working" ("off" I'm guessing).

You can take all the guess work out of what voltages to see in each scenario if you upload a sketch that sets the pin in question to the `INPUT`, `INPUT_PULLUP`, `OUTPUT`/`HIGH`, and `OUTPUT`/`LOW` states and measure the voltage at the pin when you pull it to each rail with your resistor. Later you can consult the table you've built to see what has happened.

There's only so much to say about this, particularly your first two ideas, without seeing the code and other details. Just that sometimes otherwise simple code has bugs in it. In an ATMega328P project, 40 bytes is not a lot of free space at all. To give you an idea what sort of problem this can trigger: The Arduino implementation of `new` that's in the 1.8.3 core will happily blow away your register file and whatever else it can get to after that, if the underlying `malloc` reports not enough memory. Basically `new` continues to initialize the object it thinks was allocated even when the pointed returned is nullptr. The `__malloc_margin` is 128 in the 1.8.3. So if you try to `malloc` with 40 bytes distance between the stack and heap, you will trash your program state, perhaps even setting a data direction register in the process.

---
Tags: memory, pinmode, registers
---


# Question
Title: I have a problem trying to limit motor speed to a certain RPM using a MOSFET trigger switch module
I am using the potentiometer to control the duty cycle of a PWM signal to the MOSFET trigger switch module, thus controlling the motor speed.

In my code, I have used the map function to utilize the full resolution of my potentiometer (0 - 1023) and thus create a proportional PWM signal using analogWrite function (0 - 255).

However, in my setup I want to limit the speed of the motor from going beyond a MAX\_RPM value, despite any further increase in analog value input from the potentiometer.

This means I have to continously check the RPM value (the RPM code works fine, so I will not include it).

If the motor speed hits the MAX\_RPM value, any further potentiometer input should be ignored. To achieve this, I figured I need to hold the analogWrite function value constant thus holding the speed constant.

In the event that I turn the potentiometer in the reverse direction, this should decrease the PWM value thus also decreasing the speed.

I have written the code to achieve the process described above to no avail i.e., increasing potentiometer input causes the speed to go beyond the MAX\_RPM value which is undesired.

In this project, I am developing a **rev limiter** of sorts.

Please help me figure out the problem in my code.

```
#define MAX_RPM 500
    #define MAX_RPM_PWM_MAPPED_VALUE 15

    //In this case, I first ran the motor while monitoring the speed and the potentiometer value
    //While doing this, I noted the potentiometer value at which the MAX_RPM is obtained
    //I then defined this potentiometer value as MAX_RPM_PWM_MAPPED_VALUE
    //With MAX_RPM_PWM_MAPPED_VALUE, I would directly limit the value written to the analogWrite function
    //

    MOSFETMODULE = 4;
    potentiometer = AO;

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

    void loop()
    {
        val = analogRead(potentiometer);  //Read potentiometer value - represents accelerator input
        mappedValue = map(val, 0, 1023, 0, 255); //Map the 10 bit value to 8 bit equivalent

        if(RPM >= MAX_RPM)
        {
            analogWrite(MOSFETMODULE, MAX_RPM_PWM_MAPPED_VALUE);
        }
            else
            {
              mappedValue = constrain(mappedValue, 0, MAX_RPM_PWM_MAPPED_VALUE);
              analogWrite(MOSFETMODULE, mappedValue); //Output a PWM signal to the MOSFET trigger module
            }
    }

```

# Answer
> 1 votes
Your problem is that you don't know what ADC value maps to the maximum RPM. If you did you wouldn't need to know the RPM.

What you have here is a "feedback loop", and what you need is some method of using the detected RPM to control the speed of the motor.

You need to decouple the potentiometer from the analogWrite completely - the potentiometer should be setting the desired RPM, not the value being sent to set the RPM.

So if you want an RPM range from, say, 0 to 100RPM you can `map()` the `analogRead()` to the values 0-100. Then you can examine the actual RPM and adjust the value you send to the PWM accordingly - if the motor is too fast then slow it down. If it's too slow then speed it up.

There's a special method that is used for this: PID. And there's a library that does it for you too:

The potentiometer provides the "set point", the RPM detection provides the "input", and the PID library gives you the "output" to feed to the `analogWrite()`. You need to then provide the special magic "tuning" parameters to give the best control over your motor.

---
Tags: arduino-mega, arduino-ide, pwm, adc, mosfet
---


title: Portenta pinouts for ADC

text:
# Question
Title: Portenta pinouts for ADC
I wanted to have your comments about one of my questions.

I am currently working on the sketch for the Arduino Portenta H7. However, due to my poor electrical background, I would like to ask your opinion about the pinouts. Below you can find the pinout diagram from the document page 1 available at the below link.

https://content.arduino.cc/assets/Pinout-PortentaH7\_latest.pdf

I am a bit confused about the analog pins. As the diagram and color-coding show ADC A0 ( available on the high-density connector) and analog pin A0 both separately. What can be the difference between them ? or maybe I am interpreting wrong.

Because, on an ordinary Arduino board ( as far as I found), we have the Analog pins which are used for the ADC too. However, here in the Portenta pinout diagram, we have ADC A0 and analog A0 separate?

I thank you for your time and opinion.

# Answer
The "high density" connectors expose every pin of the MCU. The pins around the edge of the board duplicate just the immediately useful ones.

Every pin that is on the edge of the board is also on the high density connectors somewhere.

Why have the pin on both connectors? Simple: if you want to use it in a breadboard or with jumper wires then you want the useful pins on the edge. If you want to use a plug-in board then you don't want to have to connect to both the high density connectors *and* the breadboard connectors, that would just be really awkward (since both have completely different height profiles). So everything is on the high density connectors for plug-in boards, and the useful ones are also on the breadboard headers.

A0 is the Arduino name for the pin. ADC is the function of the pin. The A of ADC stands for Analog. It's a pin that Converts Analog to Digital. It's an Analog to Digital Conversion pin - ADC.
> 1 votes

# Answer
It is just the one pin that they marked two times as `A0`. I think they just wanted to make clear it's the same pin, maybe that people don't get confused, but in my opinion it's just more confusing.
> 0 votes

---
Tags: arduino-ide, pins, adc, analog-sampling, arduino-portenta-h7
---


title: random() Function isn't random at all

text:
# Question
Title: random() Function isn't random at all
I'm using the `random()` to generate random coordinates for coins in a simple game console. The problem here is that the `random()` function is not generating random numbers, since the coin is at the same coordinates every single time I upload it. I am using the Adafruit GFX library with the Adafruit 1.44" Color TFT LCD Display. Here is my code (sorry, it's kind of long).

```
//necessary libraries
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

//colors
#define BLACK    0x0000
#define BLUE     0x001F
#define RED      0xF800
#define GREEN    0x07E0
#define CYAN     0x07FF
#define MAGENTA  0xF81F
#define YELLOW   0xFFE0
#define WHITE    0xFFFF

//pins
#define TFT_CS  10
#define TFT_RST  9
#define TFT_DC   8

//joystick variables
const int VRxPin = A1;
const int VRyPin = A0;
const int SWPin  = 7;
bool mov = false;

//data read from joystick pins
int x = 0;
int y = 0;
int SW = 0;

// X and Y coords for entities
int playerx = 50;
int playery = 50;

long coinx;
long coiny;

//game variables
int score = 0;

//defining the tft class
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

//useful text function
void output(char *text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//there is probably a better way to do this but im too lazy to find it
void num_output(int text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//clears screen
void clear() {
  tft.fillScreen(BLACK);
}

//setup (lcd init & startup screen)
void setup() {
  Serial.begin(9600);
  pinMode(SWPin,INPUT_PULLUP);
  tft.initR(INITR_GREENTAB);

  long coinx = random(20, 100);
  long coiny = random(20, 100);

  clear();
  output("RAMBUTAN", 40, 60, RED);
  delay(1000);
  clear();
  tft.fillRect(playerx, playery, 5, 5, WHITE);
  tft.fillCircle(coinx, coiny, 5, YELLOW);
}

void loop() {
  //reads data from joystick pins every single tick
  int VRx = analogRead(VRxPin);
  int VRy = analogRead(VRyPin);
  int SW = digitalRead(SWPin);

  //converts joystick pin data into directions
  if (VRx > 250 && VRx < 750 && VRy > 250 && VRy < 750) {
    // middle
  } else if (VRx > 511.5 && VRy < 750 && VRy > 240) {
    // right
    playery -= 5;
    mov = true;
  } else if (VRx < 511.5 && VRy < 750 && VRy > 240) {
    // left
    playery += 5;
    mov = true;
  } else if (VRy > 511.5 && VRx < 750 && VRx > 240) {
    // up
    playerx += 5;
    mov = true;
  } else if (VRy < 511.5 && VRx < 750 && VRx > 240) {
    // down
    playerx -= 5;
    mov = true;
  } else {
    mov = false;
  }

  if (mov == true) {
    clear();
    tft.fillRect(playerx, playery, 5, 5, WHITE);
    num_output(score, 10, 10, WHITE);
    tft.fillCircle(coinx, coiny, 5, YELLOW);
    mov = false;
  }
  delay(100);
}

```

# Answer
You are correct, `random()` *isn't* random - it's *pseudo random*. It returns successive results from a mathematical formula which, to all intents and purposes, is random. It's also predictable, as you have seen.

The formula has a starting value, called the *seed*, which you can choose your self. Changing that *seed* gives you a different sequence of random-like numbers.

So the trick is to set the *seed* to something that is truly random. One common source of randomness, or *entropy*, is an unconnected ADC input:

```
randomSeed(analogRead(A3));

```

You can read more about the `randomSeed()` function here.
> 1 votes

# Answer
As an alternative to Majenko's answer, this is how I generate random n-bit-numbers: for each of the n bits I read the chip temperature (which is pretty noisy), take the least significant bit of the reading and assign it to the corresponding bit in the number. The results are sufficiently random for my purpose at least.
> 0 votes

---
Tags: programming, arduino-nano, c++
---


# Question
Title: ld.exe:linker_script.ld:138 cannot move location counter backwards | ArduinoFFT Error
Board: Arduino Nano 33 BLE Sense

I'm pulling PCM data from an onboard microphone and running it through the arduinoFFT library (version 1.5.6) to obtain a spectrogram. Since the arduinoFFT library requires the data be an array of doubles, I've converted the data from short to double, and started the FFT process. The FFT.Windowing() function worked fine, but I get the error at the FFT.Compute() function call (line 77). The error goes away when I remove the function call. The error:

```
Found 25 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <arduinoFFT> 1.5.6
|-- <PDM> 1.0
Building in release mode
Linking .pio\build\nano33ble\firmware.elf
c:/users/benlu/.platformio/packages/toolchain-gccarmnoneeabi/bin/../lib/gcc/arm-none-
eabi/8.2.1/../../../../arm-none-eabi/bin/ld.exe:linker_script.ld:138 cannot move location counter
backwards (from 000000002004a470 t
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nano33ble\firmware.elf] Error 1

```

And the code:

```
#include "Mic.h"
#include <arduinoFFT.h>

// FFT

arduinoFFT FFT = arduinoFFT(); /* Create FFT object */
/*
These values can be changed in order to evaluate the functions
*/
const uint16_t samples = 16128; //This value MUST ALWAYS be a power of 2
const double signalFrequency = 16000;
const double samplingFrequency = 16000;
const uint8_t amplitude = 100;
/*
These are the input and output vectors
Input vectors receive computed results from FFT
*/
double vImag[samples] = {0};

// buffer to read samples into, each sample is 16-bits
short* sample_buffer;

// number of samples read, read from Mic class on loop
volatile int samples_read;

// The length of the buffer to use. Currently set to 4 seconds.
int buffer_size = 16000;
double double_buffer[16384] = {};

// Instantiate
Mic mic;

// DO NOT PRINT INSIDE THIS FUNCTION - Causes it to hang.
void onPDMdata() {
  mic.sample();
}

void setup() {
  Serial.begin(115200);
  while (!Serial);
  PDM.onReceive(onPDMdata);
  PDM.setBufferSize(16128);

  Serial.println("3...");
  delay(1000);
  Serial.println("2...");
  delay(1000);
  Serial.println("1...");
  delay(1000);
  Serial.println("Listening!");

  mic.begin();
}

void loop() {

  // wait for samples to be read
  samples_read = mic.samples_read();

  // If desired buffer size is reached.
  if (samples_read >= buffer_size) {
    // Retrieves audio buffer
    sample_buffer = mic.sample_buffer();

      // print samples to the serial monitor or plotter
      for (int i = 0; i < samples_read; i++) {
        double_buffer[i] = (double)(sample_buffer[i]);
        Serial.println(double_buffer[i]);
      }

    Serial.println("---------- SAMPLE BREAK ----------");

    FFT.Windowing(double_buffer, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
    FFT.Compute(double_buffer, vImag, samples, FFT_FORWARD); /* Compute FFT <--------------------- THIS LINE */
    // FFT.ComplexToMagnitude(double_buffer, vImag, samples); /* Compute magnitudes */

    // delay for data collection only, comment when not collecting
    delay(1000);
    Serial.println("Listening!");

    // clear the read count and resume recording
    mic.clear_buffer();
  }
}

```

Where can I start to troubleshoot this issue? I've not had to deal with linker errors before, so any pointers would be greatly appreciated. Thanks in advanced!

# Answer
## Short Version

The short answer is that you've exhausted RAM.

These two arrays alone:

```
const uint16_t samples = 16128;
double vImag[samples] = {0};
double double_buffer[16384] = {};

```

...are occupying (16128 + 16384) * 8 == 260096 bytes of memory. There's only 262144 bytes of RAM in entirety.

The way the linker script is set up at least 1024 bytes are reserved for the stack, and there is no doubt at least another kByte in use somewhere. In the Mbed OS and Arduino core files if nothing else.

As for why it fails only when you call `Compute`, that comes down to the compiler optimizer discovering that one (perhaps both) of your arrays are not actually used and so not entering into the mix when the linker is run.

## Details

In theory, you should have gotten a *somewhat* nicer and easier to understand message from an `ASSERT` in the linker script:

```
ASSERT(. <= (ORIGIN(RAM) + LENGTH(RAM) - 1024), "heap region overflowed into stack");

```

So, you should have seen an error "heap region overflowed into stack" on your screen instead, which is maybe not the easiest thing for an Arduino user to decipher, but heap and stack are terms likely to be recognizable as memory-related sooner or later.

However, the linker executable shipped with the current version 1.3.2 of the Arduino core for Mbed ignores `ASSERT` statements completely; I have tested this (and tested my understanding of my test using an amd64 linker). Presumably, there's a build option for the linker or a command-line or configuration file option that controls that, but I haven't found it yet. In any case, it ignores a helpful `ASSERT` and instead proceeds to fail on line 138 mentioned in the error message:

```
 . = ORIGIN(RAM) + LENGTH(RAM) - 1024;

```

You can see it involves the same expression, just without a useful message if something goes wrong. The "location counter" in the message is a linker related term that roughly means "where the next thing will be placed in memory" as it cobbles together your final executable from separately compiled chunks. You've used so much RAM in your program that the location counter has been pushed past where the linker script wants to place the `__HeapLimit` symbol, 1K from the end of the MCU's RAM. The location counter is supposed to increase monotonically. So, evaluating this expression results in an erroneous attempt to "move location counter backwards".
> 2 votes

---
Tags: compiler, linker
---


# Question
Title: Arduino with bmp280 sensor not entering void loop
I've been working on a project in which I need to know my altitude. For this purpose I've been using the BMP280 sensor. But I have an issue.

I've been trying to test if the sensor works with the program "bmp280\_sensortest.ino", already included in the library. When I open the serial monitor the message "BMP280 Sensor event test" is displayed, indicating that there is a valid sensor on board. Below that the temperature, pressure and altitude data should be displayed, but nothing happens.

I've added a simple `Serial.print("hello")` at the start of `void loop()`, but not even that is displayed. The program doesn't seem to enter `void loop()` and I don't know why.

Here is the code:

```
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>

Adafruit_BMP280 bmp; // use I2C interface
Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor();
Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor();

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 Sensor event test"));

  if (!bmp.begin()) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
    while (1) delay(10);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */

  bmp_temp->printSensorDetails();
}

void loop() {
  sensors_event_t temp_event, pressure_event;
  bmp_temp->getEvent(&temp_event);
  bmp_pressure->getEvent(&pressure_event);

  Serial.print("hello");
  Serial.print(F("Temperature = "));
  Serial.print(temp_event.temperature);
  Serial.println(" *C");

  Serial.print(F("Pressure = "));
  Serial.print(pressure_event.pressure);
  Serial.println(" hPa");

  Serial.println();
  delay(2000);
}

```

Any reply is greatly appreciated. edit:

if I remove `!bmp.begin()`

from the if statement and replace it with a 1 it enters the void loop but it displays 0°C and 0pa

# Answer
It could be a faulty library/sensor, most likely the sensor, sometimes sensors can begin but then another connection could be faulty or the chip itself is faulty and so the Arduino might just be waiting forever for a response that will never come.

To see where it gets stuck, you can add Serial.println(F("1")); after bmp.setsampling then Serial.println(F("2")); after bmp\_temp-\>printSensorDetails to see where exactly it's getting stuck

One thing I also like to do is to buy two/three of a sensor, so that I can replace a sensor with another one. That way if a piece of code doesn't work for all three sensors then I can pretty sure it's a problem with the code and not the device. Not sure if you have a spare sensor to try that but I would recommend it in future
> 1 votes

---
Tags: sensors, communication, pressure
---