text:
RFID Door Lock Coding Errors
I am trying to recreate an RFID door lock that I saw on the Arduino project hub but have ran into several issues. I had to manipulate the code slightly to make sure it was including the correct libraries and I think that solved some issues but not all. If anyone could take a look at my code and help me out that'd be awesome, I am pretty new with coding and need all the help I can get.
Thank you!
Here are the error messages I receive when trying to upload the code to my arduino:
Arduino: 1.8.8 (Mac OS X), Board: "Arduino/Genuino Uno"
rfid_based_door_automatic_management_system:66:17: error: expected unqualified-id before numeric constant
 #define SDA_D1O 9
                 ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
 MFRC522(SDA_D1O, RESET_D1O);
         ^
rfid_based_door_automatic_management_system:66:17: error: expected ')' before numeric constant
 #define SDA_D1O 9
                 ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
 MFRC522(SDA_D1O, RESET_D1O);
         ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void setup()':
rfid_based_door_automatic_management_system:120:10: error: expected unqualified-id before '.' token
   MFRC522.initial();
          ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void loop()':
rfid_based_door_automatic_management_system:137:12: error: 'class MFRC522' has no member named 'isCard'
   if( rfid.isCard() )
            ^
rfid_based_door_automatic_management_system:141:16: error: 'class MFRC522' has no member named 'readCardSerial'
       if( rfid.readCardSerial() )
                ^
rfid_based_door_automatic_management_system:152:33: error: 'class MFRC522' has no member named 'serNum'
               Serial.print(rfid.serNum[i], HEX);
                                 ^
rfid_based_door_automatic_management_system:154:30: error: 'class MFRC522' has no member named 'serNum'
               lcd.print(rfid.serNum[i],HEX);
                              ^
rfid_based_door_automatic_management_system:165:42: error: 'class MFRC522' has no member named 'serNum'
               if( My_RFID_Tag[i] != rfid.serNum[i] )
                                          ^
rfid_based_door_automatic_management_system:274:8: error: 'class MFRC522' has no member named 'halt'
   rfid.halt();
        ^
Multiple libraries were found for "LiquidCrystal.h"
 Used: /Users/gavinmiles/Documents/Arduino/libraries/LiquidCrystal
 Not used: /Applications/Arduino.app/Contents/Java/libraries/LiquidCrystal
Multiple libraries were found for "Servo.h"
 Used: /Users/gavinmiles/Documents/Arduino/libraries/Servo
 Not used: /Applications/Arduino.app/Contents/Java/libraries/Servo
exit status 1
expected unqualified-id before numeric constant
/Users/gavinmiles/Downloads/untitled_file.ino

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
/*
 *  RFID Module RC522
 *  Simple Project:- Arduino will read RFID Tag and Display To the Serial Monitor!
 *
 *  RFID RC522 and Arduino Uno Pin Configuration
 *
 *  RFID RC522          Arduino Uno
 *  SS/SDA              D10
 *  SCK                 D13
 *  MOSI                D11
 *  MISO                D12
 *  IRQ                 Not Connected
 *  GND                 GND
 *  RST                 D9
 *  3.3V                3.3V
 *
 *  //Note: We connected LCD to the Analog Pins.
 *  Remember, Analog Pins can be act as a Digital Pins,
 *  But Digital Pins CAN NOT be act as a Analog Pins.
 *
 *  LCD(16x2) Connections
 *
 *  VSS pin to GND
 *  VCC pin to 5V
 *  //We are connecting "Contrast pin to GND for Maximum Brightness"
 *  //You can also connect it to 10K Pot if you wish to change the Brightness Of LCD.
 *  VEE pin to GND
 *  RS pin to Analog pin A0
 *  R/W pin to ground
 *  Enable pin to Analog pin A1
 *  D4 pin to Analog pin 5
 *  D5 pin to Analog pin 4
 *  D6 pin to Analog pin 3
 *  D7 pin to Analog pin 2
 *  LED+ pin to POWER
 *  LED- pin to GND
 *
 *  Servo is Connected to Digital Pin 5
 *
 *  RGB LED
 *  From RGB LED, We need Only Red and Green Color,
 *  So we are not connecting Blue pin of the RGB.
 *
 *  Red pin to Digital pin 6
 *  Green pin to Digital pin 7
 *
 *  Buzzer to Digital pin 8
 *
 *
 *  Note:- RFID uses SPI Protocol to transfer the information.
 *  I took the Melody(for the Buzzer) from,
 *  File -> Examples -> Digital -> ToneMelody
*/

//Include sections
#include <MFRC522.h>
#include <SPI.h>
#include <LiquidCrystal.h>
#include <Servo.h>
#include "pitches.h"

//Define Component to Arduino Pins
/* Define the DIO used for the SDA (SS) and RST (reset) pins. */
#define SDA_D1O 9
#define RESET_D1O 8

/* Create an instance of the RFID library */
MFRC522(SDA_D1O, RESET_D1O);
#define SS_PIN 10
#define RST_PIN 9

#define SERVO_PIN 5

#define Red_LED 6
#define Green_LED 7

#define Buzzer 8

//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);
Servo DoorLock;
MFRC522 rfid(SS_PIN, RST_PIN );

//Unique ID of RFID Tag, which you want to give access.
int My_RFID_Tag[5] = {0x58,0x76,0x17,0x10,0x29};

//variable to hold your Access_card
boolean My_Card = false;

// notes in the melody, taken from:
//File -> Examples -> Digital -> ToneMelody
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup()
{
  // put your setup code here, to run once:
  //set the pins as an input/output
  pinMode(Red_LED,OUTPUT);
  pinMode(Green_LED,OUTPUT);
  pinMode(Buzzer,OUTPUT);

  //Servo Connnected to pin Digital Pin 5
  DoorLock.attach(SERVO_PIN);
  //open the serial port at 9600 baudrate.
  Serial.begin(9600);
  //Initialise the LCD to 16x2 Character Format
  lcd.begin(16,2);
  //Initialise Servo and RFID
  SPI.begin();
  MFRC522.initial();
}

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

  //First Assume detected card(Or tag) is My_Card,
  //Then later we will check is it My_Card or not!
  My_Card = true;
  DoorLock.write(0); //Servo at 0 Position, Door is Closed.
  lcd.clear();
  lcd.print("Robodia Technology");
  lcd.setCursor(0,1);
  lcd.print("gy Solutions!");

  //Check if any RFID Tags Detected or not?
  if( rfid.isCard() )
  {
      //if RFID Tag is detected, check for the Unique ID,
      //and print it on the Serial Window
      if( rfid.readCardSerial() )
      {
          lcd.clear();
          lcd.print("UNIQUE ID is:- ");
          delay(500);
          lcd.setCursor(0,1); //Set LCD Cursor to Second Row, First Character

      //Unique id is 5 Digit Number.
          //Printing in HEX for better Understanding
          for( int i = 0; i < 5; i++ )
          {
              Serial.print(rfid.serNum[i], HEX);
              Serial.print(" ");
              lcd.print(rfid.serNum[i],HEX);
              lcd.print(" ");
          }
          delay(500);

      //Compare this RFID Tag Unique ID with your My_RFID_Tag's Unique ID
          for(int i = 0; i < 5; i++)
          {
              //if any one Unique ID Digit is not matching,
              //then make My_Card = false and come out from loop
              //No need to check all the digit!
              if( My_RFID_Tag[i] != rfid.serNum[i] )
              {
                My_Card = false;
                break;
              }
          }
          Serial.println();
          delay(1000);

          //If RFID Tag is My_Card then give access to enter into room
          //else dont open the door.
          if(My_Card)
          {
            Serial.println("\nWelcome To Your Room, Robodia!");
            lcd.clear();
            lcd.print("Welcome to Your");
            lcd.setCursor(0,1);
            lcd.print("Room, Robodia!");
            delay(2000);

            //Turn on the Green LED as an indication of permission is given
            //to access the room.
            digitalWrite(Green_LED,HIGH);

            //Buzzer Config, taken from:
            //File -> Examples -> Digital -> ToneMelody
            // iterate over the notes of the melody:
            int i = 0;
            while(i < 2)
            {
              for (int thisNote = 0; thisNote < 12; thisNote++)
              {
                // to calculate the note duration, take one second
                // divided by the note type.
                //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
                int noteDuration = 1000 / noteDurations[thisNote];
                tone(8, melody[thisNote], noteDuration);
                // to distinguish the notes, set a minimum time between them.
                // the note's duration + 30% seems to work well:
                int pauseBetweenNotes = noteDuration * 1.30;
                delay(pauseBetweenNotes);
                // stop the tone playing:
                noTone(8);
              }
              i =  i + 1;
              delay(500);
            }
            delay(1000);

            //Now, Open the Door with the help of Servo Motor
            DoorLock.write(180);
            delay(200);
            lcd.clear();
            lcd.print("Door is Open");
            lcd.setCursor(0,1);
            lcd.print("Now!");
            delay(2000);
            lcd.clear();

            //Give 10 Sec delay to enter into room
            //After that door will again closed!
            for(int i = 10; i > 0; i--)
            {
              lcd.print("Door will close");
              lcd.setCursor(0,1);
              lcd.print("in ");
              lcd.print(i);
              lcd.print(" Sec.HurryUp!");
              delay(1000);
              lcd.clear();
            }

            //Now,Door is closed and Green LED is Turned-Off.
            DoorLock.write(0);
            digitalWrite(Green_LED,LOW);
            delay(200);
            lcd.clear();
            lcd.print("Door is Close");
            lcd.setCursor(0,1);
            lcd.print("Now!");
            delay(2000);
          }

          // If RFID Tag is not My_Card then
          // Do not open the Door and
          //Turn-On Red LED and Buzzer as an indication of Warning:
          //Somebody else is trying to enter into your room.
          else
          {
            Serial.println("\nGet Out of Here !");
            lcd.clear();
            lcd.print("Card isNOT FOUND!");
            lcd.setCursor(0,1);
            lcd.print("Get Out of Here!");

            for(int i = 0; i < 7; i++)
            {
              digitalWrite(Buzzer, HIGH);
              digitalWrite(Red_LED,HIGH);
              delay(500);
              digitalWrite(Buzzer, LOW);
              digitalWrite(Red_LED,LOW);
              delay(500);
            }
            delay(1000);
          }
      }
   }
  //Put RFID Reader into Halt, untill it not detects any RFID Tag.
  rfid.halt();
}

How about adding a link to the original project and some more information of a) your modifications and b) your issues? "Here's my code, tell me what's wrong" isn't really nice - and it does not comply to the rules of this forum.

you say RFID Door Lock Coding Errors and solved some issues but not all..... are we supposed to guess what the errors and the issues are?

I will find the original post and post the link. Sorry for the lack of information, I'm new to the site. Sorry if the original post came off as rude mic those weren't my intentions. Just looking for help and thought I'd ask if anyone could take a look at it and see what I missed. Thank you

https://create.arduino.cc/projecthub/user8523373/rfid-based-automatic-door-system-7b2065?ref=platform&ref_id=424_popular__intermediate_&offset=30 here is the link to the original project. All I've done is change out the rfid library for the MFRC522 library.

I had seen many errors in your code. Some of them are as follows

MFRC522.initial(); replace it with rfid.initial();
Libraries such as liquidcrystal, servo are default libraries in arduino so if you had download them from external source and copied them in your library folder please remove them.
This logic won't help as if the first id didn't match it will break the loop and and comparison won't go further with other and your will always find false as a result in this case.
      for(int i = 0; i < 5; i++)
  {
      //if any one Unique ID Digit is not matching,
      //then make My_Card = false and come out from loop
      //No need to check all the digit!
      if( My_RFID_Tag[i] != rfid.serNum[i] ) // suggested change if( My_RFID_Tag[i] == rfid.serNum[i] )
      {
        My_Card = false;//My_Card = true
        break;
      }
  }

Library functions used in code are different from those available in library, open library file and search for those function used for same purpose.
Remove them
#define SDA_D1O 9
#define RESET_D1O 8
MFRC522(SDA_D1O, RESET_D1O);

you are already defining them and using them here in your code
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN );


text:
Multiple void loops with ESP8266
I want to run multiple sketches on one sketch. I use the method of multiple void loops. It works but esp8266 take a lot of time to execute commands.
void Setup()
 {
  setup1();
  setup2();
 }
void loop()
 {
  loop1();
  loop2();
 }

Is there any method to avoid that ?

You should re-factor your code so it only uses one setup and loop function.

have you considered using multitasking?

@SimSon The Arduino doesn't support multitasking. It's a very basic microcontroller. It has a setup() function and a loop() function and that's it.

the OP seems to use an ESP8266. As far as I know there are libraries for multitasking. At least for the ESP32 I know for sure. Even on an atmega there are ways to implement multitasking, in my understanding the principle of multitasking has not much to do with the actual hardware.

@SimSon ESP32 has two cores, ESP8266 only one, so they're not the same

Without seeing what loop1 and loop2 do, it's hard to guess, but if esp8266 take a lot of time to execute commands then it doesn't matter how you write your code (multiple loop functions or put them all in one loop function) it's going to take just as long - the issue is in the code you haven't shown

@JarmondaX yes I'm aware of that. But even though multitasking might be managed differently, it still doesn't strictly depend on the hardware. Consider: even on the ESP32 one can run more than two tasks. Multitasking is pseudo-parallelism by principle. I have never used it on an 8266, but there seems to be https://github.com/nrwiersma/ESP8266Scheduler

@SimSon - OK, never considered that in such a tiny device :p

If the setup() or loop() functions call delay() then of course that will delay getting to the next function and will slow down the whole process.
The only way to deal with that is to rewrite the code, combining what you're calling and fixing it so that it takes into account the other work it needs to do.
Same thing if you call any blocking functions, like reading from Serial until you get a newline.
If that's not the case... well, the ESP8266 is a small, not particularly fast processor. If there are no delays or blocking functions then your code is running as fast as your code might run and you'll just have to live with it.

As long as you're not using delay() or other blocking code, as John mentions in his answer, that approach will work fine. I have a fairly large project where I defined a class ArduinoObject. The ArduinoObject class has a setup method and a loop method, and the main sketch creates and manages an array of ArduinoObjects (and another stack of a subclass of ArduinoObject called a MenuObject that manages menus on the LCD screen the project uses.)
At times there are a dozen or more ArduinoObjects being called on each pass through the sketch's loop() function and it works just fine. The key thing is to write your sub-loops to be FAST. They should do a tiny amount of work on each pass, and then a little more on the next pass (if needed.) You never want one of your sub-loops to take enough time to make the other sub-loops "stutter".

source: Stack Exchange

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

sort: votes


text:
Is my Realtime Clock Locking Up My Arduino? If so, how would I solve it?
I am having a very strange issue with the realtime clock in Arduino that I cannot seem to solve.  Basically, I have a program that logs data from a terrarium kit and saves each session to an SD card as a file named after the time the program started.  0
The problem with the program is that the code hangs on the statement before the setup section: “DateTime now = RTC.now().”  The realtime clock appears to be functioning correctly with the example program which makes this issue even more strange.  I am unsure if this is purely a software or hardware issue.  From scouring the internet, I have found people with a similar problem to mine where the RTC will freeze up the i2c bus on the Arduino.  However, I am unsure whether this is the issue plaguing me.  If this is indeed the issue plaguing my program, unsure of how to work around it.  I found an online solution here, however my program freezes upon launch so this would not work for me.
So far, I have tried:
-Replacing the coin-cell battery in the realtime clock (I am using 3 volt batteries)
-Replacing the datalogger shield with a new one
-Replacing the Arduino with a new one
-Checking to make sure that the jumpers were correctly soldered to the datalogger shield (Adafruit support checked mine through images and said they looked good)
I am running this program on IDE Version 1.6.9 with a program with the newer Adafruit datalogger shield on the Arduino Mega.
Any help would be greatly appreciated
//The libraries we need for our terrarium kit
//Download and install them all at this link:  https://drive.google.com/drive/folders/10XAFdYmnyz0dg9I6YYj80vJlHebFIZhN
#include <OneWire.h> //Import OneWire library
#include <DallasTemperature.h> //Import DallasTemperature library
#include <Adafruit_Sensor.h> //Import Adafruit Sensor library
#include <DHT.h> //Import first part of the DHT library
#include <TimerOne.h> //Import TimerOne library
#include <SPI.h>
#include <SD.h>  //this refers to an old SD library needed specifically for
#include "RTClib.h"  //this is from the rtc example folder code

//SD Card & Realtime Clock: Initialization
File logfile;
RTC_DS1307 RTC;

//Humidity Sensor: Constants
//This #define defines the pin that the DHT is plugged into
#define DHT_PIN 2
//This #define defines the type of the DHT
#define DHT_TYPE DHT22
//This tells the code that a DHT is plugged into port DHT_PIN and the DHT is of type DHT_TYPE
DHT dht(DHT_PIN, DHT_TYPE);

//Moisture Sensor: Variables
int MS_sigPin = A5; //Set the signal pin as analog pin 5
int MS_digPin = 7; //Set the digital pin as 2
float MS_upper = 0; //Declare highest value variable

//Other variables
int measurementNumber = 1; //Number of measurements taken

//Filename:
  DateTime now = RTC.now(); //Initialize the RTC
//  String seconds = (String)(now.second());  //Stores the seconds from the RTC upon setup as a string
 const String minutes = (String)(now.minute()); //Stores the seconds from the RTC upon setup as a string
 const String hours = (String)(now.hour());  //Stores the seconds from the RTC upon setup as a string
 const String days = (String)(now.day());  //Stores the seconds from the RTC upon setup as a string
 const String months = (String)(now.month());  //Stores the seconds from the RTC upon setup as a string
 const String years = (String)(now.year());  //Stores the seconds from the RTC upon setup as a string
 const String filename = "D_" + minutes + hours + days + months + years; //Create the file name as a timestamp

void setup() {

  int chipSelect = 10; //chipSelect pin for the SD card

  // put your setup code here, to run once:
  Serial.begin(115200); //Set the baud rate at 56700
//If RTC is already updated, the below is commented out
  RTC.begin();
  RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));//this is to force rtc update
//  if (!RTC.isrunning()) {
//
//    Serial.println("RTC is NOT running! Starting it now.");
//    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
//
//  }// end rtc if

//{
//The below is copied from wired, contains a second try, hoping for sd success herein.
 pinMode(chipSelect, OUTPUT);
 digitalWrite(chipSelect, HIGH);
 SD.begin(chipSelect);
//  if (!SD.begin(10, 11, 12, 13)) {
//    Serial.println("Card failed, or not present");
//    delay(50);
//    Serial.println("Trying again...");
//    if (!SD.begin(50, 51, 52, 53)) {
//      Serial.println("Card failed, or not present");
//    }
//  }

 /******************************** CSV FORMAT ******************************/

//  Serial.print("Current Position: ");
//  Serial.println(logfile.position());
  if(logfile.position() == 0)//Below print header line for datafile
  logfile.println("Unix Time, Date, Time, Light, Humidity, Temperature");
  //logfile.println("uni,date,time,Temperature");

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

//  sensors.begin();
//  sensors.setResolution(12);

  //Humidity Sensor:
   dht.begin();

  //Moisture Sensor:
  pinMode(MS_sigPin, OUTPUT); //Set the signal pin as an output
  pinMode(MS_digPin, OUTPUT); //Set the digital pin as an output
  digitalWrite(MS_digPin, HIGH); //Turn the digital pin on

  Serial.println("DIP THE MOISTURE SENSOR IN A CUP OF WATER MAKING SURE NOT TO SUBMERGE THE TOP OF IT INTO THE WATER, ENTER IN ANY KEY WHEN YOU ARE READY TO CALIBRATE"); //Print out useful information
  while (Serial.available() == 0) //Hang the program until the user inputs a key to continue
  {

  }
  Serial.println("Starting Calibration"); //Print out useful information
  Timer1.initialize(1000000); //Initialize an interrupt every 1 second
  Timer1.attachInterrupt(Calibrate); //When the interrupt is called run the “Calibrate” function

}
//Calibrate the moisture sensor
void Calibrate() //Function to calibrate the sensor
{
if (analogRead(MS_sigPin) > MS_upper) //If the value read by the sensor is higher than the past highest value
{
 MS_upper = analogRead(MS_sigPin); //Set the current value as the new highest value
  }
}

void loop() {

//Photocell: Variables
int photocellPin = A0; // the cell and 10K pulldown are connected to a0

  char fileCharStorage[(filename.length()+5)]; //+4 Characters to include ".csv"
  filename.toCharArray(fileCharStorage, filename.length()+5);
  fileCharStorage[filename.length()] = 'V'; //Set the file name
  fileCharStorage[filename.length()-1] = 'S'; //Set the file name
  fileCharStorage[filename.length()-2] = 'C'; //Set the file name
  fileCharStorage[filename.length()-3] = '.'; //Set the file name
  Serial.println(filename); //Print out the filename
  Serial.println(sizeof(fileCharStorage)); //Print the length of the array storing the file name
  logfile = SD.open(fileCharStorage, FILE_WRITE);  //Creates (or opens) a file names "MMHHDDMMYYYY.CSV"

  if (logfile)
  {
    Serial.println("The SD Card is functioning properly");
  }
  else
  {
    Serial.println("A Critical Error occured while trying to initialize the SD Card!");
  }
  //Realtime Clock
  DateTime now = RTC.now();

 //Photocell:
 int photocellReading = analogRead(photocellPin); //Variable that stores the amount of light detected by the photocell as an integer

  // This code gets the humidity from the DHT
  float dhtHumidity = dht.readHumidity();
  /*
  This code gets the temperature from the DHT
  */
  float dhtTemperature = dht.readTemperature();

  Serial.println(""); //Text Formatting
  Serial.println("Starting New Measurement (" + (String)measurementNumber + ")");
  Serial.println(""); //Text Formatting
  delay(1000);

  //Print out data from the number of measurements taken
  Serial.println("The Arduino has been active for " + (String)((measurementNumber*10)-10) + " seconds");
  measurementNumber++;

  //Print out data from the RTC
    Serial.print("Unix Time (Seconds since 1/1/1970): ");
    Serial.print(now.unixtime()); // seconds since 1/1/1970
    Serial.println(", ");
    Serial.print("RTC time: ");
    Serial.print(now.month(), DEC);
    Serial.print("/");
    Serial.print(now.day(), DEC);
    Serial.print("/");
    Serial.print(now.year(), DEC);
    Serial.print(",");
    Serial.print(now.hour(), DEC);
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.println("");
    Serial.println("");

  //Photocell:
  Serial.println("Data from the photocell:");
  Serial.print("Analog reading = ");
  Serial.print(photocellReading); // the raw analog reading

  if (photocellReading < 10) {
  Serial.println(" - Dark"); //says that if any number is lower than 10 then it prints out dark.
  } else if (photocellReading < 200) {
  Serial.println(" - Dim"); //says that if any number is lower than 200 then it prints out dim.
  } else if (photocellReading < 500) {
  Serial.println(" - Light"); //says that if any number is lower than 500 then it prints out light.
  } else if (photocellReading < 800) {
  Serial.println(" - Bright"); //says that if any number is lower than 800 then it prints out bright
  } else {
  Serial.println(" - Very bright"); //says that if any number higher than 800 then it prints out very bright
}
  Serial.println("");

// Humidity Sensor:
  Serial.println("Data from the humidity sensor:");
  Serial.print("Humidity: ");
  Serial.print(dhtHumidity);
  Serial.print(" %, Temp: ");
  Serial.print(dhtTemperature);
  Serial.println(" Celsius");
  Serial.println("");

  //Moisture Sensor:
  Serial.println("Data from the moisture sensor:");
  float percent = (analogRead(MS_sigPin)/MS_upper)*100; //Calculate moisture percentage
  Serial.println("Moisture = " + (String)percent + "%"); //Print out the moisture percentage

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

    //Log everything onto the SD card
    logfile.print(now.unixtime()); // seconds since 1/1/1970
    logfile.print(", ");
    logfile.print(now.month(), DEC);
    logfile.print("/");
    logfile.print(now.day(), DEC);
    logfile.print("/");
    logfile.print(now.year(), DEC);
    logfile.print(",");
    logfile.print(now.hour(), DEC);
    logfile.print(":");
    logfile.print(now.minute(), DEC);
    logfile.print(":");
    logfile.print(now.second(), DEC);
    logfile.print(", ");
    logfile.print(photocellReading);
    logfile.print(", ");
    logfile.print(dhtHumidity);
    logfile.print(", ");
    logfile.print(dhtTemperature);
    logfile.println();
    logfile.close();
//  Delay by 1+9 (10) seconds between measurements
  delay(9000);
}

I'm guessing that you can't call RTC.now() before setup like that.
It would be helpful if you told us what RTC you were using, and provided a link to the library you were using for it.
At a guess, since I don't have that info, you should probably change the declaration like this:
  //Filename:
  DateTime now;

And then in your setup():
RTC.begin();

if (!RTC.isrunning()) {
  Serial.println("RTC is NOT running! Starting it now.");
  RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
} // end rtc if
now = RTC.now(); //Initialize the RTC

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


text:
Why is my LCD I/F PIN ADAPTER won't work
I bought this on the store near us. Here is the PDF for it.
https://www.e-gizmo.net/oc/kits%20documents/new%20LCD%20with%20converter/LCD%20IF%20pin%20adapter.pdf
I followed the instructions below and uploaded the code and all I've got is this

I've reconnected it and used a different jumper wires, still the same result.
#include <LiquidCrystal.h>

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

void setup(){
  lcd.begin(16,2);
  lcd.print("ntest");
}

void loop(){

  lcd.setCursor(0,1);
  lcd.print(millis()/1000);

}

How did you wire the LCD to your Arduino? Which model of Arduino are you using?

Exactly as like with the pdf. I'm using arduino uno, I never had issues with my microcontroller and the code seems to compile and get uploaded to the board seemingly. I've tried to change the pins on the code and on the actual it still does not work.

The PDF shows 2 different ways of connecting the display to the Arduino. Which method are you using?

I tried both and it's the same output.

I guess no one knows.


text:
Running Pro Mini Continuous on 12v w/o Damaging Regulator
A Pro Mini needs to be placed in a 100mmx50mmx25mm, no holes but not air tight ABS plastic enclosure, with a 12v power supply connected to the raw input. It will be consuming max 40mA, ambient temperature 30-32C, and needs to be run 24/7. Upon prototyping in open air, I tried to touch the regulator MIC5205, after 30 seconds upon powering on with my bare fingers and it was too hot to touch. The rest of the components were cool to touch. I would use a buck converter to step down to 5v, however there isn't space for it in the current setup.
I used to run a Mega 24/7 on 12v, consuming much more current about 700mA, the onboard regulator malfunctioned after 1 year of use, which I believe was due to the excessive heat, as the PCB around the regulator turned a little brownish.
Despite being hot to touch, I understand that electronics run in heat all the time like computers, routers, etc for 24/7. Therefore, I would like to know if 12vx0.04A=0.48w will be too much heat/feasible to run in the above mentioned setup, without damaging the regulator in the long run?

Why is it running hot? 40mA shouldn't even warm up a 150mA regulator? Somethings wrong... Can you post the circuit (after checking it for shorts!)?

@MarkWilliams - heat depends on power, which is voltage as well as current.  With a very high voltage drop, even a small current can result in a hot regulator.

There almost certainly exist buck converters which will fit, but you can also see if you can sleep the processor a larger percentage of the time or reduce its clock speed, and so reduce the average current draw to a lower level.

Datasheet says 220 deg/Watt. 0.04A * 7v (drop) = 0.28 = 61 degrees. Not that hot, but yeah, uncomfortable.  It has a thermal shutdown, so you could get brownouts if it gets hot - but much hotter than this.

@MarkWilliams That's Junction to Ambient, so you need to add another 20C for ambient temperature (actually more, it's in a box) - so really 80C range and a burned finger.

Summary:
Simple, effective, low cost solution - choose any 3:
A series resistor in the regulator input, of properly designed resistance and wattage will greatly reduce regulator temperature and increase overall reliability. Reason and design details given below.
Detail:
Assuming a 5V processor dissiaption in the regulator is
(Vsupply - Vregulator_out) x Current
= (12-5)x 0.040 = 280 mW - usefully less than the 480 mW if you are dissipating all the power in the regulator.
For a 3V3 processor dissipation is (12-3.3)* 0.040 ~= 350 mW
"Too hot to touch" is a minimum of 55C and probably hotter - say 70C for now.
At 30C ambient delta T = (70-30) = 40 C.
Thermal resistanc = dT/Watts =40/0.280 = 140 C/W or 114 C/W at 3V3.
Both of those thermal resistances are very high. You do not describe what heatsinking is on the regulator but that suggests PCB copper only and not much of it. Even adding a very rudimentary heat sink should help immensely. If there is no obvious way to add a formal heat sink then adding a 'flag' of copper or brass by soldering should be doable.
Using Mark William's 220C/Watt figure (see datasheet for conditions).
Say 300 mW (see above).
Delta t = 220 C/W  x 0.3 W = 66 C rise.
Ambient is 30-32 so allow 35 for very minor safety factor.
66 C rise + 35 C ~= 101C - water boils.
And temperature inbox will rise mildly from energy dissipated so hotter again.
BUIT a series resistor inside the box or external  will make an immense difference.
An easy and effective solution:
The regulator needs some "headroom" - some voltage above the Vout value to allow some dropacross the internal switch. Check the data sheet, but a modern LDO probably allows as little as 1V headroom. So, for 5V out you need 6V in. The extra 6v from 12V to 6V is not "needed" by the regulator. So, it can be dissipated in a low cost high reliability resistor.
Determine

Vsupply_minimum - the absolute lowest value supply will assume.
Vreg_in_minimum  I'll use 6V to start.
I_load_maximum - you said 40 ma. This must be abs_max or if of very short duration must be able to be supported by capacitors.

Then
Rmax = V/I = (V_supply_min-Vregin_nax) / Imax
= (12 - 6 )/.040 = 150 Ohm.
This is the absolute maximum resistor that meets the specification. A slightly smaller value will be safer. Say 120 R in this case.
Then
Pmax in R = I^2R = .04^2 x 120 = 192 mW.
A 500 mW resistor would be "safe enough" and a 1 watt one very safe.
Pregulator max = (6-5) x 0.040 = 40 mW, 14% of the 280 mW initially.
A  W resistor with adequate cooling will be very safe. Safest is probably a purpose built air cooled wire wound.
Note that the dissipated energy will raise internal ambient. A resistor is still an effective solution.
Place a suitable decoupling capacitor at the regulator input. Even if not normally used here it is needed due to the series input resistor raising the supply resistance.
._______________________________________
Temperature rise inside box due to heat dissipation.
Summary: Using pessimistic assumptions for box thickness, available area and power dissipation an internal temperature rise of under 15 degrees C can be expected. As the regulator is now dissipating under 15% of the original dissipation due to the series resistor it will have a far longer operating lifetime.
Notes:
Temperature rise (assuming no air transfer occurs) is limited by heat transfer through the plastic. This is controlled by the thermal conductivity of th e plastic, its thickness and its area.  Obviously:
 - Thicker plastic leads to higher temperature rise.

More surface area leads to lower temperature rise.
Higher thermal conductivity of the plastic leads to lower temperature rise

So given Thermal conductivity = Ktc

Delta T = Watts x thickness / (Ktc x area)

So Ktc = Watts x thickness /(Delta_Tx area)
So units of Ktc must be Watts/metre/degree_C
Which is indeed how Ktc is usually expressed.
This table of Thermal properties of plastic materials lists Ktc for ABS as 0.17 W/m/K
This means that 170 mW will cause a 1 degree K (or C) rise when plastic ratio of thickness to area is 1.
Assume thickness of box = 5mm = much higher than is likely.
Box area for a box L x W x D = 2 x (LW + WD + DL)
Here  = L D W = 100mm x  50mm  25 mm or 0.1 x 0.05 x 0.025m
Area = 0.0175 m^2.
Use a smaller more pessimistic area of 0.01 m^2
Use a pessimistic heat dissipation of 0.5 Watts
Using the formula - Delta T = Watts x thickness / (Ktc x area)  from above
Temperature rise = 0.5 x 0.05 / (0.17 x 0.01) ~= 15 degrees C (or K)
This is based on a thicker than likely box, smaller than actual area, and higher than expected energy dissipation. A 15C rise is bearable and actual is lower, and as the regulator now dissipates under 20% of original it will survive very well.

The series resistor is a great idea. But you need to know that a series resistor with a linear regulator will not reduce total heat generated: it will only take some of the heat away from the regulator and heat up the resistor.  This is a benefit because it increases the surface are you are radiating from. BUT if it's all going inside the box it's not that much of a difference. If you can inline this resistor into the cable leading into the box this might give you the best cooling solution

@portforwardpodcast Your points are covered in my existing answer. If you allow 1V regulator headroom, a 5V regulator with 6V into regulator and 12V supply will reduce dissipation in the regulator by a factor of 7 times. ie it dropped 7V in the regulator before and now drops 1V at full current. A 1 watt resistor operating at 240 mW inside the box with some internal temperature rise will be reliable and a 2 Watt resistor could be used with still very compact sizing. Removing 80%+ of the heat energy from the regulator will make a vast difference. | ...

... The statement "... if it's all going inside the box it's not that much of a difference ..." is essentially not correct. You can calculate delta temperature from the total dissipation for a typical box and its not vast - the local temperature rise of the regulator is what kills things. I'll add a calculation for box temperature rise to show that it's minimal. But, as I noted in the answer* - the resistor can be external if desired. | [ *"BUT a series resistor inside the box or external will make an immense difference."]

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


text:
Trying to read different gas levels with MQ2 Gas Sensor
I found a link on how to connect MQ-2 Gas Sensor to Arduino Uno.
http://electronicsprojectshub.com/how-to-connect-mq2-gas-sensor-to-arduino/
After I bought all the parts and tried it out, the sensor gave me this in the serial monitor

Ro: 10.81 kohm
LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm
LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm

and so on.
Here is the code I used
#include <MQ2.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16,2);
int Analog_Input = A0;
int lpg, co, smoke;
MQ2 mq2(Analog_Input);

void setup(){
  pinMode(A0, INPUT);
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  mq2.begin();
}

void loop(){
  float* values= mq2.read(true);
  //lpg = values[0];
  lpg = mq2.readLPG();
  //co = values[1];
  co = mq2.readCO();
  //smoke = values[2];
  smoke = mq2.readSmoke();

  lcd.setCursor(0,0);
  lcd.print("LPG:");
  lcd.print(lpg);
  lcd.print(" CO:");
  lcd.print(co);
  lcd.setCursor(0,1);
  lcd.print("SMOKE:");
  lcd.print(smoke);
  lcd.print(" PPM");
  delay(1000);
}

Please help me fix it so that it can perform just the same as the video. Thanks.

I want it to show this
LPG: 4  CO:2803
SMOKE: 16 PPM
on the LCD. Please help. Thanks.

blow the right amount of gas and smoke onto the sensor so that you get those readings

First this should be like this:
float* values= mq2.read(false); //false

and then write this to be printed in the serial monitor
Serial.print('\n');
  Serial.print("LPG:");
  Serial.print(lpg);
  Serial.print(" CO:");
  Serial.print(co);

  Serial.print('\n');
  Serial.print("SMOKE:");
  Serial.print(smoke);
  Serial.print(" PPM");
  Serial.print('\n');


text:
Is the johnny-five library and javascipt good for Arduino projects?
I am new to Arduino. I just have my Arduino UNO kit and started to do some small projects with node.js and the Johnny-five library.
My question is why there not many content about javascript+Arduino in web, and the last news on Johnny-five website dated last year.

Is js development still relevant for Arduino?

johnny-five makes the arduino nothing more than a peripheral for a computer ... the arduino contains a very basic code that allows the computer to send commands to the arduino .... most people want to use the arduino as a standalone system

Because Johnny-five covers about 1% of the possible use cases for an Arduino and hardly anyone uses it because of that?

js is great to use for web interfaces with the ESP chips, but it's not very good to actually program the low-power, low-ram device itself. As MCUs get more powerful, and further blur the lines between them and SBCs you will see JS as a more viable option. I would say the big obstacle now is attitude; embedded programmers don't take JS seriously. Heck, they don't even take arduino very seriously. Looking at the site, it seems that j5 only runs on expensive corporate boards that nobody wants, and ardnuio ones that are too weak and don't have wifi, and nobody wants a usb tether.


text:
Radino40 Breakout Board
I would like to control the Radino40 breakout board with arduino. But i don't know if is it possible. I know that the single Radino40 DW1000 antenna could controlled by Arduino through SPI, but my board haven't this connection.

I think that the idea is you program the Radino40 directly with your own code. No reason you couldn't write code that accepts some data over serial from an Arduino.

I think so. The schematics of this board aren't clear and the documentation is bad. There are, available, more then 32 pin but i don't know how to connect.

It shows RX and TX pins, which implies that it has a UART, and it also has a micro USB connector. I don't see any indication of an SPI connection from the (scant) documentation.

it is a nRF52840 programmable over SWD. you can code for it with mbed or as Arduino with Arduino mbed package if you create a board definitions based on Arduino Nano 33 BLE board variant (it is nRF52840 too) and burn the Arduino bootloader


text:
Why is IF statement executing on itself
x = 5;
Serial.println (x);

if (x == 0);
    {
      //stuff in this IF keeps happening why ?
      //Iam too stupid ?
    }

the if statement must be executed to evaluate the condition. if the condition is true the following command or block of commands is executed. your command after the if is ; (empty command)

You have a rogue semi-colon.
Splitting your code up on the end of statements you get:
1. x = 5;
2. Serial.println (x);
3. if (x == 0);
4. { // stuff }

With the semi-colon after the if it terminates the if before the opening block {, and that block becomes a completely separate statement detached from the if.

Yeah, most of us have been bitten by this one. I wish C/C++ compilers would flag this if (condition); form with a warning as it is very likely a mistake, and is certainly bad coding practice even if intentional. (Same for if (a=b). Valid, but bad practice.)

@DuncanC They can. GCC has the flag -Wempty-body: "Warn if an empty body occurs in an "if", "else" or "do while" statement.  This warning is also enabled by -Wextra."

It should be on by default.

Hell, I'd even argue it should be flagged as an error. Anybody who deliberately writes a "side-effect only" if statement should be shot. :)

You can turn it on in preferences in the Aduino IDE.  /home/matt/Arduino/sketch_mar30a/sketch_mar30a.ino:5:14: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]


text:
Will the Duemilanove bootloader work in the Uno?
Similar to Will the Uno bootloader work in the Duemilanove? but the other way around.
I have an Arduino Uno. I require a slower upload speed than the 115200 baud rate used in the Uno's Optiboot bootloader.
The Arduino Duemilanove uses the ATmegaBOOT_168_atmega328 bootloader which has an upload baud rate of 57600. The Arduino Duemilanove also uses the ATMega328P like used on the Arduino Uno.
Will the Duemilanove bootloader work in the Uno?

you could use Optiboot compiled for a different baud rate

@Juraj Quite true. Why not turn that into an answer. Personally, the ATmegaBOOT_168_atmega328 bootloader appeals to my lazyness.

Yes it will.
Both the Arduino Duemilanove and Arduino Uno use the ATMega328P microcontroller. (There is also a version of Arduino Duemilanove ATMega168 that uses the Diecimila bootloader and that is not compatible, so just watch out).
The main difference between the Arduino Duemilanove and the Arduino Uno is that the Duemilanove uses FTDI FT232R IC, whereas the Uno uses the Atmega8u2 microcontroller fto handle the USB to serial UART interface.
Also important is that both boards both have the same 16MHz clock rate.
The schematic for the Arduino Duemilanove can be found here.
The schematic for the Arduino Uno can be found here.
Of course, instead of selecting Arduino Uno as the board type, you need to always select Arduino Duemilanove or Diecimila and the ATmega328 processor.

The question asks about Y problem. Here is the solution for the problem X in this X->Y situation.

I require a slower upload speed than the 115200 baud rate used in the Uno's Optiboot bootloader.

The Optiboot bootloader can work on different UART baud rates. The baud rate is configurable as parameter of the make command at build.
If don't want to setup the toolchain for compilation of the bootloader, MCUdude has on GitHub ready Optiboot hex files compiled with many options.
I recommend to use a custom boards definition for boards with not standard settings to burn the bootloader and to upload to the board. Here I have my https://github.com/jandrassy/my_boards as example.

Thanks for the answer. MCUdude looks like a good resource.


text:
Controlling a DC motor with an external power source
I'm trying to use an Arduino to release a single drop of water using a solenoid valve.  This article describes how to create this circuit with a Raspberry Pi using a DC powered solenoid that opens and closes very quickly and they use this for photographing water drops.  Exactly what I need, if I could only get it to work with the starter kit items first.
The design for the solenoid circuit from that site looks like:

I don't have a solenoid yet, but I've been experimenting with the cheap motor that comes with the Arduino and a 9 V battery.  I've burned out several transistors in my attempts to get this working.  My schematic looks like:

Relays won't work.  They are too slow.  Also, I need to use an external battery.  I can't use the power from the Arduino because I will eventually be moving up to a 12 V battery and the Arduino won't be able to handle that.

A motor is a quite different load than a solenoid. Before it starts rotating it takes a lot of current. A solenoid has no inrush current when you apply power.

Are you sure about the inrush current? Seems to me there would be.

Seeing as you want to use a 12V battery, you should try an external motor controller. You would essentially connect the Arduino to the controller, then the external battery and motor to the controller. Dimension Engineering makes several high quality motor controllers that are compatible with Arduino and can handle the voltage (like this controller). The site also includes Arduino libraries, documentation, and all the specifications on every product. I have used several of their products with my Arduino Uno and have had no problems.

I can think of a couple of things that you might consider.
The motor looks like a good surrogate for the solenoid.
If you're burning out transistors, look at the following 3 most probable causes:
a) Voltage spike when you cut the current to the coil (motor or solenoid). If the fly-back diode is still intact, this should not be your case.
b) Current spike exceeding Icmax. This is the maximum current your BJT can sustain without damage. An inductor like your solenoid or motor will reach in DC a maximum value dictated by Ohm's law. So measure the motor's resistance with a multimeter and calculate the Imax.
It should be Imax = (VDC - Vcesat)/Rcoil, where Vcesat is the saturation voltage of your BJT, somewhere around 0.3V.
Measuring the current of the motor connected to the battery also works if you measure it while you block the rotor.
Check that your transistor can handle the current.
Small signal transistors usually are rated at around 150mA, so this might be too little for your coil. So maybe you would need to buy/build a Darlington transistor that will have the amplification factor and current capacity to handle the load.
c) If a and b are OK, then maybe the transistor is overheating? Your fingers will tell you :-)
Once this works with the motor, you might need to recalculate to accommodate the (eventual) higher current of the solenoid.

You will also need a ceramic capacitor connecting the wires of the motor. also the diode should be at least 1amp and the transistor have the specs to take the loadd.

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


text:
Can I run ESP8266 via Arduino using the PWM pins?
First question: Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3 V ESP8266?
Second question: Can we also use these PWM pins as software serial pins i.e. they will be sending instructions at 3.3 V?

First question, Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3v ESP8266?

No. The ESP8266 draws far too much current (in excess of 200mA) to use anything other than a proper supply.

Second question, Can we also use these PWM pins as Software serial pins i.e. they will be sending instructions at 3.3v?

We'll drop the "also", since we've decided that you're not doing that.
You can use SoftwareSerial on any GPIO pins you like, provided the RX pin supports pin change interrupts.

and... the answer to the "sending instructions at 3.3V" will also be... No! setting the output voltage to 3.3V in a PWM output means to tell the board to send a series of 5V pulses so that, IN AVERAGE, the voltage is 3.3V. see PWM on wikipedia for more info


text:
Arduino - use print(.., DEC) to save into variable
I am using:
Serial.print(rawCodes[i - 1], DEC);

to print into serial monitor, but how can I save (rawCodes[i - 1], DEC) to save into variable?

The string value or the integer value of rawCodes[i-1]? How is rawCodes declared?

@MaximilianGerhardt rawCodes is unsigned int

rawCodes is already a variable. What do you actually want to achieve?

@Majenko I want get rawCodes[i - 1] to int variable

NO!!! That is what you think you want to do. Not what the end result is that you desire.

Assuming your code comes from here: https://www.alanzucconi.com/2015/08/19/how-to-hack-any-ir-remote-controller/
Since rawCodes is declared as
unsigned int rawCodes[35];

I.e., it is a 35-element array of unsigned int elements, we can access a single unsigned int element at some index and save it in a variable like
unsigned int myVariable = rawCodes[i - 1]; //assuming i is some integer variable
                                           //and exists in this scope

If conversion to a String object is needed it can be passed into the constructor of the String class as
String myString = String(myVariable);

That answers your syntactical question on how to save that element into a variable; however, it is unlikely that this is your real underlying problem. We cannot determine that until you tell us what exactly you actually want.
References:

Arrays in C tutorial


text:
compile error when using two typename in template class
I am using Arduino 1.8.5 ide. I am just creating a class with two typename which name is "Map". This class takes all int and String variations. Like;
class Map<int, int>;
class Map<int, String>;
class Map<String, int>;
class Map<String, String>;

Map<int, String> *list = new Map<int, String>();

If I create instance of this class like above in Main.ino file then everything is ok. But if I create it another file with .h extension which is "Test.h" then compilation fails. These are files;
    Main.ino
#include "Map.h"
#include "Test.h"

Test *test = new Test();
Map<int, String> *list = new Map<int, String>();

void setup() {

}

void loop() {

}

Map.cpp
#include "Arduino.h"
#include "Map.h"

template<typename E, typename T> Map<E, T>::Map()
{

}

template class Map<int, int>;
template class Map<int, String>;
template class Map<String, int>;
template class Map<String, String>;

Map.h
#ifndef Map_h
#define Map_h

#include "Arduino.h"

template<typename E, typename T> class Map {

public:
    Map();
    ~Map();
};

#endif

Test.h
#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

#endif

Error is;
In file included from C:\Users\zafer\Desktop\Main\Main.ino:3:0:
Test.h:14: error: expected ';' at end of member declaration
  Map<int, String> *list = new Map<int, String>();

                                        ^

Test.h:14: error: expected unqualified-id before '>' token
  Map<int, String> *list = new Map<int, String>();

                                              ^

Test.h:14: error: wrong number of template arguments (1, should be 2)
  Map<int, String> *list = new Map<int, String>();

                                   ^

In file included from C:\Users\zafer\Desktop\Main\Main.ino:2:0:
Map.h:6: error: provided for 'template<class E, class T> class Map'
 template<typename E, typename T> class Map {

                                        ^
exit status 1
expected ';' at end of member declaration

Sorry, If it's been already resolved and I couldn't find it.
Thank you.

What is the error?

I put the error in question.

What MCU/board are you using? AVR? ESP8266? Something else?

the errors indicate that it doesn't know what a 'String' is; 'string' is usually spelled in lowercase. n.b. not sure about string classes on arduino

Map.cpp has a ; missing at the end of the template.

I added ; to Main.cpp and I am still getting same error. I am using Arduino/Genuino Uno board. By the way, if I create instance like; Map<String, int> *list = new Map<String, int>(); then no compile error.

In this class declaration:
class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

This line is wrong:
    Map<int, String> *list = new Map<int, String>();

You can't execute procedural code when declaring a class. That has to go into the constructor or some other function.
For example, this compiles without errors:
Test.h
#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test() { list = new Map<int, String>; } ;
    ~Test();
    Map<int, String> *list;
};

#endif


text:
LCD readout is odd
I want it to display the current temperature in the middle of the screen, fade out for two seconds, display new temperature, rinse repeat.  This is current (see images)]2
/*
 * File:    readTemperature.ino
 * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
 * License: GPLv3
 *
 * For more information see www.freetronics.com/irtemp
 *THIS NOW WORKS!!! Except for reading to LCD.
 */

#include "IRTemp.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

static const byte PIN_DATA    = 2; // Choose any pins you like for these
static const byte PIN_CLOCK   = 3;
static const byte PIN_ACQUIRE = 4;

static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

void setup(void) {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // initialize the serial communications:
  Serial.begin(9600);
}

void loop(void) {
  float irTemperature = irTemp.getIRTemperature(SCALE);
  printTemperature("",irTemperature);
 delay(1000);
   // when characters arrive over the serial port...
  if (Serial.available()) {
    // wait a bit for the entire message to arrive
    delay(100);
    // clear the screen
    lcd.clear();
    // read all the available characters
    while (Serial.available() > 0) {
      // display each character to the LCD
      lcd.write(Serial.read());

  // delay at the end of the full loop:
  delay(1000);

}
  }
}

void printTemperature(
  char  *type,
  float  temperature) {

  lcd.print(type);
  lcd.print(" temp: ");

  if (isnan(temperature)) {
    lcd.println("Failed");
  }
  else {
    lcd.print(temperature);

  }
}

Try setting the LCD's cursor to the right place...

Before you write the first character of your temperature text, set the cursor to where you want that first character to display.
For example, use lcd.setCursor(col, row); to set the cursor at a specified column in a specified row.  Row and column numbering starts from zero.
You can also use lcd.home(); to set the cursor at (0,0).
The output cursor advances a column each time you write a character.

So how do I change the code to reflect that?

I have set the cursor but it still prints all over the place in the correct order.

Can you edit your question to show this change where you "set the cursor" please?

/*
 * File:    readTemperature.ino
 * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
 * License: GPLv3
 *
 * For more information see www.freetronics.com/irtemp
 *THIS NOW WORKS!!! Except for reading to LCD.
 */

#include "IRTemp.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

static const byte PIN_DATA    = 2; // Choose any pins you like for these
static const byte PIN_CLOCK   = 3;
static const byte PIN_ACQUIRE = 4;

static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

void setup(void) {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 1);
  // initialize the serial communications:
  Serial.begin(9600);
}

void loop(void) {
  float irTemperature = irTemp.getIRTemperature(SCALE);
  printTemperature("",irTemperature);
 delay(1000);

  }

void printTemperature(
  char  *type,
  float  temperature) {

  lcd.print(type);
  lcd.setCursor(1,1);
  lcd.print(temperature);
  lcd.setCursor(7,1);
  lcd.print("celcius");

}

/*
 * File:    readTemperature.ino
 * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
 * License: GPLv3
 *
 * For more information see www.freetronics.com/irtemp
 *After much playing around this is the finaL result.
 */

#include "IRTemp.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

static const byte PIN_DATA    = 2; // Choose any pins you like for these
static const byte PIN_CLOCK   = 3;
static const byte PIN_ACQUIRE = 4;

static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

void setup(void) {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 1);
  // initialize the serial communications:
  Serial.begin(9600);
}

void loop(void) {
  float irTemperature = irTemp.getIRTemperature(SCALE);
  printTemperature("",irTemperature);
 delay(1000);

  }

void printTemperature(
  char  *type,
  float  temperature) {

  lcd.print(type);
  lcd.setCursor(1,1);
  lcd.print(temperature);
  lcd.setCursor(7,1);
  lcd.print("celcius");

}


text:
ping pong with two Arduinos over serial
I have two Arduino boards and want to make them communicate with each other over serial. The code I have used for the two boards is almost identical.

Every one second the "A" board sends a "ping" message over serial.
The "B" board receives the "ping" message and responds with a "pong" one.
The "A" board receives the "pong" message and prints it on screen.

Board A - ping code
String inputString = "";
boolean stringComplete = false;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  Serial.print("ping");

  if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
  delay(1000);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
    }
  }
}

Board B - pong code
String inputString = "";
boolean stringComplete = false;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  if (stringComplete) {
    Serial.println("pong");
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
  }
 }
}

The code seems to work, but not exactly as expected. I initiate the serial monitor of the board "A" and expect to see every one second:

pingpong

Instead I see this:

pingpong
pong
pong
....

which means that the pong message is repeated more than one time per second. But I want the "B" board to transmit the "pong" message only when it receives the "ping" one.
Why is this happening? Is there an error in the code? Is there a detail about the serial protocol which escapes me?
Any thoughts would be appreciated.

You should output every log message directed to human-programmer with a prefix like "#" or ... and so in your program you don't interprete any line beginning by a "#" ...

@AlexandreMazel Using a separate port for debugging and communication would be one more solid, less software option?

@user3060854 you might even want to make one piece of code, for two devices. And that you can select if it's master or slave by pulling a pin low setting it high. Or with some setting in EEPROM. Or at startup/button.
Would be easier to maintain and is quite an usefull trick to learn.

@user3060854 if you can hook up some displays and/or buttons, you can actually make them play ping-pong :D (I'm curious to see what you'll make out of this project)

The problem is with your protocol and also with how you are using the serial.
You are using the same serial channel both for your communication protocol and for the reporting of the results.  What you see the B end sees.
So A sends ping, and when it sees the letter g it responds with pong.  You then print that pong to the serial, so end B sees pong. It gets the character g and thinks "That was a ping, I'll respond with a pong", so it does - it sends pong, which you then receive and duly print - starting the sequence over yet again.
You either need to separate out the communication and the reporting, or make your protocol look for the whole string "ping" so it never inadvertently responds to a "pong" when it shouldn't.
Here's a good resource about reading serial strings on the Arduino: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

I changed the code accordingly to your answer and works fine. Thank you.


text:
Generate a ramp input with an Arduino Uno
Is there anyway to generate a ramp input from an Arduino Uno? A visual depiction of the pulse I am looking for is as follows:

With other microcontrollers, I was able to use their in-built DACs, however I am aware that the Arduino UNO doesn't have any? Is there a way using PWM or analogWrite to output these type of pulses? I'm new to Arduino programming, so I'm a bit unsure. However my next guess would be to use an R-2R ladder to output this type of pulse?

A resistor ladder is a good option. For example 4 pins for 16 steps. What frequency is the signal and how steep and how accurate should the ramp be? The Arduino Uno does not have a analog output. The function analogWrite is PWM (it should be called pwmWrite).

Yea, I was thinking on using an R2R ladder. The rise time should be really fast (around 150 microseconds), and then 50 microseconds of constant voltage. After that, it could drop to 0 instantly. Yea I was fearing that I might need to use an R2R ladder

The function digitalWrite on a arduino uno is 5 microseconds. It can be (a lot) faster when writing directly to output registers of the microcontroller. Together with the function delayMicroseconds and turning off interrupts, then it is possible. The default pwm frequency is 500Hz when using the arduino libraries, that is too slow.

@Jot ahhh, I see. I will try giving it a go. I'm actually generating this pulse to trigger muscles. Okay but instead of directly outputting to the registers, won't digitalWrite alone, also be able to accomplish this rise time?

No, that is very fast and there is no way to slow it down. The 5 microseconds is used to call the function, check if the pin is valid and find the register and bit for that pin: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_digital.c#L138 Would a pullup resistor and capacitor and transistor be possible? The resistor and capacitor to rise slow, and the transistor to fall fast.

@Jot ahhh I hadn't considered that. Yes, I will definitely give these a try. Yea that is interesting. Would it be possible to show a circuit arrangement of what that type of circuit what look like?

A RC filter will create a slow slewrate.

simulate this circuit – Schematic created using CircuitLab
The circuit creates this signal:

A slow rising signal and a fast falling signal can be created with an extra transistor (the signal will be inverted).

simulate this circuit
For a linear rising and falling edge, a resistor network with a few digital pins is a simple solution. I think it can be created with an opamp circuit as well, but there are also special chips called "slew rate limiter".

This is so incredibly helpful! Thank you so much!

By "ramp", it seems that you mean a square wave with sloping rather than vertical edges between + and -.  Can you clarify the question further: do the sloping parts need to be linear?
Direct synthesis of the waveform could be done using the digital output ports and an R2R ladder, as suggested in the comments.  Each PWM timer output of the AVR can control output of 2 digital pins and definitely with a timing precision better than 1 microsecond.  If high voltage resolution is needed, this method may not be able to produce the result you want.
Other possible solutions:

The waveform as plotted in the original post looks like a truncated sine wave.  Such a waveform could be made by clipping a sine wave with an operational amplifier.  For the sine wave connect the Arduino to a DDS module such as AD9850/1.
Use an external digital-to-analog converter, e.g. MCP48x2
Use an Arduino Zero or other 32-bit microcontroller (e.g. ARM STM32).  These microcontrollers have a true analog output pin, but it's not bipolar.

Yes, it could be any. A sine wave or a sloping square wave. I will update the question. I will take a look at all the solutions that you suggested. Thank you for the help!


text:
No valid serial ports for Arduino UNO on Mac
UPDATE: The issue turned out to be with my work laptop. Our IT department has them configured in such a way that the assignment of serial ports is different somehow. When I plugged in on my personal Macbook Pro it all worked perfectly.

I just got my first Arduino. Its an UNO R3. I'm running OS X 10.8.5 (Mountain Lion) and the Arduino IDE 1.0.5
Under Tools>Board I have Arduino Uno selected
Under Tools>Serial Port my options are:

/dev/tty.Bluetooth-Serial-1
/dev/cu.Bluetooth-Serial-1
/dev/tty.Bluetooth-Serial-2
/dev/cu.Bluetooth-Serial-2
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem
/dev/tty.Bluetooth-PDA-Sync
/dev/cu.Bluetooth-PDA-Sync

I've tried all of them, but when I try to upload a sketch it fails. Most give the following error:
avrdude: stk500_recv(): programmer is not responding

The two "modem" options return this message:
Serial port '/dev/tty.Bluetooth-Modem' already in use. Try quitting any programs that may be using it.

I'm at a loss. None of these serial ports seems correct but there aren't any other options.
Also under Tools>Programmer which option should I be using?

The issue turned out to be with my work laptop. Our IT department has them configured in such a way that the assignment of serial ports is different somehow. When I plugged in on my personal Macbook Pro it all worked perfectly.

Have you hooked up your Arduino prior to pulling down the tools>Serial Port menu? I only see the port for my Arduino listed when it's actually connected and running. (And it's never one of the bluetooth ports.) I don't have my Arduino with me at the moment so I can't tell you exactly what it is.
Also note that on my MBP (running 10.9.4) I have to be sure to plug the USB cable into the CORRECT USB port. The other port maps to a different port in the list of serial ports.


text:
Garbled data output from sensor through XBEE?
I have a fio v3 + a 9DOF sensor hooked up to an XBEE. On another UNO board, I have a GSM shield and another XBEE board.
The fiov3 is supposed to sample data from the sensor, send it through the xbee. The receiving XBEE will then receive and pass the data to the UNO. The UNo then activates the GSM shield on condition.
However my resulting output on the UNO is as shown :

The data received is corrupted.
CODE ON UNO.
/*****************************************************************
XBee_Serial_Passthrough.ino

Set up a software serial port to pass data between an XBee Shield
and the serial monitor.

Hardware Hookup:
  The XBee Shield makes all of the connections you'll need
  between Arduino and XBee. If you have the shield make
  sure the SWITCH IS IN THE "DLINE" POSITION. That will connect
  the XBee's DOUT and DIN pins to Arduino pins 2 and 3.
*****************************************************************/
// We'll use SoftwareSerial to communicate with the XBee:
#include <SoftwareSerial.h>
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

void setup()
{
  // Set up both ports at 9600 baud. This value is most important
  // for the XBee. Make sure the baud rate matches the config
  // setting of your XBee.
  XBee.begin(9600);
  Serial.begin(9600);
}

void loop()
{
  if (Serial.available())
  { // If data comes in from serial monitor, send it out to XBee
    XBee.write(Serial.read());
  }
  if (XBee.available())
  { // If data comes in from XBee, send it out to serial monitor
    Serial.write(XBee.read());
  }
}

CODE ON FIOV3.
#include <SPI.h> // Included for SFE_LSM9DS0 library
#include <Wire.h>
#include <SFE_LSM9DS0.h>

#define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
#define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
// Create an instance of the LSM9DS0 library called `dof` the
// parameters for this constructor are:
// [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

const byte INT1XM = 4; // INT1XM tells us when accel data is ready
//const byte INT2XM = 8; // INT2XM tells us when mag data is ready
//const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
const int buttonPin = 15;     // the number of the pushbutton pin

int buttonState = 0;

void setup(){

  pinMode(INT1XM, INPUT);
  //pinMode(INT2XM, INPUT);
  // pinMode(DRDYG, INPUT);
  pinMode(buttonPin, INPUT);

  dof.setAccelODR(dof.A_ODR_1600);
  dof.setAccelScale(dof.A_SCALE_16G);

  Serial.begin(115200); // Start serial at 115200 bps
  Serial1.begin(9600);
  // Use the begin() function to initialize the LSM9DS0 library.
  // You can either call it with no parameters (the easy way):

  uint16_t status = dof.begin();
  // Or call it with declarations for sensor scales and data rates:
  //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

  // begin() returns a 16-bit value which includes both the gyro and
  // accelerometers WHO_AM_I response. You can check this to make sure
  // communication was successful.
  // Serial.println(status, HEX);

}

void loop(){

  //Serial1.println("Hello!");

   buttonState = digitalRead(buttonPin);

  if (buttonState == 1) {

    //  Serial1.println("Hello!");

  printAccel();
  }

  //if (Serial1.available()){
     // Serial.write(Serial1.read());
//  }

}

void printAccel()
{
  // Only read from the accelerometer if the accel interrupts,
  // which means that new data is ready.
  if (digitalRead(INT1XM))
  {
    // Use the readAccel() function to get new data from the accel.
    // After calling this function, new values will be stored in
    // the ax, ay, and az variables.
    dof.readAccel();

    Serial.print("A: ");

    // Using the calcAccel helper function, we can get the
    // accelerometer readings in g's.
    Serial.print(dof.calcAccel(dof.ax));
    Serial.print(", ");
    Serial.print(dof.calcAccel(dof.ay));
    Serial.print(", ");
    Serial.println(dof.calcAccel(dof.az));

    Serial1.print("A: ");

    // Using the calcAccel helper function, we can get the
    // accelerometer readings in g's.
    Serial1.print(dof.calcAccel(dof.ax));
    Serial1.print(", ");
    Serial1.print(dof.calcAccel(dof.ay));
    Serial1.print(", ");
    Serial1.println(dof.calcAccel(dof.az));

  }
}

Any idea how to mitigate this would be greatly appreciated.

Are the xbees addressing each other? Sometimes if you don't directly address each other (ie you are in broadcast mode) data gets dropped.

@Treesrule14 How would I go about checking that? I am a little new to the XBEE. If you could post an example/tutorial, that will be highly appreciated.

Do you have a module which can connect the units to the computer? If so you can use XCTU try using this tutorial once you have downloaded it. https://www.youtube.com/watch?v=EA-2Xa5OAY8.


text:
Is TM4C123 similar to Arduino?
I'm currently studying embedded systems on eDx.
https://courses.edx.org/courses/UTAustinX/UT.6.01x/1T2014/info (must login to see)
http://users.ece.utexas.edu/~valvano/edX/index.html (don't need to login)
and I found out that TM4C123 is quite similar to Arduino.
but I haven't worked TM4C123 yet.(I ordered it and I'm waiting for it)
 I don't know much about it.
and it's not that popular as Arduino I guess.
so If anyone has used Tm4C123, please give me some information compared to Arduino.

This link does not show anything about this course or requires registration, this is not acceptable. Rather try to copy part of the course description to your question so that we know what it is about.

@jfpoilpret I'm sorry. I've just added the link. thanks :)

It's a micro controller, just like an Arduino. But it's more powerful than an Arduino. 32-bit instead of 8-bit architecture, faster clock-speed, more flash memory, more s-ram, usb-support. You just don't get the ton's of libraries and tutorials that are available for arduino.

@Gerben: Seen the Due yet?

Arduino'like IDE for Launchpad http://energia.nu/

The Tiva C LaunchPad is comparable to the Arduino Due in power and capabilities, but is incompatible with the stock Arduino ecosystem. It uses "BoosterPacks" rather than Shields, and Code Composer Studio (or other [some non-gratis] tools) instead of the Arduino IDE and libraries.
The Energia IDE is a port of the Arduino IDE and significantly simplifies configuration and programming Tiva C launchpads.
Beware of odd quirks with the Tiva C Launchpad board, such as the 0-ohm shunts that must be removed if you want all pins to be completely independent.

But if you're looking to jump from an AVR-based Arduino then I recommend the MSP430-based LaunchPads instead.

Actually, as the Tiva C has an ARM Cortex-M4 CPU it is likely that free toolchains can be used and an Arduino port seems possible.  But yes, it is quite different hardware and from the manufacturer a quite different environment.

@ChrisStratton: Corrected.

I have completed the edX course, and the TM4C123 is significantly different to the Arduino from a programming perspective. Each family of microcontrollers have (on the surface) a fair amount in common - GPIO pins, an ADC or two, timers etc. However the way these work internally are very different - different registers, different process for using them, different gotchas to look out for, etc. If you're looking at tackling a new MCU family, be prepared to effectively learn a new "language".
Incidentally, the Launchpads from Texas Instruments have a processing-based language similar to the Arduino - called Energia - which should work on your TM4C123.
Enjoy the course, I did.

Thank you for the information.
I have a question.
Do you think TM4C123 will be more popular or it's just for embedded students or hobbyists??

@StarbuckSb: With all due respect to TI, I honestly don't think they can make something that can displace the Arduino any time soon. Which is fine, they don't have to; their products are excellent regardless.


text:
Serial device file no longer shows up in /dev/ after working fine for months
I am using an Arduino MEGA connected to my Linux workstation via USB. I have been using this setup for several months with no issues.
A few days ago, the usual serial device file (/dev/ttyACM0) stopped showing up when I plug in the device)

Haven't re-flashed recently.
Unable to reflash.
Removing the devices only shield does not do anything.
Have not changed my physical setup recently.
Connector cable is confirmed working with a different device.

Is this a case of bad hardware, or is there a possible fix other than buying a new device?
dmesg results: None (cleared buffer and re-ran dmesg after plugging / unplugging device)
usb-devices:
T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1a.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1d.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=02 Prnt=02 Port=03 Cnt=01 Dev#=  3 Spd=480 MxCh= 0
D:  Ver= 2.00 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1bcf ProdID=2805 Rev=20.15
S:  Manufacturer=6047B0021601A0218M7NB
S:  Product=HP HD Webcam [Fixed]
C:  #Ifs= 2 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=0e(video) Sub=01 Prot=00 Driver=uvcvideo
I:  If#= 1 Alt= 0 #EPs= 0 Cls=0e(video) Sub=02 Prot=00 Driver=uvcvideo

T:  Bus=02 Lev=02 Prnt=02 Port=05 Cnt=02 Dev#=  4 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=0bda ProdID=0001 Rev=68.17
S:  Product=CSR BS8510
C:  #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
I:  If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb

T:  Bus=03 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=04 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=5000 MxCh= 2
D:  Ver= 3.00 Cls=09(hub  ) Sub=00 Prot=03 MxPS= 9 #Cfgs=  1
P:  Vendor=1d6b ProdID=0003 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

ls-usb:
Bus 002 Device 004: ID 0bda:0001 Realtek Semiconductor Corp.
Bus 002 Device 003: ID 1bcf:2805 Sunplus Innovation Technology Inc.
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Please give us any relevant output from dmesg and also lsusb and usb-devices

The fact that dmesg gives you nothing at all is the most telling fact.  The there was a communication problem, or the firmware had messed up on the USB interface chip, then you'd expect something to show up - even if it was something along the lines of "device not accepting address 8: -71"
We can ignore the main ATMega2560 chip since that has no bearing on the USB interface.  Instead we're interested in the ATMega16U2 (or whatever is on your board version).
So some things you need to confirm by probing around on the board with a multimeter, or better still, an oscilloscope:

Check that there is power to the board through the USB.
Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
Grab the datasheet for your ATMegaxxU2 chip and get the pinout.  Check that there is power on the pins there should be power on.
Check that the RESET pin of the ATMegaxxU2 chip is HIGH.

If you have a hardware programmer, or another Arduino you can use as a hardware programmer, connect it to the 2x3 header (you may need to populate it first) and try get it to identify the chip ID.  Try to re-flash the USB interface firmware.
Another thing to check is the USB socket itself.  Those big chunky USB sockets look strong, but they're actually quite flimsy inside.  The metal leaves that the plug presses against can bend with time and not make a good contact.  Using a fine needle try lifting them up slightly so they make better contact with the cable.  I think Arduino are the only people that still use them in an active product these days ;)


text:
Writing Data through Pin at certain frequency
I have an Arduino UNO which is connected to an KLZ25 board, the Arduino sends an 1MHz Clock at Pin 9 and now I should write the PDM-Data with 1 Mhz at pin 8. But i don't know how to write with such a speed, because if I write in the Loop:
loop{
digitalWrite(1);
digitalWrite(0);
}

I get only a frequency of 36Khz, I know it depends on the count of commands in the loop, but I don't know how to write with a certain frequency in my case 1Mhz.
I get the PDM-Data (pulse density modulation) in form of 1 and 0 from a python script on a Host-PC and now I want to stream the Data with 1MHz to an other developer board which makes further calculation with the PDM-Data. I store the PDM-Data in queues because I have not enough memory to store the whole Data.
Does anybody know how to write PDM-Data with a 1MHz frequency to an output pin ?

What does the acronym PDM mean?  It would help to state it in your question.

Use one of the timers on the UNO. Those are the ones that are used for PWM. Set the prescaler to /8. Set the mode to fast-pwm. Set the output pin to no-inverting mode. Set OCxA/OCxB to 2 (since the timer runs at 2Mhz). Then change the TOP value based on the PDM value you want to send.

PDM means pulse density modulation, basically I write 1 or 0 with 1Mhz frequency. @Gerben What do you mean by TOP value ? Does the change of the timer changes also the loop speed because I don't get how to write in 1Mhz if the loop is slower.

DigitalWrite itself is super slow. It takes a lot of cycles. loop itself also takes a few cycle to get called. You could use direct port manipulation instead, which is a lot faster. But to run at 1Mhz, you only have 16 cycles to toggle the pin and run the loop, leaving you with nearly no time left to do anything else.  Also other interrupts could occur and slow your loop at "random" intervals, giving you a unstable 1Mhz signal. That's why I'm suggesting using timers, as they run in parallel.

The timer is for example used to PWM an LED. This timer runs parallel to your code. The timer has a counter that it increments every clock cycle. You can select a TOP value, so that, when it reaches this value, it reset the counter to zero. It also has a compare registers. You can instruct the timer that, once the counter reaches the value in the compare register it should set one of the output pins LOW. You can also instruct it to set the output pin HIGH when it's set back to zero. So by combining this the output will be HIGH for 1µs, followed by a number of µs LOW, depending on value of TOP.

You might also be able to emulate the desired behaviour with one of the atmegas interfaces (e.g. SPI master). The essence of what Gerben mentioned is that you should use the available hardware because as you already found out handling this stuff in loop() won't work at 1 MHz.

16 CPU cycles is a very short time. You won't be able to do much other than the delta-sigma algorithm for generating the PDM output. Some time ago I wrote a program that does almost what you are asking for. It reads data in a “shift register” fashion and outputs it as PDM at 615 kHz with a CPU running at 8 MHz. That's 13 CPU cycles per PDM cycle. It's intended to run on an ATtiny13A and should be easy to adapt to an Uno. It's based on a carefully timed assembly loop, with no interrupts. Tell me if you are interested in me publishing it.

Ah ok I understand, thanks for the answers! @EdgarBonet that would be nice if you would publish it. I don't know if the SPI solution would work with the frdm-klz25 board but I will try to use the timer interrupt solution and if this don't fit I give it a try, thanks! And I don't must do the sigma delta modulation, I have done it on python on the Host-PC and I use the Arduino to send the Data to a KLZ25, basically the Arduino and the Host-PC together simulates a Microphone and on the KLZ25 I will do an MFCC calcuation after I streamed the PDM-Data from the PC to the Arduino.

If I understand correctly, you want to output a synchronous serial bit
stream at 1 MHz. Something like this:
        ___     ___     ___
clk  __/   \___/   \___/   \___⋅⋅⋅
     ______ _______ _______ ___
dat  __D0__X___D1__X___D2__X___⋅⋅⋅

where the data bits come from the PC.
If you want this to be a continuous bit stream, it will not be easy to
generate on an Arduino Uno.
Receiving the data
Since the data comes from the PC, it comes presumably through the serial
link. You have to account for the fact that this link adds a start bit
and a stop bit to every byte. Thus, you have 10 bits on the wire
for every 8 bits of actual data. Since you have to sustain
1 Mb/s average of actual data, this means that you must configure
the serial port for at least 1.25 Mb/s. However, the only baud rate
higher that 1 Mb/s supported by the Arduino Uno is 2 Mb/s.
Does your PC support this baud rate? Is the communication reliable at
this speed?
If the speed is too high, I would suggest you try to have the PC send
the data as PCM at a lower speed, and have the Arduino handle the
PCM → PDM conversion.
Transmitting the data
This data format is very similar to an SPI transmission. Then, the SPI
hardware port seems like the easiest way to generate it. However, the
SPI transmitter on the Uno is not double-buffered. This means that you
have to wait for the current byte transmission to be finished before
providing the next byte to the SPI hardware. This in turn means that you
will inevitably have small delays between consecutive bytes, and one out
of every 8 clock cycles will be stretched beyond the expected
1 µs. If this unsteadiness is acceptable for your application, then
do use the SPI transmitter. If not, you will have to find another
solution.
The serial port on the Uno has a special mode of operation where it
behaves like a master SPI port. Unlike the actual SPI port, this port is
double-buffered, which makes it possible to send a continuous bit stream
with a steady clock. The problem is, you cannot use this mode for
transmission and at the same time use the serial port receiver in its
regular asynchronous mode. Thus you will not be able to receive the data
from the PC when using this mode. If you can manage to route the
PC → Arduino communication through SPI, this mode of operation
of the serial port may be a good choice.
If none of the options above works for you I suggest, as last resort, to
generate the bitstream entirely by software. The timings are tight, as
each level of the clock has to be held for only 8 CPU cycles. But
it is likely doable in hand-written assembly, provided that interrupts
are disabled. Here is roughly how I may try to do that:
    in output, _SFR_IO_ADDR(PORT_OUT)   ; save a copy of the port reg.

loop:
    lds data, _SFR_MEM_ADDR(UDR0)       ; load data from USART

    ; output bit 0
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 0                         ; save data[0]
    bld output, 0                       ; load it into output[0]
    ; no delay needed here
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6                             ; assumed to be a macro
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; output bit 1
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 1                         ; save data[1]
    bld output, 0                       ; load it into output[0]
    delay 4
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; etc...

    rjmp loop

The code above assumes the UART is synchronized with the output stream,
which will likely not be the case in reality. Your real application may
then be more complex, and you will have to make that extra complexity
fit within the delay slots above.
Note that if you handle the PCM → PDM conversion on the
Arduino the resulting code may end up being simpler, as you will be able
to read the UART at every loop iteration without worrying about
synchronization. I have written a program that does something very
similar a while ago, and I just pushed it to GitHub for you to take a
look: avr-dac: Turn an AVR into a 1-bit D/A converter. Note
that this program is meant to be usable on AVRs without a hardware UART.
It expects the PCM data to be fed in the fashion of a shift register.
Using the UART would make the program simpler.


text:
DHT22 Hanging Up Entire Program
In the process of learning and working on a larger project, I started by adding an OLED display (128x64, SPI). I wrote a simple script to update every 5 seconds and then display the number of seconds on both the OLED and the Serial port. This worked just fine and I even let it run for more than a day. Then I added a DHT22. This is where the issues started coming in. The Arduino Mega (clone) is powering both devices. I have a 10K resistor across the VCC and signal pins of the DHT22. The code should now update both the OLED and the serial port with the number of seconds and the temperature and humidity. This works, for awhile, and then the whole program freezes for some odd reason. The time before freezing is also at random intervals.
During my research it was suggested to add a 10uF capacitor across the ground and VCC. So I added a 10uF 50v cap and the results are still the same. Originally I had Serial.println(String(..... in the code, but I replaced all that to not use String(). I tried adding Serial.flush() at the end of the display code, but equal results.
Additional research also suggested waiting 30 seconds before trying to read the DHT22. I added this 30 second wait at the end of the setup function, but same results. I've tried checking for NaN, not checking for NaN and nothing has seemed to correct this issue.
I've also tried the program without the OLED. Same results. I've tried the program without the Serial output, but same results.
What is going on here and does anyone have any suggestions as to how to correct this?
Currently this whole thing is rigged up on a breadboard if that helps.
Below is the current code I'm trying:
#include <Arduino.h>

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

#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// Adafruit Libraries for the OLED display
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// Setup the OLED variables
#define OLED_MOSI   9 // D1 on the OLED
#define OLED_CLK   10 // D0 on the OLED
#define OLED_DC    11 // DC on the OLED
#define OLED_CS    12 // CS on the OLED
#define OLED_RESET 13 // RES on the OLED
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// Global variables
unsigned long currentMillis;
long previousMillis = 0;
#define interval 5000

float humidity;
float fahrenheit;

void setup(){
  // Start the serial port transmission
  Serial.begin(9600);

  // Start the OLED
  display.begin(SSD1306_SWITCHCAPVCC);

  dht.begin();

  // Clear the memory of the OLED
  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(1,0);
  display.println("Madgayrah");
  display.display();

  while(millis()<2000);

  display.setCursor(0,16);
  display.println("Arduino");
  display.display();

  while(millis()<5000);
//  while(millis()<30000);

  Serial.println("");
  display.clearDisplay();
}

void loop() {
  currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    poll_and_display(currentMillis);
  }
}

void poll_and_display(long currentMillis){
    read_dht22();

    Serial.println(previousMillis/1000);

    if(!isnan(humidity) && !isnan(fahrenheit)){
      Serial.print(fahrenheit, 1);
      Serial.print("* ");
      Serial.print(humidity, 0);
      Serial.println("%");
    }

    display.clearDisplay();

    display.setCursor(0,0);
    display.println(currentMillis/1000);
    if(!isnan(humidity) && !isnan(fahrenheit)){
      display.setCursor(0,16);
      display.print(fahrenheit, 1);
      display.print("* ");
      display.print(humidity, 0);
      display.print("%");
    }
    display.display();

    Serial.println("");

    Serial.flush();
}

void read_dht22(){
    humidity = dht.readHumidity();
    fahrenheit = dht.readTemperature(true);

//    while (isnan(humidity) || isnan(fahrenheit)) {
//      unsigned long tempEnteredMillis = millis();
//      while (millis() - tempEnteredMillis < 2500);
//
//      humidity = dht.readHumidity();
//      fahrenheit = dht.readTemperature(true);
//
//      Serial.print("Result from NaN loop = ");
//      Serial.print(fahrenheit, 1);
//      Serial.print("* ");
//      Serial.print(humidity, 0);
//      Serial.println("%");
//    }
}

UPDATE:
After continuing to research on this I discovered that Arduino has a Watchdog Timer, or at least SHOULD have, and this SHOULD detect hang ups and restart the Arduino. So I tried a hardware version of the Watchdog Timer and a software version, but neither one seemed to work and/or correct the hang up/freeze issue. Below are the links I used for the software and hardware versions.
https://circuits4you.com/2018/01/24/tutorial-on-arduino-watchdog-timer-setup/
https://blog.frogslayer.com/creating-an-arduino-watchdog-timer/
I then ran across another post about a different solution that I have implemented and it seems to be working, but I want to give it some more time just to be sure. More updates to come.

Here is the solution. After searching last night I ran across this post https://forum.arduino.cc/index.php?topic=517608.new . Turns out, I was using the Adafruit DHT library and that seems to be what the issue was. I switched over to this https://github.com/markruys/arduino-DHT DHT library and it's been running for some 14 hours now with NO issues. Looking back through the Serial output I don't even see where it returned a NaN, not even once. I'm so excited to have this corrected and hopefully this will help out someone else stuck with this problem.


text:
How do i properly read an analog pin on attiny85?
Anyone ever run into a problem with your attiny not reading  your analog pins correctly? (-1023 or 1023 or 0 value) How did you resolve the issue?
Here's what my code looks like now :
4th revision of code as of 5/6/2015 8pm:
int NTC = A1; // thermistor
int switchPin = PB1; // push button
int LED = PB0;  // led

// button latch
byte ButtonState;
byte lastState = LOW;
byte count = 0;

 //brightness level of each different mode
int low = 50;
int med = 140;
int high = 255;
int dim = 0;

int ADCcount = 0;

void setup()
{

 pinMode(switchPin, OUTPUT);
 pinMode(LED, OUTPUT);

  }

 void loop()
 {

  ADCcount = analogRead(NTC);

delay(100);

  ButtonState = digitalRead(switchPin);

  if(ButtonState && ButtonState != lastState)  // button latch, no debounce      needed.
   {
      if(count < 4) // This will check to see if the count is within a range of  0 - 255
                 // anything over that, it will reset count back to 0. Of course
      count += 1;  // same as count = count + 5;
      else
      count == 0;
        }

    lastState = ButtonState;

   if (count == 0)
  {analogWrite(LED,0);}
    else if (count == 1) { if(ADCcount < 500) {analogWrite(LED,high);}
      else{ if(ADCcount > 525){analogWrite(LED,low);}
       }
          }
      else if (count == 2 ){analogWrite(LED,med);}
      else if (count == 3) {analogWrite(LED,low);}
      if(count >=4) {count = 0;}
      delay(50);
 }

simulate this circuit – Schematic created using CircuitLab

Show some effort and indent your code properly. Use four spaces in front of every line of code. I'd do it myself, but I'm on a phone right now.

350000 is a very big value for microsecond delay. The generated code might overflow and not actually wait or get stuck in an infinite loop. Use millisecond delay instead.

How is the thermistor wired? The pin assignments in your code do not fit your schematic. 2) The switch pin should be configured as INPUT. 3) What should happen when count = 1 and 500 ≤ ADCcount ≤ 525? 4) Why use two delays in loop() instead of a single 150 ms delay? 5) The test for count >= 4 at the end of loop() is useless. 6) A switch/case on count would make the code more readable. 7) Constants should be declared const.