text:
1 Button + Potentiometer
Sketch
arduino-uno programming
1 Button and 1 Potentiometer
Sketch: Each time the button is pressed, acquire the value of the potentiometer in a array of 10 positions of these values do the average and print it on the serial monitor or display.
At the end print the average (sum of values / 10)
#define BUTTON 5
#define ARRAY_SIZE 10
int counter = 0;
int valori[ARRAY_SIZE];
int pinPotenziometro = A0;
int statoPresenteBottone = LOW; //why so LOW?
float media = 0.0;
void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT);
  for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
}
void loop() {
  if (counter > ARRAY_SIZE) {
    counter = 00;
    media = 0.0; // when we fill array fully - we start again
    for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
  }
  statoPresenteBottone = digitalRead (BUTTON);
  while (statoPresenteBottone == HIGH) {
    valori[counter] = analogRead(A0);
    media = media + valori[counter];
   Serial.print("Average: ");
   Serial.println(media / counter);
   Serial.print("Button pressed times: ");
   Serial.println(counter);
    statoPresenteBottone = LOW;
    counter++;
  }
}

Can u guys edit the Sketch? Cuz if u try It on tinkercad with adding a potentiometer+ a button u will see he does the average after each value we acquired but i need to do that at the end...
I dont need explaining of how i should i do It cuz the teacher did that already but these are my skills D: if u guys can edit the sketch and solve this problem would be cool thx

Duplicate of the OPs previous question: Schematic: 1 Button and 1 Potentiometer Sketch

So your teacher explained to you, how you should solve the problem? And now you are asking as to do the rest of your homework for you? And you ask us to build the project ourselves in tinkercad? Sorry, we are not here to do other peoples homework. We are not a free code writing/editing service. And when you are talking about a tinkercad simulation, you should provide a link to a public tinkercad project, that you build. I don't have an account there and I also don't want to build up the project from your description. Please provide such things in your question, if you want good answers.

basically there is AN array of 10 positions every time we press the Button he acquires the value of the potentiometer (we do that for 10 times) at the end he does the sum of values/array_size and print the average , the link of public project Is : https://www.tinkercad.com/things/cNjZS9Oz02j-progetto-media-varianza-da-finire-d-uwu-uwu-uwu-lt3/editel?sharecode=Bs8_pG7HsyANlYI4yp9W2cuaJ20dIlfdgQmPhO1U1zY

You didn't actually answer to the other things that I wrote. Though your tinkercad project doesn't seem to be public. I cannot see it without login in.

ah 1 sec i will update link

Please put that link in your original question. This one will be closed soon, since it is basically the same question, as before.

Ok but its public already the link y can edit


text:
Uploading bootloader on ATmega328P SMT package using Arduino Uno
I have been trying to upload bootloader on ATmega328P SMT package on a custom PCB using Arduino Uno as ISP, I was quite successful.
I have Googled a lot and have tried numerous ways, sometimes I was able to successfully upload the bootloader, but I am not able to upload the sketch am getting "avr sync error".

What kind of bootloader should I use for this particular package?
How should I upload the sketches into the chip?

Are you using a serial converter to upload the sketch?

I removed the chip on arduino uno and tried uploading sketchs using tx ,rx and reset pin.

Are you using a bootloader for the Uno, e.g. Optiboot?

I am using optiboot(arduino duemilanove or nano w/atmeg328) as bootloader i also tried optiloader.I was able to upload the bootloader on both the methods

Well, okay, but you need to behave like an Uno, since you're using an Uno as the frontend.

Do you have a crystal of the same frequency on your board?  Try making a serial echo sketch and uploading that using ISP (instead of bootloader) to test that your board works and the serial connection works.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Can the Adafruit PN532 NFC/RFID be used to read Gen-2 EPC class RFID Tags?
I used Mifare Classic cards on a previous project and it worked brilliantly with the RIFD/NFC shield and Arduino Uno. I came across a Gen 2 EPC Class 1 RFID tags. This tags are long range ones. They use an IC chip called Alien Higgs3. I know that the shield itself is not capable of reading from a long range. I would just like to know if the shield is just able to read this type of tag even in close contact.
Is there a UHF RFID Reader that I can use to connect it with the Arduino and read these tags?
Any advice or suggestions are welcome. Thank alot.
RFID Tag Specifications:
Protocol- EPC Class 1 Gen2
Frequency- 860-960 MHz
IC Type (chip)- Alien Higgs3

It can not. The frequencies are different: 13.56MHz vs.868–956 MHz.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Is there some sample code for operating a servo with an Adafruit Motor Shield?
I have an Adaruit Motor Shield v2, and a Tower Pro SG92R micro servo. I've got it setup so the shield works with my Arduino Uno, and I've successfully tested using other types of motors on the shield. I could not find any sample code for working with a servomotor though. The shield has two dedicated spots for a servo (labeled "Servo 1" and "Servo 2"). I'm planning to use wall wart transformer to power the motor separately from the Arduino. Any pointers/links to documentation/sample code would be appreciated.

Does the standard servo example work?

With the shield mounted on the Arduino, I don't have access to those pins. Also I if I understand correctly, that would not let the servo be powered by a separate power supply.

On the Motor shield the servo headers are directly connected to pins 9 and 10 (I think 9 is servo 2 and 10 is servo 1).  So you can use the standard servo examples using pins 9 and 10.
If you need to power the servos with an external power supply you must cut a trace on the back of the board -- the silk screen tells you where to cut.  Then you need to connect power to the "Opt Servo" input.
The power to the servos is not changed by the power jumper used for the DC/stepper motors.


text:
I get an error?
void setup()
{
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
if(Serial.available()>0)
{s_num =Serial.read();}
if(s_num=='0'){
digitalWrite(13,HIGH);
delay(100); //the specified time for 0
digitalWrite(13,LOW);
delay(100);}
if(s_num=='1'){
digitalWrite(13,HIGH);
delay(200);
digitalWrite(13,LOW);
delay(200);}
if(s_num=='2'){
digitalWrite(13,HIGH);
delay(300);
digitalWrite(13,LOW);
delay(300);}
char s_num; if(s_num=='3'){
digitalWrite(13,HIGH);
delay(400);
digitalWrite(13,LOW);
delay(400);}
if(s_num=='4'){
digitalWrite(3,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);}
if(s_num=='5'){
digitalWrite(13,HIGH);
delay(600);
digitalWrite(13,LOW);
delay(600);}
if(s_num=='6'){
digitalWrite(13,HIGH);
delay(700);
digitalWrite(13,LOW);
delay(700);}
if(s_num=='7'){
digitalWrite(13,HIGH);
delay(800);
digitalWrite(13,LOW);
delay(800);}
if(s_num=='8'){
digitalWrite(13,HIGH);
delay(900);
digitalWrite(13,LOW);
delay(900);}
if(s_num=='9'){
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
delay(1000);}
digitalWrite(13,LOW);
s_num=10;
}

If you are getting a compilation error, you need to include the full error message (including the information, where the error happened) in your question.

One tip to prevent these kind of error: next time align the { and } and you see the error very fast:
void setup()
{
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}

void loop()
{
  char s_num;
  if(Serial.available()>0)
  {
    s_num =Serial.read();
  }

  if(s_num=='0')
  {
    digitalWrite(13,HIGH);
    delay(100); //the specified time for 0
    digitalWrite(13,LOW);
    delay(100);
  }

  if(s_num=='1')
  {
    digitalWrite(13,HIGH);
    delay(200);
    digitalWrite(13,LOW);
    delay(200);
  }

  if(s_num=='2')
  {
    digitalWrite(13,HIGH);
    delay(300);
    digitalWrite(13,LOW);
    delay(300);
  }

  if(s_num=='3')
  {
    digitalWrite(13,HIGH);
    delay(400);
    digitalWrite(13,LOW);
    delay(400);
  }

  if(s_num=='4')
  {
    digitalWrite(3,HIGH);
    delay(500);
    digitalWrite(13,LOW);
    delay(500);
  }

  if(s_num=='5')
  {
    digitalWrite(13,HIGH);
    delay(600);
    digitalWrite(13,LOW);
    delay(600);
  }

  if(s_num=='6')
  {
    digitalWrite(13,HIGH);
    delay(700);
    digitalWrite(13,LOW);
    delay(700);
  }
  if(s_num=='7')
  {
    digitalWrite(13,HIGH);
    delay(800);
    digitalWrite(13,LOW);
    delay(800);
  }
  if(s_num=='8')
  {
    digitalWrite(13,HIGH);
    delay(900);
    digitalWrite(13,LOW);
    delay(900);
  }
  if(s_num=='9')
  {
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);
    delay(1000);
  }
  digitalWrite(13,LOW);
  s_num=10;
}

As you can see char s_name needs to be be declared in the front of the method as you need it in the second line, so you get the following code that compiles:
void loop()
{
  if(Serial.available()>0)
  {
    s_num =Serial.read();
  }

  if(s_num=='0')
  {
    digitalWrite(13,HIGH);
    delay(100); //the specified time for 0
    digitalWrite(13,LOW);
    delay(100);
  }

  if(s_num=='1')
  {
    digitalWrite(13,HIGH);
    delay(200);
    digitalWrite(13,LOW);
    delay(200);
  }

  if(s_num=='2')
  {
    digitalWrite(13,HIGH);
    delay(300);
    digitalWrite(13,LOW);
    delay(300);
  }
  char s_num;

  if(s_num=='3')
  {
    digitalWrite(13,HIGH);
    delay(400);
    digitalWrite(13,LOW);
    delay(400);
  }

  ...
}

Now you also can see that you process the s_num variable even if there is not a new value from the serial class, so you should put it probably inside, getting:
void loop()
{
  if(Serial.available()>0)
  {
    char s_num =Serial.read();

    if(s_num=='0')
    {
      digitalWrite(13,HIGH);
      delay(100); //the specified time for 0
      digitalWrite(13,LOW);
      delay(100);
    }
  }
}

The last statement s_num=10; does not anything.
Now, to greatly reduce your code, all digits perform more or less the same code. You can combine this by calculating the delay time (0 -> 100, 9 -> 1000), and you get the following code:
void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
  if (Serial.available() > 0)
  {
    char s_num = Serial.read();
    if ((s_num >= '0') && (s_num <= '9'))
    {
      uint16_t delayTime = (s_num - '0' + 1) * 100;
      digitalWrite(13, HIGH);
      delay(delayTime);
      digitalWrite(13, LOW);
      delay(delayTime);
    }
    else
    {
      digitalWrite(13, LOW);
    }
  }
}

By subtracting '0' from a character digit ('0' to '9'), you get its value.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Record data to SD card with ATtiny85
An application of ATtiny with SD card is complicated due to missing of hardware SPI in attiny.
The "ATmega" code for creating of a "SD file" is:
#include <SPI.h>
#include <SD.h>

File file;
int const pinCS = 2;

void setup()

{
SD.begin(pinCS);
file = SD.open("Test.txt", FILE_WRITE);
file.println("anything");
file.close();}

void loop()
{}

This code creates on SD card a file "Test.txt" and to this file records text "anathing".
Is it possible to rewrite this code for "ATtiny85"?

The ATtiny85 has no dedicated SPI port. It has, however, an “USI” port
(Universal Serial Interface) that should be able to do the job. The lack
of SPI should not be a problem, but the lack of memory will be a
problem.
Files on an SD card are written one sector (512 bytes) at a time.
For this reason, the SD library uses a 512 bytes buffer in RAM.
That cannot work on an ATtiny85, as the buffer would consume the whole
RAM.
You may be able to do something using the Petit FAT library,
provided you can work around the severe limitations of its write
interface:

The write function has some restrictions listed below:

Cannot create file. Only existing file can be written.
Cannot expand file size.
Cannot update time stamp of the file.
Write operation can start/stop on the sector boundary only.
Read-only attribute of the file cannot block write operation.

The first two points imply that you would have to create the file and
allocate the sectors for it in your computer.
This blog post mentions a port of the library to the Arduino
environment, and its use on an ATtiny84, which has similar capabilities
to the ATtiny85 (only with more pins).

Thank you of this relevant response. No problem, ATmega operates good in this connection, but ....attiny is smaller and sympatric. It is pity, the limitations of the "Petit.." is problem. Thank You.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

Your code doesn't compile with the plain "IRRemote" library from the manager, at least not with the version I have installed.  Rather than guess at which library/fork/version, I figured I'd ask, which is it?

I have IRremote by shirriff, z3t0 and ArminJo. I just updated it to 3.0.0 although I'm not sure what version I had before updating, 2.6 or something... It now doesn't compile :/, do you know why that is? Thanks

I have used the website: https://github.com/Arduino-IRremote/Arduino-IRremote to update my code to the 3.0 version but there is still one line which returns an error: IRsend.sendNECMSB(shootCode, 32); gives the error: expected unqualified-id before '.' token. Do you know how to fix that or will I need to send you the whole sketch again now I have updated it?

I'm not sure I want to go down that rabbit hole in comments.  I just needed to know how to get your original code to compile.  I installed 2.6.1 and it compiles.

Okay, 2.6.1 sounds likely, but once an Arduino sends an IR code, it no longer receives them even though I have the enable ir line in it. Any ideas?

That sort of thing goes in the question.  Which you already have in the question.  Which I've read already.  What I'm wondering is exactly where in your code does it stop?  If you have this connected to serial you can sprinkle your code with Serial.println(__LINE__); see line numbers print.  Move them around until you've narrowed down the exact line (or lines if its stuck in a loop in code you wrote) where the code stops executing.

The code never gets stuck as such, after the "game" has ended it returns to the main loop and works fine. Even if I have send IR in that loop, the code doesn't get stuck somewhere, it just disables the receiver so more IR cannot be received.

Well, I have it compiled and uploaded to a board, but I have no practical way to test it to even see what you're seeing.  I'd replace the IR receiving code with Serial input for testing, but I expect having done that the problem will be gone or different.  If you were on IRC I'd take you through transforming the code into something cleaner, but there's not really a lot I can do here in this format.  I do think it's nice that you want to do something for your cousins though.  If you cut this down into something more managable someone (maybe me) will have useful input.

Thanks, I tried using the serial input and as you expected, the problem disappeared. What's IRC? The problem is when I cut it down into a smaller program I don't have the same problem, I'll try reducing the contents of the program bit by bit (removing sound, then LCD etc) to see if I can identify what makes it work in my small sketch but not the large project. Thanks again.

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.


text:
Touch sensor trouble
I need help I use Touch Sensor(T)v.0 and it always receives a signal not matter I touched it or not.
Here is the code.
#define TOUCH_PIN 7
int touchVal = 0;

void setup() {
   Serial.begin(115200);
   pinMode(TOUCH_PIN, INPUT);
}

void loop() {
   touchVal = digitalRead(TOUCH_PIN);
   Serial.println(touchVal);
   delay(200);
}

What touch sensor do you have? Please provide a link to the datasheet or to the product page at your reseller. How did you connect it? Is it active HIGH or active LOW? (meaning if touching it makes the output HIGH or LOW, both is possible)

https://aliexpress.ru/item/32800470168.html?&sku_id=64142657896

Honestly, I don't  know it's active HIGH or active LOW but it doesn't chengs value when I touched it always print 1

how do you know that the output is digital ?

why does your code not look for a change in the output?

I just want understand does my sensor work or not that's why I haven't output. In this line, I just print the value. Serial.println(touchVal);


text:
Arduino Serial.readString() trouble
Hello everyone I write my code and have some troubles.
When I write on in my serial monitor my buzzer condition wasn't changed.
Can you help me realize the reason. I wrote code with int type and it works with Serial.parseInt() function properly.
String ask="Please enter buzzer condition";
int buzzerPin=2;
String state;
void setup() {
  pinMode(buzzerPin,OUTPUT);
  Serial.begin(115200);

}

void loop() {
 Serial.println(ask);
 state=Serial.readString();
 Serial.println(state);
 while(Serial.available()==0){

 }
 if(state=="on"){
  digitalWrite(buzzerPin,HIGH);
 }
 if(state=="off"){
  digitalWrite(buzzerPin,LOW);
}
}

What line ending have you selected in the Serial Monitor? And why do you wait for more data to arrive after you read a string from Serial?

@chrisl thank you you really help me I find my mistake

You need to use Serial.readStringUntil('\n') instead of Serial.readString if you use the Arduino IDE's serial monitor (where a \n is added as termination character when you press enter).
Also remove that while(Serial.available()==0). It will wait as long as there are any bytes in the serial buffer and as you don't Serial.read() within the loop, the buffer will not be emptied. So, if anything is received while Serial.println(state) is called or if you send two termination characters, the program will be stuck in that loop.


text:
how to use Nano instead of Uno3 to operate DC motors
OK I have the Logitech G29 Wheel and Pedal setup that I use for my Racing Sim. On YouTube there is a gentleman (amstudio) who has used motors on the Gas and Brake pedals to give some realism to the Sim. To achieve this he used a Uno 3 and a motor shield. The motors used are those that you'd find in the XBox/PS4 controllers. It's my understanding that the Uno 3, Nano and Micro are the same in its basic form, meaning that the sketch he uses can be used on all 3. If this is true then I want to use the smallest footprint to achieve the Rumble effect.
Question is how do I wire up the Nano to do this and with the motors as small as they are is it really necessary to have a motor shield or H bridges?
I have taken a picture of his Uno setup.  My aim here is to make it the smallest as it can be and still do the function of this mod' as this will be its only function. Any ideas on how best to go about this, The XBox Controller is rated at 5v @ 450mA. have included a picture showing his setup.thanks in advance

It's my understanding that the Uno 3, Nano and Micro are the same in its basic form

Not exactly. The Uno and Nano use the same chip (the Atmega328p) and have the same pins broken out. The Arduino Pro Mini also uses that chip, but I think the pinout is a bit different. But mostly a code can be reused between these boards. The Arduino Micro uses an ATmega32U4, which is a different chip. Depending on the actual code, you might not be able to just reuse the code. Then you might have to change to code to use the Micros hardware.

with the motors as small as they are is it really necessary to have a motor shield or H bridges?

I would say yes. A digital output pin of an Arduino can only supply 20mA of current over longer time (absolute maximum 40mA). Even very small motors can easily exceed that. As long as you don't know the exact needed current in worst case (like stalling the motor), you should assume, that it is more than 20mA. Also a running motor generates a lot of electrical noise and the coils can induce backcurrents, that might destroy the output hardware of the Arduino pin (for that you need a flyback diode). And lastly, if you want to change the direction of the motor, you absolutely need an H-bridge. Otherwise it is only on or off.

Question is how do I wire up the Nano to do this

With H-bridges you normally need 3 pins to control the motor:

The enable pin (often marked as EN) enables or disables the motor (run or stop). You normally use analogWrite(en_pin, speed) to control the speed of the motor. It will send a PWM signal with the given duty cycle to the enable pin.
And you have 2 input pins (often marked as IN). They give you control over the direction.

IN1 to HIGH and IN2 to LOW will give you the first direction. Reversing to IN1 LOW and IN2 HIGH will give you the other direction. This will cause the H-bridge to lead the current through the motor in different directions.
Setting them to the same value will cause the motor to break (because that will short circuit the motors coil).

So you would wire 3 output pins of the Arduino to the mentioned pins on the H-bridge. It is up to you, what you want to use here. You can use a shield (which is normally the size of the Uno), you can use other ready to use motor driver boards (there are many) or you could build your own driver with a H-bridge chip and flyback diode.


text:
Arduino IDE has no shortcut in openSUSE
I just installed the Arduino IDE in openSUSE 13.1. I am able to open the application using the run dialogue, so I know it has installed. However, there is no way to open the IDE from any application launcher. I have tried both the Kickoff and Lancelot applciation managers. I have also tried to uninstall and re-install the IDE, both through the 1-click on the Arduino website as well as through the command line.
Does anyone know why I am unable to launch the application from the launcher? Thanks in advanced for any help!

I had the same problem and this seems to work. If you right click on the Kickoff Application launcher and open 'edit applications' with KDE Menu Editor, you can 'add new item' where you want and give it a name (ArduinoIDE) and then just put arduino (small case) in the 'command' box, and shut down KDE Menu Editor, it should appear in the menu where ever you placed it. At least it did for me.


text:
Direct 5V current based on analog signal
I would like to manage many LEDs from my Arduino - 12 or so - but I do not have the available digital pins to do this. Only one LED needs to be on at one time. Instead, I was hoping to control these with an analog pin. I was wondering if there is some sort of switch out there which can take an analog signal and, based on the value, direct a 5V current to a certain LED.
I realize that I could use a second Arduino for this, but I am trying to avoid that.
Thanks in advance for any help!

Please check out this question: http://arduino.stackexchange.com/questions/117/is-there-a-way-to-have-more-than-14-output-pins-on-arduino it contains many answers enumerating several different solutions to the problem.

It should be noted that analog input pins still only output digital signals; only the PWM capable pins can emulate analog signals and they are dispersed among the digital pins.

You can accomplish this digitally with a device called a decoder. For example, the 74154 takes 4 inputs and maps those to one of 16 outputs (depending on the binary coding of the inputs). From the data sheet:

The 74HC154; 74HCT154 decoders accept four active HIGH binary address inputs and
  provide 16 mutually-exclusive active LOW outputs.

Great! I found even better results by searching for "demuliplexer". For instance, this page on the arduino site: http://playground.arduino.cc/Learning/4051 Thanks!

If you have 4 pins available, you could use charlieplexing to selectively light up 12 led.

Alternatively you could use some IC. You could use the one Greg suggested.
Or you could use a shift-register. This requires only 2 or 3 pins, an will enable you to light up any one or more leds at the same time. Most have 8 outputs, but you can connect one to the other (daisychain), so with 2 shift-registers you can individually turn on/off 16 leds. You can easily control these using arduino's shiftOut command.
You could also use a port-expander using I2C to talk to it. More complicated, and a bit more expansive. But also more powerful. It will require only 2 pins (A4, and A5).

You can use some of the analog pins to clock a shift register by defining them as a digital output.  Also two of the analog pins are also defined as I2C depending on your code. You could use 2 PCF8574s or an PCF8575 expansion board and control it that way. They can be used as inputs and outputs any order you want. There are a lot of other chips you can use to do this.  The reason I am suggesting this approach is later you will probably want to expand into other peripherals such as LCDs etc.


text:
Reading button presses with the 74HC4067E multiplexer
My project is progressing quite well, but I am having some issues reading button presses through my MUX.
The Goal
Cycle through twelve buttons and twelve LEDs. When a button is pressed, light up the corresponding LED. I have one MUX for the LEDs which is working great thanks to the stack exchange community. My button MUX is the issue.
The Symptom
I have one button hooked up to the MUX. When it is not pressed, nothing lights up - that's right. But when it is pressed, every LED lights up as it is cycled through. It is as if pressing this button for one of the MUX pins is sending a HIGH signal to all of the MUX pins.
The Pictures

^^ You can see the big honking button in the bottom right. It is connected to 5V and then the MUX pin.

^^ I have two multiplexers. The one on the left is for the LEDs and the one on the right is for the buttons (of which I currently [ha!] have only one).

The Code
// set vars for all the pins
int led_input = 0;
int led_ctrl_1 = 1;
int led_ctrl_2 = 2;
int led_ctrl_3 = 3;
int led_ctrl_4 = 4;

int btn_input = 5;
int btn_ctrl_1 = 6;
int btn_ctrl_2 = 7;
int btn_ctrl_3 = 8;
int btn_ctrl_4 = 9;

// how many MUX pins?
int players = 12;

// function to take player number and convert to control pins
void ledWrite(int led, boolean val){

    if(!val){

        digitalWrite(led_input, LOW);

    }else{

        if((led - 8) >= 0){
            led = led - 8;
            digitalWrite(led_ctrl_4, HIGH);
        }else{
            digitalWrite(led_ctrl_4, LOW);
        }

        if((led - 4) >= 0){
            led = led - 4;
            digitalWrite(led_ctrl_3, HIGH);
        }else{
            digitalWrite(led_ctrl_3, LOW);
        }

        if((led - 2) >= 0){
            led = led - 2;
            digitalWrite(led_ctrl_2, HIGH);
        }else{
            digitalWrite(led_ctrl_2, LOW);
        }

        if((led - 1) >= 0){
            led = led - 1;
            digitalWrite(led_ctrl_1, HIGH);
        }else{
            digitalWrite(led_ctrl_1, LOW);
        }

        digitalWrite(led_input, HIGH);
    }
}

// function to take player number and convert to control pins
int btnRead(int btn){

    if((btn - 8) >= 0){
        btn = btn - 8;
        digitalWrite(btn_ctrl_4, HIGH);
    }else{
        digitalWrite(btn_ctrl_4, LOW);
    }

    if((btn - 4) >= 0){
        btn = btn - 4;
        digitalWrite(btn_ctrl_3, HIGH);
    }else{
        digitalWrite(btn_ctrl_3, LOW);
    }

    if((btn - 2) >= 0){
        btn = btn - 2;
        digitalWrite(btn_ctrl_2, HIGH);
    }else{
        digitalWrite(btn_ctrl_2, LOW);
    }

    if((btn - 1) >= 0){
        btn = btn - 1;
        digitalWrite(btn_ctrl_1, HIGH);
    }else{
        digitalWrite(btn_ctrl_1, LOW);
    }

    return digitalRead(btn_input);
}

void setup(){

    pinMode(led_input, OUTPUT);
    pinMode(led_ctrl_1, OUTPUT);
    pinMode(led_ctrl_2, OUTPUT);
    pinMode(led_ctrl_3, OUTPUT);
    pinMode(led_ctrl_4, OUTPUT);
    pinMode(btn_input, INPUT);
    pinMode(btn_ctrl_1, OUTPUT);
    pinMode(btn_ctrl_2, OUTPUT);
    pinMode(btn_ctrl_3, OUTPUT);
    pinMode(btn_ctrl_4, OUTPUT);
}

void loop(){

    for(int x = 1; x <= players; x++){

        if(btnRead(x) == HIGH){

            ledWrite(x, true);
            delay(100);
            ledWrite(x, false);
        }
    }
}

I know this is a lot to trudge through, and I honestly appreciate any help you are willing to offer. Thanks in advance!

All your unused MUX input pins for the button MUX are floating. You will need to tie all of the unused inputs (those that do not have a physical button attached) to ground. Floating inputs are undefined and cause undefined output.
Also, when your attached button is not pressed, its input will also be floating. You can avoid this by connecting the input pin on the MUX to ground using a resistor. That way, when the button is not pressed the input will be low (through the resistor), and when the button is pressed it will be high (through the button connection).

Also, floating inputs will generally increase current consumption of CMOS chips.

Ah ha! The Digital Read Serial and Input Pullup Serial tutorials make more sense now. If only there was an INPUT_PULLDOWN! I should never assume that a lack of a definite signal means LOW.


text:
Controlling an LED with the 74HC4067E multiplexer
I am testing a 74HC4067E MUX setup with my Arduino Uno which I would like to use to selectively light up many LEDs, one at a time. For this first test, I am using a modified version of the blink tutorial. Essentially, I am setting the 4 control pins to digital LOW and setting the input to HIGH, through a resistor appropriate for my LED. I am also providing 5V to the Vcc pin on the MUX. I don't really know why I am doing this, but it seems to work. Here is my code:
int led_input = 0;
int led_ctrl_1 = 1;
int led_ctrl_2 = 2;
int led_ctrl_3 = 3;
int led_ctrl_4 = 4;

void setup() {
    pinMode(led_input, OUTPUT);
    pinMode(led_ctrl_1, OUTPUT);
    pinMode(led_ctrl_2, OUTPUT);
    pinMode(led_ctrl_3, OUTPUT);
    pinMode(led_ctrl_4, OUTPUT);
}

void loop() {
    // control signal
    digitalWrite(led_ctrl_1, LOW);
    digitalWrite(led_ctrl_2, LOW);
    digitalWrite(led_ctrl_3, LOW);
    digitalWrite(led_ctrl_4, LOW);

    // input signal
    digitalWrite(led_input, HIGH);
    delay(500);
    digitalWrite(led_input, LOW);
    delay(500);
}

I know, the code could be more efficient.
The blue LED is hooked up to I0 and blinks as it should. The problem comes when I try to change the control pin values. When I change it to, say 6...
// control signal
digitalWrite(led_ctrl_1, LOW);
digitalWrite(led_ctrl_2, HIGH);
digitalWrite(led_ctrl_3, HIGH);
digitalWrite(led_ctrl_4, LOW);

... and I move my LED to I6, I get no blink. I've tested all the pins and it doesn't seem like there is a signal coming from any of them. I assume that I am using the chip wrong, but I'm not sure how. Pictures of my setup follow... any help is greatly appreciated!

Arduino pin 0 maps to chip pin 1 (through resistor) as input.
Arduino pins 1-4 map to chip pins 10, 11, 14, and 13 in that order.
I have a 5V going to chip pin 24.
The LED is connected long leg to chip pin 9 in the images, the grounded.

Pins 1 & 2 are connected to the breadboard but NOT connected to the IC, as you forgot to put a wire from E to F on the breadboard for these pins, they are thus not connected to your IC.

Good eye! I will give it a run tonight. This is the second time you have solved one of my questions. I wish you would post these as answers so that I can give you credit!

Pin 15 on that MUX is the enable pin, you need to tie it to ground. Otherwise, it's just floating, and it only would have worked by accident.
Also, you state:

I am also providing 5V to the Vcc pin on the MUX. I don't really know why I am doing this, but it seems to work.

The chip needs power to work. The Vcc pin is where you give it the +5V power. Without that, it might still work, but only by accident and depending on the inputs on the other pins.

I've heard a few things about floating pins and grounding them for stability's sake. Any suggested reading to help me fully understand the subject?

@Nate It's not just stability, but the enable pin 15 is an input to the logic in the chip. The output depends on the state of all inputs as defined by the truth table in the data sheet. The enable input is pretty important and its state is undefined if you don't connect an input wire to it. If the enable input is undefined, then it follows that the output is undefined.

@Nate The exception is inputs that are marked with an X in the truth table (which indicate a "don't care" input).

It worked! It worked sporadically after I actually connected pins 10 and 11 as jfpoilpret suggested, but it works consistently with the enable pin grounded. In fact, this fixes another issue I was having - I had been needing to disconnect the 5V supply line from the arduino board in order to upload code to it. Now, that is not needed. Thanks!


text:
how to ignore a sensor being tripped the first time and start recording millis on the 2nd time it is tripped
I am building a timing system that has a start, split and finish beams with this I am using a start gate that will drop when the race starts. when it drops it will trip the 1st sensor starting to count the millis which I am using to calculate the time. I am using IR sensors to that give me the 3 times based on the millis and then I do a calculation in excel that will give me the split and finish time.
Where I am running into issues is that after the person goes through the 3 timer sensors I have to close the start gate which trips the first sensor which messes up my times for the next person.
So I need to adjust my sketch so it takes this into consideration when it starts counting the millis. Basically I am thinking it needs a line of code to have the 1st sensor == LOW once and do nothing and then on the 2nd time that same sensor is == LOW it records the millis from that point.
Below is the sketch I am working on.
//timer
unsigned long start, reaction, push, elapsed;

void setup()
{
  Serial.begin(115200);
  pinMode(2, INPUT); // start switch
  pinMode(3, INPUT); // split sensor
  pinMode(4, INPUT); // finish sensor
}

void loop(){

if (digitalRead(2) == LOW)
  {

    start = millis();

  }

  if (digitalRead(3) == HIGH)
  {

    reaction = millis();
 //   delay(200); // for debounce

  }

     if (digitalRead(4)==HIGH)
      {

       push=millis();
       delay(500); // for debounce

    Serial.print(start);
    Serial.print(",");
    Serial.print(reaction);
    Serial.print(",");
    Serial.print(push);
    Serial.println();

  }

}

Are you sure it really messes up the timing of the next person? When you reset the start gates, you code sets start to the current time. But then you you actually start the next race, you code overwrites start with the correct value. As long as you reset the gate after the last sensor is triggers (which actually prints out the times), you're fine, as far as I can see.

So what is happening is if when testing it out (just using my hand to break the beams) if I do it quickly it seems like I get a good result. but if I put the finish sensor far away from the split it gives me after calculations a number on the 1st time that is WAY too high when it should be the opposite.

So for example I get a start milli of 27083 split of 28657 finish of 29214. when I do the math to get m/s it turns out to be 1.574 from start to the split and .557 from the split to the finish...... I am not sure if this is a problem with my code or if it is a problem with my math?

Those millisecond values don't look odd to me, assuming the car is accelerating. I think you are calculating s/m not m/s. You should divide the distance (which I assume is 1m) by the number of seconds (which is 0.1574 and 0.557). Then you get an average of 0.64m/s in the first section. And an average of 1.8m/s in the second section.

The start time will default to zero, so you could change it to:
if (digitalRead(2) == LOW && start == 0)
  {

    start = millis();

  }

You could also declare start as a static in the loop: static long start = millis();. That way it gets called only the first time, and will remember the var in the rest of the loop()

with changing the sketch line to "if (digitalRead(2) == LOW && start == 0)" it seems that the first millis is always the same value as the first time it was tripped but the other sensors record what looks to be correct numbers.

I am thinking it needs a line of code to have the 1st sensor == LOW once and do nothing - that's what my suggestion does. If you want it to "reset" then you need more code. I'm not quite sure what your parameters are. How do you know you are starting a new race?


text:
AFMotor.h Throws Multiple Errors
I'm trying to get AFMotor.h working on an Arduino Uno Wifi Rev2 with a L293D Motor Shield.
However, when I install the library (regardless of whether I do it using the in-built library manager or by downloading a zip and moving it to the relevant folder), the following errors get thrown on compilation.
In file included from c:\users\charya\documents\arduinodata\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5\avr\include\avr\io.h:99:0,
                 from c:\users\charya\documents\arduinodata\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5\avr\include\avr\pgmspace.h:90,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/String.h:31,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/Print.h:24,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/Stream.h:25,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/Client.h:22,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/ArduinoAPI.h:29,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/Arduino.h:23,
                 from sketch\code.ino.cpp:1: C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:49:30: error: 'CS01' was not declared in this scope
     #define MOTOR34_8KHZ _BV(CS01)              // divide by 8
                              ^ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:52:33: note: in expansion of macro 'MOTOR34_8KHZ'
     #define DC_MOTOR_PWM_RATE   MOTOR34_8KHZ    // PWM rate for DC motors
                                 ^~~~~~~~~~~~ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:156:47: note: in expansion of macro 'DC_MOTOR_PWM_RATE'    AF_DCMotor(uint8_t motornum, uint8_t freq = DC_MOTOR_PWM_RATE);
                                               ^~~~~~~~~~~~~~~~~ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:49:30: note: suggested alternative: 'B101'
     #define MOTOR34_8KHZ _BV(CS01)              // divide by 8
                              ^ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:52:33: note: in expansion of macro 'MOTOR34_8KHZ'
     #define DC_MOTOR_PWM_RATE   MOTOR34_8KHZ    // PWM rate for DC motors
                                 ^~~~~~~~~~~~ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:156:47: note: in expansion of macro 'DC_MOTOR_PWM_RATE'    AF_DCMotor(uint8_t motornum, uint8_t freq = DC_MOTOR_PWM_RATE);
                                               ^~~~~~~~~~~~~~~~~ exit status 1 Error compiling for board Arduino Uno WiFi Rev2.

I've also attached an image of the error if that's easier to read. I have no code written, and I am only importing the library and compiling it.
What am I doing wrong? I'm unsure what's even happening.

Looks like the library doesn't support the newer MegaAVR chips, and the "compatibility layer" either isn't working or you have it turned off.

have you examined any example code that may be included with the library?

I have the same problem.
When I am using an Arduino Uno board the sketch is compiled without errors.
When I am using an Arduino Wifi Rev 2 board I get the same error messages.
My feeling is, that the AFMotor library is not compatible for Arduini Wifi 2 boards.


text:
I'm trying to use a E18-D80NK but the output is always 1
i'm trying to use a E18-D80NK sensor with arduino but the output is always at 1, i really don't understand why
This is my code :
int irPin2 = 8;// define pint 2 for sensor

void setup() {
  Serial.begin(9600);// setup Serial Monitor to display information
  pinMode(irPin2, INPUT);// define pin as Input  sensor
}

void loop() {
  int out = digitalRead(irPin2);// read the sensor

    Serial.println(out);

  delay(250);
 // E18-D80NK Obstacle Sensor
}

and circuit:

What do you see when you attach an oscilloscope or a volt meter to the sensor? Does the LED on the sensor flash when you place an object in front of the sensor?

Unfurtunately i have not this facility but on arduino terminal i see all the time 1 in output

A cheap digital voltmeter (better: estimator) or an inexpensive DSO138 style oscilloscope will save your head from time to time...

do you see any error in my project? this is the datasheet http://www.energiazero.org/arduino_sensori/wiring%20the%20e18-d80nk%20infrared%20distance%20ranging%20sensor.pdf

There are a few possibilities for what is wrong:
1) The wiring may be wrong: the datasheet you reference lists two types (red,black,yellow) and (blue,brown,black) but in your pic it looks like you have (blue, grey, black).  I wouldn't assume the color coding of the sensor wires are correct.
2) The "pull-up" resister mentioned in the data sheet referenced (and included schematic) is not functioning as a pull-up resistor.  I would get rid of the resistor and plug the digital-output wire of the sensor directly into the arduino input.   Also, try configuring the input with pull-up like:  pinMode(irPin2, INPUT_PULLUP);
The Arduino inputs are high impedance and typically do not need a series resistor.

Your second point is probably the problem. The wiring diagram in the datasheet is wrong. The signal line needs a pull-up (either internal or external).

Thank you for your help, i tried to plug the digital-putput wire directly into the arduino input but it doesn't work, the output is still at "1" every time i put an object in front of the sensor

Then possibility 1) above is likely the issue.   There are not that many combinations so with trial and error you should be able to find the correct wiring arrangement.

i tried different combinations but that doesn't work.. i think that my sensor could be defective

Or perhaps the sensitivity adjustment on the sensor needs adjustment.

Your sensor pull low and not high, normally they pull high , I did however buy a few that is permanently on and then switch of ( pull low) when object in range.


text:
little Code problem Servocity SPT 400 tilt kit
I hope you are in a helpful mood, today.
I have run into a little problem with my project. I wanted to mount my camera on a Servocity SPT 400 tilt kit  and control the thing via a bluetooth connection. The setup is as follows I have an Arduino Uno V3 board with an HC - 05 bluetooth module and hooked a Hitec HS-5485HB servo to the board.
Pretty straightforward but I managed to make it work as intended so far.

Here is a picture of how everything is connected, since it partially works I think it's not completely wrong.
The problem starts here though, the Servocity SPT 400 tilt kit comes with an external potentiometer,
The instructions sheet says to cut the internal potentiometer cables that were connected to the servo circuits and solder the three cables (red, yellow and green) to the external potentiometer.
With the coding skills I made the tilt mechanism move a few mm but that was not the desired result.
So what I need is a working code that allows me to control the whole thing via bluetooth.
I don't know how to control a potentiometer into my noobish code.

#include <SoftwareSerial.h> // TX RX software library for bluetooth

#include <Servo.h> // servo library
Servo myservo; // servo name

int bluetoothTx = 10; // bluetooth tx to 10 pin
int bluetoothRx = 11; // bluetooth rx to 11 pin

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo.attach(9); // attach servo signal wire to pin 9
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available()> 0 ) // receive number from bluetooth
  {
    int servopos = bluetooth.read(); // save the received number to servopos
    Serial.println(servopos); // serial print servopos current number received from bluetooth
    myservo.write(servopos); // roate the servo the angle received from the android app
  }

}

I really would appreciate some help.

It is unclear to me, what the actual problem is. You didn't describe, what you expect the servo to do, and also not, what you are actually sending. Are you sending binary data or ASCII data? The external potentiometer has nothing to do with the code, since  the servo handles it. Have you connected the external potentiometer to the servos axis somehow? does the servo motor work correctly with the standard sweep example code?

Hi @chrisl. Oh well, I want that the servo turns up to 90 degree in both directions. I have tested another servo which is not connected the external potentiometer, On the Arduino board it makes the 180 degree turn, albeit becomes very warm. The servo, which is soldered to the external potentiometer doesn't make that much movement when connected to the Arduino. It worked a little in both directions, but that was not enough for the purpose. After I checked my soldering, I tried again. This servo now reacts on powering up but didn't move afterwards. I might have a servo defect?

you have not answered all of the questions ... how is the potentiometer connected to the servo mechanically?

Also looks like the servo is powered off the Arduino board.  That’s not a good idea.  It likely needs more current than is safe to provide there.  Motors and servos should not pull power off the arduino board unless you just want to fry boards.

@jsotola The instructions said to cut the connection inside the servo and connect them to the external potentiometer. link The thing looks like this link

@Delta_G Ok advice taken, I will change the setup :)


text:
Arduino Due Master Programming
I am newbie. In my application Arduino Due is configured as Master and Arduino Uno as Slave. I need to transfer 24-bit Hexadecimal data of about 79-registers to slave device. At the slave end in serial monitor window I would like to display the transmitted data. I have developed an array at slave side, and I am comparing the master data with slave one. I have divided the 24-bit data into 3 Bytes. I will attach the Master and Slave codes below. I am getting Invalid data in serial monitor window as the data (Hexa Decimal) transmitted by Master is converted into decimal format internally and I think this was the reason I am not able to print the Valid data in serial monitor window.
Any help will be greatly appreciated. Thanks in Advance.
MASTER Code
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

//pinMode(10, OUTPUT)
void setup() {
  pinMode(ss, OUTPUT);

  SPI.begin();
SPI.beginTransaction(mySettting);

 digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x1C);
  SPI.transfer(0x25);
  SPI.transfer(0x00);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x08);
  SPI.transfer(0x08);
  SPI.transfer(0x01);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x00);
  SPI.transfer(0x05);
  SPI.transfer(0x02);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x42);
  SPI.transfer(0x06);
  SPI.transfer(0x03);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x43);
  SPI.transfer(0x0A);
  SPI.transfer(0x04);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0xC8);
  SPI.transfer(0x00);
  SPI.transfer(0x05);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x02);
  SPI.transfer(0xC8);
  SPI.transfer(0x6C);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0xB2);
  SPI.transfer(0x40);
  SPI.transfer(0x07);
  SPI.transfer('$');
  SPI.transfer('&');
  delay(100);
  digitalWrite(ss, HIGH);
SPI.endTransaction();
}

void loop() {
}

SLAVE Code
#include <SPI.h>
#include <stdio.h>
#include <string.h>
int buff[100] = {0x001C2500,0x00080801,0x00000502,0x00420603,0x430A04,0xC80005,0x02C806,0xB24007};

uint32_t buff_1 [100];
volatile byte indx;
volatile boolean process;
int i = 0;
uint32_t var_byte = 0x00000000;
uint32_t var_byte_1 = 0x00000000;
int byte_pos = 0;
short int status_1 = 0;

void setup (void) {
   Serial.begin (115200);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt
   memset(buff_1,'\0',sizeof(buff_1));
}

ISR (SPI_STC_vect) // SPI interrupt routine
{
   byte c = SPDR; // read byte from SPI Data Register

   if(c == '@')
   {
      var_byte = 0x00000000;
      byte_pos = 2;
   }
   else if(c == '$')
      buff_1 [indx++] = var_byte;
   else if(c == '&')
      process = true;
   else
   {
      var_byte_1 = 0x00000000;
      var_byte_1 = (var_byte_1 | c) << byte_pos;
      var_byte |= var_byte_1;
      byte_pos--;
   }

}
void loop (void) {
   if (process) {
      process = false; //reset the process
      status_1 = 0;
      for(i=0;i<79;i++)
      {
        if (buff[i]==buff_1[i])
        {
          Serial.println ("Valid data_1");
        }
        else
        {
          status_1 = 1;
          break;
          //Serial.println ("Inavlid data");
        }
      }
      if (status_1 == 0)
        Serial.println ("Valid data");
      else
        Serial.println ("Inavlid data");
      indx= 0; //reset button to zero
      memset(buff_1,'\0',sizeof(buff_1));
   }
}

Try to print out the data, that you received. Then you might see, what the problem is, meaning how exactly the data is "invalid"

24-bit Hexadecimal data ... do you want to transmit 6 text characters, or 3 bytes?

I want to transmit 3 bytes of hexadecimal data, I mean 0x1A, 0x25, 0x00 in this way I would like to send the data.

Your process turn true for every receive of a "$", i.e. at end of receiving 3 bytes of data, but you are comparing it with 80-bytes of data, of course it won't match and will be "invalid". And BTW, where that 80 bytes come from? it looks that your data only consists of 32 bytes.


text:
I am tying to split a float variable into bytes and then re combine to the original float
Here is the code I am currently using, there have been many and various alternatives I have tried all so far without success, this being the latest incarnation sitting within my main program loop (void loop)...
// get temperature from Dallas Temperature Sensor
  sensors.requestTemperatures();
  sen0_data = sensors.getTempC(sensor_0_address);             // read temperature sensor0

// split float
  float f1 = sen0_data;
  byte* fb = (byte*) &f1;

  Serial.println(f1);
  Serial.println(fb[0]);    // Take a look at the bytes
  Serial.println(fb[1]);
  Serial.println(fb[2]);
  Serial.println(fb[3]);

// rebuild float
  temp = (fb[0] << 24) + (fb[1] << 16) + (fb[2] << 8) + (fb[3]);
  Serial.println(temp);

Now for the result as seen in the serial monitor - original float, split byte 0, byte 1, byte 2, byte 3, and finally rebuilt float. What am I doing wrong? as no doubt can be seen from the dirty coding I am a relative newbe
The starting float value -127.00 is because I currently have no temperature sensor connected to the Arduino, but I would still expect the rebuilt float to be the same and not -318.00. Even if I connect a sensor the rebuilt float does not mirror the original...
-127.00
0
0
254
194
-318.00

I look forward to any advice...
Regards,
Simon.

AVR is little-endian...

I have been told to be careful about a simple casting of non-byte variables to an array of bytes because there's no guarantee that the memory allocated for certain data types will be contiguous. I.e., the bytes might be spread out to non-adjacent spots in memory. For example, I was encouraged to use a union to convert a unit64_t, which is 8 bytes, to a byte array on an ESP8266. This involves declaring a union type:
union u64_bytes {
  uint64_t u64;
  uint8_t u8[sizeof(uint64_t)];
};

And then you can use this to convert either way, for example:
  uint64_t myNum = 1;
  u64_bytes splitNum;
  splitNum.u64 = myNum;
  // now i can loop thru the bytes
  for(int i=0; i<sizeof(uint64_t); i++) {
      uint8_t myByte = splitNum.u8[i];
      Serial.print("byte ");
      Serial.print(i);
      Serial.print(" is ");
      Serial.println(myByte);
  }
  // or just refer to individual bytes
  uint8_t oneByte = splitNum.u8[0];

  // you can also take bytes and convert the other way
  u64_bytes rebuilt;
  for(int i=0; i<sizeof(splitNum); i++) {
      rebuilt.u8[i] = splitNum.u8[i];
  }

  Serial.print("The rebuilt value is ");
  Serial.println(rebuilt.u64);

EDIT: I added some code to show conversion the other way.
That said, it's probably pretty safe in your case to use the bitwise operators you are using. A float is in all likelihood 4 bytes on your hardware, and most hardware allocates memory these days in four-byte blocks.
HOWEVER you still have to take into account the Endianness of the system when it stores values. The basic idea is that if you have four bytes that represent one number, are the most significant bytes first or are the least significant bytes first?
For example, if you are talking about a four byte unsigned integer the number 1, aka 0x00000001, it would be stored like this in Big-Endian hexadecimal:
0x00 0x00 0x00 0x01

But on little endian hardware (like mine) the order is different. They put the least significant bytes first in memory like so:
0x01 0x00 0x00 0x00

This might be very confusing, but the bottom line is you might have to think twice about what the byte order is for your data. I'd add that floats and signed integers might have some aspects that surprise you, and when you try and communicate any information over a serial line (SPI, I2C, etc.) or over a network then you might have to worry about what sort of conversions are happening. You must have to make sure that you know what order your bytes are and you unpack them in a way that's appropriate to the way you packed them.
Lastly, I would encourage you maybe think about (and possibly elaborate) what you are hoping to accomplish by taking apart a float into bytes? If you don't know about the structure of bits inside a float, you would need to get better acquainted with that before you start monkeying with the bytes inside it.
EDIT 2: here's an example where I use a struct to convert a float:
  union float_bytes {
    float flt;
    uint8_t u8[sizeof(float)];
  };

  float myNum = -127.0;
  float_bytes splitNum;
  splitNum.flt = myNum;
  // now i can loop thru the bytes
  for(int i=0; i<sizeof(splitNum); i++) {
      uint8_t myByte = splitNum.u8[i];
      Serial.print("byte ");
      Serial.print(i);
      Serial.print(" is ");
      Serial.println(myByte);
  }
  // or just refer to individual bytes
  uint8_t oneByte = splitNum.u8[0];

  // you can also take bytes and convert the other way
  float_bytes rebuilt;
  for(int i=0; i<sizeof(splitNum); i++) {
      rebuilt.u8[i] = splitNum.u8[i];
  }

  Serial.print("The rebuilt value is ");
  Serial.println(rebuilt.flt);


text:
Why is my "port" button on the toolbar greyed out?
I am trying to program a Teensy 3.2 to act as a lightsaber controller. My code works perfectly but I can't select a port. How should I fix this problem?
Here is my code:
/* Presented without warranty, guarantee and support.
    By Bob Clagett - I Like To Make Stuff

   This is the code to accompany the lightsaber project at http://www.iliketomakestuff.com/make-lightsaber/
   Expected hardware is listed in post (Teensy 3.2, Prop Shield, DotStar LEDs)

   This is functional v1 of this code.  Lots more I want to add to it including crash detection/sounds.
   This code is dirty, bulky, poorly documented and ugly but I finally got it all functional.
   Cleanup to come later in v2.
*/

#include <SerialFlash.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

// GUItool: begin automatically generated code

// GUItool: end automatically generated code

#include <Adafruit_DotStar.h>
#include <NXPMotionSense.h>

NXPMotionSense imu;
NXPSensorFusion filter;

int motionThreshold = 2;

float lastPitch = 0, lastRoll = 0, lastHeading = 0;

int buttonState = HIGH;
int bladeState = 0; //0 off, 1, fading up, 2 on, 3 fading down
int fadeStep = 0;
int fadeStepSize = 6;
int selectedColor = 0;
int lastSelectedColor = 0;
bool isAnimating = 0;
bool bladeOn = 0;
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;
int lastButtonState = HIGH;
int pendingPress = 0;

//BC = Blade Color
int BCbuttonState = HIGH;
long BClastDebounceTime = 0;  // the last time the output pin was toggled
long BCdebounceDelay = 50;
int BClastButtonState = HIGH;
int BCpendingPress = 0;
int pendingColorPress = 0;

#define COLOR_BUTTON_PIN 1
#define POWER_BUTTON_PIN 0
#define COLOR_ORDER BGR
#define CHIPSET     APA102
#define NUMPIXELS    252

#define BRIGHTNESS  100
#define FRAMES_PER_SECOND 70

#define PROP_AMP_ENABLE 5
#define FLASH_CHIP_SELECT 6
#define LED_BUFFER_SELECT 7

#define VOLUME_POT 15

#define LED_PIN    7
Adafruit_DotStar strip = Adafruit_DotStar(
                           NUMPIXELS, DOTSTAR_BRG);

int outputValue = 0;
int presetColors[] = {0x0000FF, 0x00FF00, 0xFF0000, 0xFFFFFF};
int totalPresetColors = (sizeof(presetColors) / sizeof(int));
int selectedColorIndex = 0;

int swingSounds = 4;
int lastSwingSound = swingSounds;

int clashSounds = 0;
void setup() {
  delay(500); // sanity delay
  imu.begin();
  filter.begin(100);
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif

  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP

  pinMode(POWER_BUTTON_PIN, INPUT);
  pinMode(COLOR_BUTTON_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(POWER_BUTTON_PIN, HIGH);
  digitalWrite(COLOR_BUTTON_PIN, HIGH);
  digitalWrite(LED_PIN, LOW);

  Serial.begin(9600);
  // wait up to 3 seconds for the Serial device to become available
  long unsigned debug_start = millis ();
  while (!Serial && ((millis () - debug_start) <= 3000))
    ;

  Serial.println ("Start prop shield RAW player");
  SPI.begin();
  // Enable the amplifier on the prop shield
  pinMode(PROP_AMP_ENABLE, OUTPUT);
  digitalWrite(PROP_AMP_ENABLE, HIGH);
  pinMode(LED_BUFFER_SELECT, OUTPUT);
  digitalWrite(LED_BUFFER_SELECT, HIGH);

  // Audio connections require memory to work.  For more
  // detailed information, see the MemoryAndCpuUsage example

  // Set initial volume

  // Start SerialFlash
  if (!SerialFlash.begin(FLASH_CHIP_SELECT)) {
    while (1)
    {
      Serial.println ("Cannot access SPI Flash chip");
      delay (3000);
    }
  }

}

void powerUpBlade() {

  isAnimating = 1;
  bladeState = 1;
  Serial.println("Turn on blade");
  bladeOn = 1;

}

void powerDownBlade() {
  //animate DOWN

  bladeState = 3;
  fadeStep = NUMPIXELS;
  isAnimating = 1;
  Serial.println("Turn off blade");

  bladeOn = 0;
}

void bladeIsOn() {

}
//nothing needed here unless adding animation

void bladeIsAnimatingUp() {
  //Serial.println("bladeIsAnimatingUp");
  int midpoint = NUMPIXELS / 2;
  int newSection = fadeStep + fadeStepSize;
  for ( int j = fadeStep; j < newSection; j++) {
    strip.setPixelColor(j, selectedColor);
    strip.setPixelColor(NUMPIXELS - j, selectedColor);
  }
  Serial.println(newSection);
  fadeStep = newSection;

  if (fadeStep >= midpoint + fadeStepSize) {

    fadeStep = NUMPIXELS;
    isAnimating = 0;
    bladeState = 2;
    //      delay(200);
    Serial.println("blade up complete");

  }
}

void bladeIsAnimatingDown() {
  //Serial.println("bladeIsAnimatingDown");
  int midpoint = NUMPIXELS / 2;
  int newSection = fadeStep - fadeStepSize;
  for ( int j = fadeStep; j > newSection; j--) {

    strip.setPixelColor(j - midpoint, 0x000000);

    strip.setPixelColor(midpoint + NUMPIXELS - j, 0x000000);
  }
  //Serial.println(fadeStep);
  fadeStep = newSection;

  if (fadeStep <= midpoint - fadeStepSize) {
    fadeStep = 0;
    isAnimating = 0;
    bladeState = 0;
  }
}

void detectMotion() {
  float ax, ay, az;
  float gx, gy, gz;
  float mx, my, mz;
  float roll, pitch, heading;

  if (imu.available()) {
    // Read the motion sensors
    imu.readMotionSensor(ax, ay, az, gx, gy, gz, mx, my, mz);

    // Update the SensorFusion filter
    filter.update(gx, gy, gz, ax, ay, az, mx, my, mz);

    // print the heading, pitch and roll
    roll = filter.getRoll();
    pitch = filter.getPitch();
    heading = filter.getYaw();

    // does it need a time threshold too?

    float headingDiff = abs(lastHeading - heading);
    float pitchDiff = abs(lastPitch - pitch);
    if (lastHeading != 0) {
      if (pitchDiff > motionThreshold || headingDiff > motionThreshold) {
        //cyle through swing sounds
        lastSwingSound++;
        if (lastSwingSound > swingSounds) {
          lastSwingSound = 1;
        }
        String swingFile = "saberswingX.raw";

        char charBuf[50];
        swingFile.toCharArray(charBuf, 50);
        triggerSwing(charBuf);  // needs sequence to iterate through
      }
    }
    lastHeading = heading;
    lastPitch = pitch;
  }

}
void loop() {
  // Add entropy to random number generator; we use a lot of it.
  // random16_add_entropy( random() );

  //handle color selector button
  int BCreading = digitalRead(COLOR_BUTTON_PIN);

  if (BCreading != BClastButtonState) {
    // reset the debouncing timer
    BClastDebounceTime = millis();
  }

  if ((millis() - BClastDebounceTime) > BCdebounceDelay) {
    if (BCreading != BCbuttonState) {
      BCbuttonState = BCreading;

      if (BCbuttonState == HIGH) {
        nextColor();
      }
    }
  }
  BClastButtonState = BCreading;

  selectedColor = presetColors[selectedColorIndex];
  if (selectedColor != lastSelectedColor && bladeState != 0) {
    Serial.print("COLOR CHANGE");
    Serial.println(selectedColorIndex);
    for ( int j = 0; j < NUMPIXELS; j++) {
      strip.setPixelColor(j, selectedColor);
    }
  }
  lastSelectedColor = selectedColor;

  //handle blade on/off

  int reading = digitalRead(POWER_BUTTON_PIN);
  //debounce
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
    }
  }
  lastButtonState = reading;

  if ( pendingPress == 1 && buttonState != LOW) {
    buttonState = HIGH;
    pendingPress = 0;
    Serial.print("execute pending blade press");

    if (bladeOn) {
      powerDownBlade();
    } else {
      powerUpBlade();
    }
  }

  if (buttonState == LOW && !isAnimating) {
    Serial.println("BLADE BUTTON IS PRESSED");
    pendingPress = 1;
  }
  switch (bladeState) {
    case 0:
      //blade is off
      break;
    case 1:
      //blade is animating up
      bladeIsAnimatingUp();
      break;
    case 2:
      //blade is on
      bladeIsOn();
      break;
    case 3:
      //blade is animating down
      bladeIsAnimatingDown();
      break;
  }
  SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
  digitalWrite(LED_PIN, HIGH);  // enable access to LEDs
  strip.show();                     // Refresh strip
  digitalWrite(LED_PIN, LOW);
  SPI.endTransaction();   // allow other libs to use SPI again

  delay(10);

  if (bladeState == 2) {
    detectMotion();
  }

}
void nextColor() {
  selectedColorIndex++;
  if (selectedColorIndex >= totalPresetColors) {
    selectedColorIndex = 0;
  }
}
void triggerSound(const char *filename) {

}
void triggerSwing(const char *filename) {

}

void startHum() {
  //Serial.println("startHum");

}

what port are you talking about? ... how is it related to your sketch?

please format your code to make it readable

So your problem is with the Arduino IDE or with the detection of the teensy board on your PC? Which of OS and which IDE version do you use?

From what I understand TeensyDuino modifies your Arduino IDE installation to make it work with the Teensy. Once that is done it is no longer the Arduino IDE. It doesn't use the standard board manager installation system, but direct modification of the IDE itself. I am not aware of a "port" button in the Arduino IDE (there is a port menu entry though, which only appears if you have a serial port available). The Teensy doesn't use serial for uploading code. You shouldn't need a port for that.

The error message says “you do not have a port selected”. I am talking about the port button in the too bar.

I mean the tool bar

There is no port button in the toolbar of the Arduino IDE. There is "Verify", "Upload", "New", "Open", "Save", and on the far end "Serial Monitor".

Did you fix the problem? I am Working with the same code, but something is stocking with
Colors. I am working with NeoPihel and WS2812.


text:
Using a limit switch to stop a stepper motor
I am building a machine with a moving bed, the bed moves forward and backward. I need to incorporate a limit switch at the two ends that makes sure the motors stop at the two extremes. I have 2 stepper motors controlled by TB6600 motor drivers, I am trying to start with 1 limit switch (SS-5Gl2) and advance from there.
My 1st question is how I get the code to stop steppers if limit switch is closed?
// Define stepper motor connections and steps per revolution:
#define dirPin1 2
#define stepPin1 3
#define dirPin2 5
#define stepPin2 6
#define stepsPerRevolution 200 // We may need to change 200 to 1600 to get more precise control, i.e. decimals verse integers

#define Lim1 8

int direction = 0;
int remainder = 0;
long travel = 0;
long revolutions = 0;

void setup() {

  // Declare pins as output:
  pinMode(stepPin1, OUTPUT);
  pinMode(dirPin1, OUTPUT);
  pinMode(stepPin2, OUTPUT);
  pinMode(dirPin2, OUTPUT);

  pinMode(Lim1, OUTPUT);

 //Desired travel distance, in mm !!!! set here !!!!
travel = 1;
//Desired direction !!!! set here !!!! move die in(ccw) = 1, back out(cw) = 0 !!!!
//direction = 0; did not work, need boolean?

// Set the spinning direction counterclockwise (die in) or clockwise (die out):
//if(direction = 1) digitalWrite(dirPin, HIGH);
//if(direction = 0) digitalWrite(dirPin, LOW);

//set direction manually, uncomment HIGH for die in, LOW for die back out
digitalWrite(dirPin1, LOW);
digitalWrite(dirPin2, LOW);
//digitalWrite(dirPin, LOW);

digitalWrite(Lim1, OFF) //

//calculating number of revolutions based on mm input. Does not yet account for partial revs - variable is truncated, integers are default. Would need another loop to handle the remainder
//6.659 (microns) constant is based on 1.25mm acutator screw pitch, and ratio in gearbox
revolutions = 1000.00*travel/6.659;
//attempt to output the stored value to PC for debug purposes

Serial.print("revolutions = ");
Serial.print(revolutions,4);
}

void loop() {

   // Spin the stepper motor X revolutions fast, speed (delay) apparently limited by voltage. 42v should go faster?
   //Required a nested loop because integers on the UNO are limited to ~32k
  for (int i = 0; i < revolutions; i++) {

   if (digitalRead(Lim1 == OFF)){}

   else {
      for (int j = 0; j < stepsPerRevolution; j++) {
       // These four lines result in 1 revolution:
      digitalWrite(stepPin1, HIGH);
      digitalWrite(stepPin2, HIGH);
      delayMicroseconds(250);
      digitalWrite(stepPin1, LOW);
      digitalWrite(stepPin2, LOW);
      delayMicroseconds(250);
      }
  }
  }

   while(1){}

}

// These four lines result in 1 revolution: ... that should say // These six lines result in 1 step:

You are doing every step manually directly via digitalWrite(), so the principal would be to read the limit switch pin on every iteration of the inner for loop in an if statement. What to do in that if statement depends on what you want to do on hitting the limit switch. Currently you have an infinite empty loop after your motor code. So if you want to stop forever in that case you can create another infinite loop there. So something like this:
...
for (int j = 0; j < stepsPerRevolution; j++) {
   if(!digitalRead(Lim1)){
       while(true);
   }
   // These four lines result in 1 revolution:
   digitalWrite(stepPin1, HIGH);
   digitalWrite(stepPin2, HIGH);
   delayMicroseconds(250);
   digitalWrite(stepPin1, LOW);
   digitalWrite(stepPin2, LOW);
   delayMicroseconds(250);
}

Note that this assumes that you have connected the limit switch to ground and use the digital pin with a pullup resistor.

But you have 2 other problems with your limit switch code:

You set your limit switch pin Lim1 as output, though to read a switch you need to configure it as input. And if you want to use a pullup resistor (in contrast to a pulldown resistor) you can activate the internal pullup in the same step:
 pinMode(Lim1, INPUT_PULLUP);

When reading the limit switch inside the outer for loop you write
 if (digitalRead(Lim1 == OFF)){}

You are doing the equality comparison between OFF and the pin number and not between OFF and the return value of digitalRead(). You need to place the parentheses here correctly:
 if(digitalRead(Lim1) == OFF){}

Above I used the equivalent form
 if(!digitalRead(Lim1)){}

with the negation operator !

Besides that you are missing the Serial.begin() with the baudrate, that you want to use, in setup().

Thank you for your answer, I am really new and completely confused.

// Define stepper motor connections and steps per revolution:
#define dirPin1 5
#define stepPin1 2
#define dirPin2 6
#define stepPin2 3
#define stepsPerRevolution 200 // We may need to change 200 to 1600 to
get more precise control, i.e. decimals verse integers'
#define limPin1 8
#define CW 0x1
#define CCW 0x0

int remainder = 0;
long travel = 0;
long revolutions = 0;
bool homed = false;

void setup() {

  // Declare pins as output:
  pinMode(stepPin1, OUTPUT);
  pinMode(dirPin1, OUTPUT);
  pinMode(stepPin2, OUTPUT);
  pinMode(dirPin2, OUTPUT);
  pinMode(limPin1, INPUT_PULLUP);

//Desired direction !!!! set here !!!! move die in(ccw) = 1, back
out(cw) = 0 !!!!
//direction = 0; did not work, need boolean?

// Set the spinning direction counterclockwise (die in) or clockwise
(die out):
//if(direction = 1) digitalWrite(dirPin, HIGH);
//if(direction = 0) digitalWrite(dirPin, LOW);

//set direction manually, uncomment HIGH for die in, LOW for die back
out
digitalWrite(dirPin1, LOW);
digitalWrite(dirPin2, LOW);

//attempt to output the stored value to PC for debug purposes
Serial.begin(9600);
Serial.println("test");
}

//main routine
void loop() {
Homing();
}

void Homing() {
     // Spin the stepper motor X revolutions fast, speed (delay)
     apparently limited by voltage. 42v should go faster?
     //Required a nested loop because integers on the UNO are limited to
     ~32k
     if (homed == false)
  {
    //calculating number of revolutions based on mm input. Does not yet
   account for partial revs - variable is truncated, integers are
default.
   Would need another loop to handle the remainder
        //6.659 (microns) constant is based on 1.25mm acutator screw
pitch,
    and ratio in gearbox
        float travel = 2.0;
        float revolutions = 1000.00*travel/6.659;
    int totalStepsOut = revolutions * stepsPerRevolution;
    Serial.print("revolutions = ");
    Serial.println(revolutions,4);
    digitalWrite(dirPin1, CCW);
    digitalWrite(dirPin2, CCW);
    for (int j = 0; j < totalStepsOut; j++) {
      bool limState = digitalRead(limPin1);
      if (limState == false)
      {
        //Limit is triggered
        HomingReturn();
        break;
    }
    else
    {
        //Limit is not triggered
        // These six lines result in 1 revolution:
      digitalWrite(stepPin1, HIGH);
      digitalWrite(stepPin2, HIGH);
      delayMicroseconds(250);
      digitalWrite(stepPin1, LOW);
      digitalWrite(stepPin2, LOW);
      delayMicroseconds(250);
      }
    }
   }
   //Add stuff here to do whatever you want after homing
   Serial.println("Homed");
}

void HomingReturn()
{
  //set direction for reverse
  digitalWrite(dirPin1, CW);
  digitalWrite(dirPin2, CW);
  Serial.println("Reversing");
  //Desired travel distance, in mm !!!! set here !!!!
  float travel = 0.1;
  float revolutions = 1000.00*travel/6.659;
  int totalStepsOut = revolutions * stepsPerRevolution;
  for (int j = 0; j < totalStepsOut; j++) {
    //drive back
    digitalWrite(stepPin1, HIGH);
    digitalWrite(stepPin2, HIGH);
    delayMicroseconds(250);
    digitalWrite(stepPin1, LOW);
    digitalWrite(stepPin2, LOW);
    delayMicroseconds(250);
      }
      homed = true;
     Serial.println("Done");
   }

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.