text:
Arduino losing connection to Serial port after running function
For some reason when I loop my code through a separate function the serial port hangs up. The serial connection appears fine when I call cases within the loop but not when I call outside.
I tried to figure out where the problem is and for some reason using the Serial.print(ComControlValue); and the output is

-1

But the error still persists.
Previous it was this before I changed the baudrate

-b⸮⸮⸮⸮ Waiting for Command

It's not printing out the -1 I'm using as the main case. Could this be the problem?
#include <Wire.h>
/* RPi Army variables */
int RPi[3] = {3,6,9};                                        // SDA/SCL code names for the different Raspberry pi's

/* Define parameters for computer control */
int ComControlValue = -1;

void setup() {
  Serial.begin(115200);                                     // Establish Serial connection to computer
  Wire.begin();                                             // join i2c bus as master
}

void loop() {
 switch(ComControlValue){
  /* -1 : nothing happened yet */
  case -1:
     Serial.println("Waiting for Command");
     while (Serial.available()==0){}
     ComControlValue=Serial.parseInt();                             // Pull value from serial port
     break;

  case 111:
     Serial.println("Eat more Toast");
     ComControlValue = -1;
     break;

  case 210:
     Sendsignals(RPi[0],333);
     Sendsignals(RPi[1],333);
     Sendsignals(RPi[2],333);
     ComControlValue= -1;
     Serial.print(ComControlValue);
     break;
  }
}

void Sendsignals(int Rpi, int code){
   char str[4];
   sprintf(str, "%3d\n", code);
   Wire.beginTransmission(Rpi);                                 // transmit to device of choice
   Wire.write(str);                                             // sends 16 bytes
   Wire.endTransmission();                                      // stop transmitting
}

Consider adding more debug lines during your Sendsignals function.
Perhaps it hangs up during the Wire transmission.
You should also consider changing sprintf to snprintf - apparently it's more robust against buffer issues, and requires the buffer size to be set manually.

I tried that and it seems everything runs fine up until the break; when going through my separate function.

Arduino Uno with an Adafruit motor shield

reconnecting Serial Monitor resets the board. while (Serial.available()==0){} blocks the loop

Everything seems to work fine though when not calling Wire.h . Once I call the Wire.h functions the serial connection messes up.

Your str variable in function Sendsignals is short. sprintf writes 5 bytes to it, 3 digits, the \n and terminating zero. The terminating zero is written outside of the allocated array and causes the crash.

This causes the serial terminal to disconnect? How to fix? Should I increase the str to 8 bits?

Thanks. I changed the size of the str to 16 and it fixed the issue.

str[5] would be enough, if your codes have always 3 digits


text:
How to combine time into a variable
I have an Arduino Uno project which is recording student attendance using fingerprint sensor. So when sensor found a match, the serial monitor will be printing out Student ID and current time like this:
    DateTime now;
    void setup()
      {
          ...
      }

    void loop()
      {
          .....
          //found a match
          Serial.print("Found ID #");
          Serial.println(finger.fingerID);
          Serial.print("Time->");
          Serial.print(now.hour(), DEC);
          Serial.print(':');
          Serial.print(now.minute(), DEC);
          Serial.print(':');
          Serial.print(now.second(), DEC);
      }

Sample result will be:
Found ID#1
Time-> 18:11:54

I would like to store the time into a variable and print it out instead of printing hour, minute, and second separately. How can I do that???
I have tried to do like this as below but I'm getting an error, I would like to store it as a string. How can I do that?
string time = now.hour() + ':' + now.minute() + ':' + now.second();

It's going to be more efficient to print piece by piece. Because it constructs the text straight into the output buffer instead of needing to copy it over.

Hint: If you want to do some calculations or store a timestamp the data type time_t is a better choice. It is defined as seconds since midnight Jan 1 1970 (aka unix time). For more details see https://github.com/PaulStoffregen/Time/blob/master/TimeLib.h#L21

You want to use snprintf for this:
char timeString[9];

snprintf(timeString, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
Serial.println(timeString);

By using a format string like this you are taking into account time portions < 10 (like 7 minutes and 23 seconds past 3 am, which would otherwise be 3:7:23) by padding the time with leading zeroes where needed.

Damn, you were three minutes quicker with the same solution.
Replacing 9 with sizeof timeString could be useful in case he ever wants to include more data into his time stamp.

Could be - as long as timeString is in the same (or greater) scope and not a pointer passed to a function :)

@Majenko Do you familiar with python or firebase? Cause I would like to send the output to the python code, for the python code itself will catch the output and push it to firebase real time database. I refer to this website , I made the output like this Serial.println("{'SID':"+ String(finger.fingerID) +",'time':"+ String(timeString) +"}"); but I don't know how to catch it in my python

I loathe python with a passion, and I have never heard of firebase.

@Majenko It's ok. I do the same thing to date. But I can display date like this2018/11/. Day cannot display, what happened?

Did you give enough room in your string?

source: Stack Exchange

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

sort: votes


text:
Can the function be written without ";" in the end?
I have seen the following code on the Internet:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);
void setup()
{
  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);
}
void loop()
{
  if (Serial.available()>0)
  mySerial.write(Serial.read());
  if (mySerial.available()>0)
  Serial.write(mySerial.read());
}

The command works perfectly fine. How was it possible in the code to write the command without ";" at the end of the line?
The link to the code is: enter link description here

take a coding course or read a book about C or C++

Do you refer to this block?
if (Serial.available()>0)   <- here
mySerial.write(Serial.read());
if (mySerial.available()>0) <- here
Serial.write(mySerial.read());

If so, there is a ; at the end of each command. The commands are just split onto two lines each.  It could be written like this:
if (Serial.available()>0) mySerial.write(Serial.read());
if (mySerial.available()>0) Serial.write(mySerial.read());

The second and fourth lines are the body of the if.  Better indenting with the original arrangement would be:
if (Serial.available()>0)
    mySerial.write(Serial.read());
if (mySerial.available()>0)
    Serial.write(mySerial.read());

Or even better, include the brackets around the body:
if (Serial.available()>0) {
    mySerial.write(Serial.read());
}
if (mySerial.available()>0) {
    Serial.write(mySerial.read());
}

So this means, we are allowed to neglect the {} and () for conditions, right? But why do sometimes errors occur if I do not write this symbols?

You can omit the brackets if there is only one statement in the body of the if.

A conditional or loop expression, such as 'if' or 'while', controls the next statement or block. It does not need its own semicolon because it is not a complete complete statement. A block is one or more statements surrounded by '{' and '}' and is treated like a statement. So the following simple statement ended with ';' or block surronded by '{', '}' is a necessary part of the 'if' or 'while'.

authors: Асмир Абдимажитов

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


text:
MKR1000 and DS18B20 temperature sensor
I am new to Arduino and electronics in general and I can't get my MKR1000 to read correct data from a DS18B20 temperature sensor.
Here is the tutorial I followed.
The issue is: I always get the same readings from the sensor: -127.00.
I should mention I have tried 2 different sensors and get the same readings.
From the sensor, GND goes directly to GND on the board, and I have the 4.7kΩ resistor in between the data and power wires.
According to the sensor manufacturer, output leads: Yellow (VCC), Red (DATA), Black (GND).
Data line is connected to the pin ~2 on the MKR1000.
/********************************************************************/
// First we include the libraries
#include <OneWire.h>
#include <DallasTemperature.h>
/********************************************************************/
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
/********************************************************************/
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
/********************************************************************/
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
/********************************************************************/
void setup(void)
{
 // start serial port
 Serial.begin(9600);
 Serial.println("Dallas Temperature IC Control Library Demo");
 // Start up the library
 sensors.begin();
}
void loop(void)
{
 // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
/********************************************************************/
 Serial.print(" Requesting temperatures...");
 sensors.requestTemperatures(); // Send the command to get temperature readings
 Serial.println("DONE");
/********************************************************************/
 Serial.print("Temperature is: ");
 Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
   // You can have more than one DS18B20 on the same bus.
   // 0 refers to the first IC on the wire
   delay(1000);
}

Any idea what I am doing wrong?

In addition to the photos, do you have a schematic for the circuit to upload?  It would be more helpful than looking at the bunch of wires to figure out what is going on.

Thanks @MichaelT - This question has been answered already. Sensor manufacturer messed up their documentation so I had the power going to the data and vice-versa.

Looks like you have it wired wrong.  A schematic would really help but it looks like you've got 5V going directly into the sensors data line (yellow wire) it's connected on your breadboard to the orange wire +5V.  The power wire of your temperature sensor (red wire) is running through a 4.7K resistor which is not likely what you wanted here either.

According to the sensor manufacturer: Output leads: Yellow (VCC), Red (DATA), Black (GND)

May be a typo in their documentation.  I've found similar sensors on Ebay and:  Output lead: red (VCC), yellow(DATA) , black(GND)

The schema I am trying to achieve can be found on the link I posted earlier: https://create.arduino.cc/projecthub/TheGadgetBoy/ds18b20-digital-temperature-sensor-and-arduino-9cc806#toc-step-4--build-simple-circuit-3

OMG! Okay... you were right, they managed to get their schemas wrong! Red is VCC and yellow is DATA! I thought about many possible causes but not that one... ;) Thanks for your help.

The only thing worse than no documentation is errant documentation.


text:
Generated frequency is not as expected
This code sets a pin HIGH for 1 microsecond and then LOW for 1 microsecond. The expected frequency should be about 500 kHz. When measuring the output the frequency is about 96.4khz. Why ?
int del = 1;

void setup() {
   // put your setup code here, to run once:
pinMode(3, OUTPUT);
}

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

digitalWrite(3, HIGH);
delayMicroseconds(del);
digitalWrite(3, LOW);
delayMicroseconds(del);

}

Your code says 1 microsecond, but delayMicroseconds is actually much slower than that.  Also the loop has some overhead.  Try putting the code inside while(true){ }.  Recent versions of the Arduino IDE have got better at making code faster, but if you want timing accuracy it is better to use low-level timer/counters of the AVR.

digitalWrite() takes a few microseconds to execute as well. There is also some overhead around the delayMicroseconds() function.
If you need exactly 500 kHz, you would want to consider using a timer.
You can read up on how to set one up in the microcontrollers datasheet.
Unfortunately, I don't have access to an Arduino Leonardo, but here is an example code for the ATmega328P. The register names will be different, but you should be able to adapt the code to fit your Arduino.
// 500 kHz frequency

void setup() {
  cli();                 //Disable interrupt during setup
  TCCR2A = 0;
  TCCR2B = 0;

  TCCR2B |= (1 << CS20); //Enable timer without prescaler
  OCR2A = 15;            //Do interrupt TIMER2_COMPA after reaching this counter value
  TIMSK2 |= (1 << 1);    //Enable TIMER2_COMPA interrupt

  DDRD |= (1 << PORTD3); //Set Digital Pin 3 as Output Pin
  sei();                 //Enable interrupts again
}

ISR(TIMER2_COMPA_vect) { //If the counter has reached the point where the output needs to be low
  TCNT2 = 0;
  PIND |= (1 << PORTD3); //Toggle Digital Pin 3
}

void loop() {
  //your looping code here
}

Explanation:
TIMER2 is an 8-bit timer, which means it will always count from 0 to 255, regardless of what the CPU is doing.
Normally, it counts up at the Arduino's clock frequency, like 16 MHz.
When the counter hits 15, a special code is immediately executed, called an "Interrupt Service Routine". In this code, we reset the timer and change the state of your output pin, resulting in a 500 kHz square wave on that pin.
We count to 15 since there are 16 steps in between "0" where the counter begins and 15, where we reset it.
16'000'000 Hz / 1 (no prescaler) / 16 (counter) / 2 = 500 kHz
The divisor of 2 comes from the fact that we need to change the pin state twice for every full square of the output signal.

Sometimes you write 500kHz, then you write 500Hz. As calculated the code is for 500Hz. As the OP asked for 500kHz, the prescaler could be set to 1 and the compare value (at which the timer fires the interrupt) to 16. In my calculation this gives you exactly 500kHz. Am I right?

But as you wrote, digitalWrite() takes to long, so bit manipulation on the port registers are the right way to go: https://www.arduino.cc/en/Reference/PortManipulation

Yes, of course, I'm so sorry. This is what happens when you recycle code after a long work day. I'll fix it. And you're also right, digitalRead and -Write are too slow for 500 kHz, I'll implement it via the registers.

You could use one of the hardware time outputs like OC2A or OCRB and avoid the ISR/digitalWrite/bitbanging overhead entirely.

It's fixed now - so sorry again.
My scope isn't fast enough for 500 kHz, but it works as intended for 50 kHz.
The "standard" outputs are nice, but you're then limited to the two pins per timer. Is that already necessary at 500 kHz?

I think you answered the question as to 1) why: b/c overhead, 2) solving the 500kHz problem.  But if ISR overhead is still a problem  at this or higher freqs, he might have to tune with a smaller-than-calculated threshold, or go to hardware toggling on an OCxx pin.

https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM has a "Fast PWM Mode with OCRA top" section for this use case.

delayMicroseconds() has a minimum lower value of 3-4 us per the IDE documentation. It won't do 1.
loop() also adds some delay mechanisms doing it's background stuff.
You will see better results with a while() :
loop(){
  while (1){
  digitalWrite(3, HIGH);
  delayMicroseconds(del);
  digitalWrite(3, LOW);
  delayMicroseconds(del);
  }
}

with direct port manipulation in place of the digital writes.
There will also be jitter from the millis() background time keeping, if you want a smoother signal it will be best to turn off interrupts as well.


text:
How do I use a servo in an interrupt?
I am working on a small circuit now where I increment the rotation of a servo motor and at the same time blink a LED.
I have used all methods I know to do it but still it does not work or it blinks and then the servo start working but never both at the same time.
This is what i am basically working with:
  for(position=0;position<=90;position=position+5){
    digitalWrite(led_pin,HIGH);
    delay(200);
    digitalWrite(led_pin,LOW);
    delay(200);
    servoBar.write(position);
    delay(15);
  }

But it blinks once and then it stops and the servo start working right after that.
I know I must not use delays in interrupts. I am using a function that I can but just to show you what I am working with.

The problem is that the delay routine is blocking. It stops operation and blocks other things from happening. Have a look at the Blink without delay example in the example tab. (also linked below)
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
What you need to do is to not block. Call the time checker often and check if the time you want delayed has run out. The perform the action needed to be done at that time.
This is a more sophisticated way to deal with timed events. Also look at this
Demonstration code for several things at the same time.
https://forum.arduino.cc/index.php?topic=223286.0
Have fun learning. :)

If you want the timing mechanics of the interrupt, you'd want to create very slim loop() routine that only checks if your custom "move the servo" flag is set. If it is, remove the flag and move the servo, and use the interrupt only to set the flag.

A good way to manage timing without delay is to use:
if(millis()-lastCheck > delayPeriod){
lastCheck=millis();
doStuffHereOrChangeServo();
}

This code is naturally overflow-safe and is actually how delay() works. The difference is that delay() uses a while() loop that breaks when this condition is met, so it prevents any code after the delay from running UNTIL delay completes. That's why you are getting odd pauses in your code.
As a side note, it's actually a fun project to build a simple task scheduler that uses a list of function pointers and a variation on this method to do completely generic scheduling. If you want to try that route, you'd keep a struct holding the function pointer and a signed integer larger than your maximum intended delay size. Then, every time the scheduler is called, you subtract the difference between millis() and the stored value of millis() from each of those integers in the struct. Once that goes negative or zero, the task can run!


text:
Problem with Arduuino to breadboard Mega8
I am trying to make an arduino using mega8 mcu. After so much struggling with sync/response/signature  problems and reading the previous questions, finally managed to do it (almost). However I still have some weird problems.
I uploaded the arduinoISP sketch to an Uno for programming the chips: AtMega8A-PU and AtMega8L-8PI (I had a couple of L version from years ago).
For bootloader selected the Mega8 from NG board in IDE 1.8.5 then uploaded to Mega8A-PU
for the L version cloned the ng part in boards.txt and reduced the F_CPU to 8MHz, (same bootloader code) and uploaded to 8l
Now, I'm able to upload sketches to both using a usb-serial breakout board/ avrisp mkII.
my first problem is when I disconnect the converter board neither of the MCUs can start unless I pull up or pull down the RxD pin (#2) which i find accidentally. it seems they both stuck in bootloader part. even if i leave the reset pin floating (using internal pullup) and tie the rxd pin they work fine up on applying power (with like an annoying 15~16s delay). the resistor value I tried 1K and 10K but no difference in operation and delay time. it wont start with rxd open. I couldn't find why?
another question is running the code on mega 8L as reliable as on 8A? (need it for lower V)
More clarification: they both run with Xtals and 22pf caps on breadboard. the 8l also works fine with 16MHz Xtal at 5v.
sketch (I know it's not much of help):
void setup() {
  Serial.begin(19200);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  tone(10,3520);
}

volatile unsigned int i, var = 1;

void loop() {
  digitalWrite(9, HIGH);
  for(i = 0; i < 1500; i++)
                 var += ((var * 3) / 2);
                 // do something (if compiler not wipe it for optimizing :D )
  digitalWrite(9, LOW);
  Serial.println(millis());
}

sample of 8A and (similarly) uno output:
7 11 15 19 23 27 31 35 39 44 48 52 56 60 64 68 72 76 80 84 89 93 97 101 106 110

8L output @ 3.3v @8MHz:
16 24 32 40 51 59 67 75 86 94 102 110

tone() output is the same for all
Appreciate your help

I found here: https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader
that NG / mega8 bootloader doesn't enable the rx pin internal pullup nor it gets out of the bootloader even if receiving junk data on rx  (which was my case due to leaving it open thus floating). It also has a delay of 6 to 8 seconds intentionally.
Probably I'll use another bootloader since the link to source code on the page was broken or just program the L version without any bootloader and better fuse options.


text:
GPRS Based OTA to the NODEMCU
I need the OTA firmware update. I have the only option in my hand GSM(GPRS SIM800), with the help of this is it possible OTA, plz help me for this how I Do OTA via GPRS, FYI, I completed OTA Via WIFI.

Download the bin file over GPRS and then use the Update singleton object. It is declared in Update.h. Example is ArduinoOTAClass::_runUpdate() in ArduinoOTA.cpp or ESP8266HTTPUpdate::runUpdate() in ESP8266httpUpdate.cpp


text:
What do the charactors " '/2' " mean in the variable declaration?
I'm working on an RS485 project, In the CPP file there are const variables declared in the following manner:
#include <RS485_protocol.h>
const byte STX = '\2';
const byte ETX = '\3';

What does the '\2' and '\3' mean?

The '\2' and '\3' are characters with octal code 2 and 3. Which is nothing more then 2 and 3 in octal and in decimal. The author could simply write const byte STX = 2; const byte ETX = 3;.
Characters with ASCII code 2 and 3 are control characters STX (start of text) and ETX (end of text). Control characters are invisible characters used to control the terminal or as mark characters in communication.

Perhaps the question is more about the '' than the 2 and 3. A list is here: https://en.cppreference.com/w/cpp/language/escape


text:
Arduino pin 13 as PWM output, not possible?
I have noted on more than one occasion the comments in sketches "reserving pin 13 for future PWM backlight dimming of the LCD" while using Uno and Nano boards.
Am I missing something ?  I always considered it NOT possible as PWM output is only available on pins 3,5,6,9,10 and 11 on most boards.

Have you checked schematics and processor datasheets?  That pin may be backed with PWM hardware, but not be supported by Arduino software for the reason stated.  Remember that an Arduino is a product of a little self-contained ecosystem with certain design goals in mind.

you can program any pin to output a PWM signal

yes, but analogwrite() only works with those pins backed by hardware PWM circuitry on-chip

Arduino pin 13 is SCK/BP5 on the ATmega8 MPU, there's no hardware PWM capability on that pin, so any PWM would be software driven.


text:
Measure movement distance - not sure what sensor?
I want to measure the length of a step / stride -not sure what sensor to use.
I am trying to get several people to march a pattern for a band.  I am thinking a Arduino to beep when step is too short or too small.  Thinking the Arduino will be tied to their shoe laces.  IR or Ultrasonic do not seem to be the correct sensor to use.
Ideas?

Maybe just go lowtech and simply use rope? Tie person ankles together to train muscle memory when walking. Doing precise measurements quickly and in uncontrolled enviroment is a nightmare to sensors.

Or, to pick up Filip Franiks idea, use a small rope on a coil, that will roll itself up automatically. A step would roll some rope of the coil and you can measure the amount by measuring the rotation of the coil (for example with a rotary encoder).

The sensor to use is an accelerometer. The principle is easy: measure the acceleration, perform a double integration and you have the distance (after the first integration you have the velocity).
The problem is that, because of the double integration, small errors in the acceleration signal lead to big errors in the calculated distance. For example: an error e in the acceleration leads to an error e.t2 in the distance (where t stands for time). For this reason al sorts of filters are used often in combination with gyroscopes and/or gravity sensors. The signals from the gyroscopes and/or gravity sensors are used for the low frequency signals (long term) and te signals from the accelerometer(s) for the high frequency signals (short variations). That's why you find these sensors often combined in one package (for example the BNO055 form Robot Electronics https://robot-electronics.co.uk/bno055.html).
It is a complicated and highly mathematical area of science. In fact you want to do the same thing as fitness trackers do (and I think you are striving to a higher accuracy than they) - and there are not many that do really well.
P.S. Robot Electronics also sell a tilt compensated compass board with this BNO055 chip: the CMPS12 (https://robot-electronics.co.uk/cmps12-tilt-compensated-magnetic-compass.html). With this board you can read out absolute and relative positions straight away without any calculations.


text:
Ultrasonic sensor and ledstrip color problem
So I've made a parking sensor with the Ultrasonic sensor and a ledstrip. But the ledstrip doesn't turn yellow or green. I think it has to do with the Thresholds. Can anyone help me to set this up? I also want a longer distance greater than 1 meter. This is my code:
#include "FastLED.h"
 #include <math.h>

    #define NUM_LEDS 32
    #define BRIGHTNESS 10
    #define DATA_PIN 4

    // Define the array of leds
    CRGB leds[NUM_LEDS];

    // Module Pins
    #define trigPin 11
    #define echoPin 12

    // Thresholds (in CM)
    long SECTION_SIZE = 80;
    long STOP_DISTANCE = 60;
    long WARNING_THRESHOLD = 50;
    long MAX_THRESHOLD = 375;

    long RED_THRESHOLD = STOP_DISTANCE;
    long YELLOW_THRESHOLD = RED_THRESHOLD + SECTION_SIZE;
    long GREEN_THRESHOLD = YELLOW_THRESHOLD + SECTION_SIZE;

    const int numReadings = 5;

    int readings[numReadings];      // the readings from the analog input
    int readIndex = 0;              // the index of the current reading
    int total = 0;                  // the running total
    int average = 0;                // the average

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

      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      FastLED.setBrightness(10);

      // HC-SR04 Setup
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // initialize all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
    }

    void loop() {
      long distance, lastRun;
      bool red, yellow, green;
      total = total - readings[readIndex];
      readings[readIndex] = calculateDistance();
      total = total + readings[readIndex];

      readIndex++;
      if (readIndex >= numReadings) readIndex = 0;

      distance = abs(total / numReadings);

      yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
      red = distance <= RED_THRESHOLD;
      green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

      if (red) {
        setRed();
      } else if (yellow) {
        setYellow(distance);
      } else if (green) {
        setGreen(distance);
      } else {
        setGreenStandby();
      }

      Serial.print(distance);
      Serial.println(" cm");
      FastLED.show();
      delay(1);
    }

    void lightItUp(const CRGB& pColor, const CRGB& sColor, uint16_t travel) {
      uint16_t travelFix = travel * (NUM_LEDS/SECTION_SIZE);
      uint16_t leftStop = travelFix/2;
      uint16_t rightStop = NUM_LEDS - leftStop;
      for (int i = 0; i < NUM_LEDS; i++) {
        if (i < leftStop || i > rightStop) {
          leds[i] = pColor;
        } else {
          leds[i] = sColor;
        }
      }

      FastLED.show();
    }

    long calculateDistance() {
      long duration;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      return (duration/2) / 29.1;
    }

    void setGreenStandby() {
      return fill_solid(leds, NUM_LEDS, CRGB::Black);
    }

    void setRed() {
      return fill_solid(leds, NUM_LEDS, CRGB::Red);
    }

    void setGreen(long distance) {
      long travel = GREEN_THRESHOLD - distance;
      return lightItUp(CRGB::Yellow, CRGB::Green, travel);
    }

    void setYellow(long distance) {
      long travel = YELLOW_THRESHOLD - distance;
      return lightItUp(CRGB::Red, CRGB::Yellow, travel);
    }

what is longer distance greater than 1 meter?  .... please describe exactly what you want the code to do ..... also describe exactly what it does right now ..... add the information to the question above .... DO NOT add info to comments

I believe your mistake is in this part of your code:
  yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
  red = distance <= RED_THRESHOLD;
  green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

  if (red) {
    setRed();
  } else if (yellow) {
    setYellow(distance);
  } else if (green) {
    setGreen(distance);
  } else {
    setGreenStandby();
  }

In particular, you are defining three boolean variables independently and then switching based on their values.
Assuming you are seeing the right values output on serial monitor (like 90 cm, 60 cm, etc...), which is something I'm unsure of as I'm not getting how you are determining the distance, then the following should be easier to follow/understand:
if (distance > GREEN_THRESHOLD) {
  setGreenStandby();
} else if (distance > YELLOW_THRESHOLD) {
  setGreen(distance);
} else if (distance > RED_THRESHOLD) {
  setYellow(distance);
} else {
  setRed();
}

You have only one variable determining the led strip configuration, no need to go to 3 and then try to reduce again ;-)
Please note that your YELLOW_THRESHOLD is defined as 140, if you don't ever see a message in the serial monitor greater than that value you don't have a chance of seeing any colour other than red.... I'm asking because you mentioned I also want a longer distance greater than 1 meter that might imply your sensor is unable to go farther than 1 meter...
With the code above I'm checking the distance in a greater to smaller order: the first matching is the only one activated and it's impossible for the distance variable to match more than one condition. Generally speaking, simpler is better.


text:
How do I make a toggleable Infrared motion detection module
I just got an Arduino and an Infrared motion detection module. What I tried making is, that if the module detected movement, a led would turn on, and if it detected movement again, it would turn off. So I wrote this code and tried looking online for solutions, but couldn't find it. I really don't know what to change about my code to make it work. Does anyone have solutions for this?
(Sensor value can be 0 or 1, 0 means nothing detected, 1 means something detected. After detection the value automatically goes back to 0 in a few seconds)
int Sensor = 4;
int led = 13;
bool bool1 = false;

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

void loop() {
int SensorValue = digitalRead(Sensor);

if(SensorValue == 1){
  bool1 = !bool1;
  }

if(bool1 == true){
  digitalWrite(led, HIGH);
  }
if(bool1 == false){
  digitalWrite(led, LOW);
  }
}

what to change about my code to make it work  .... what is wrong with the way the code behaves right now?

Consider using a state machine with 4 states.  Currently you only have 2 states.  One where "bool1" is TRUE and another when "bool1" is FALSE.  The 4 states needed are:

When the LED is OFF & the PIR is NOT-ACTIVE.
When the LED is OFF & the PIR is ACTIVE.
When the LED is ON and the PIR is ACTIVE.
When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3.  And you will only want to turn the LED OFF when traveling between states 4 & 1.


text:
Porting the FastNoise c++ library to Due
I'm trying to use the FastNoise library with a Due, however, I get something like the following errors, when I try to complie.
error: 'abs' was not declared in this scope
error: 'mt19937' is not a member of 'std'
error: 'uniform_int_distribution' is not a member of 'std'
so I added the following:
#include <cstdlib>
#include <cmath>
#include <random>

which solved most of the problems, however it still says printf hasn't been declared. So I tried to edit cstdio to comment out the #undef printf, but it just brought back the full list of error messages, so that's not the solution. I googled some solutions but none of these seem to work. Do you have any suggestions I should try?
I'm not trying to use printf, just want to use the library.
Thanks for any help.

Also asked here: https://forum.arduino.cc/index.php?topic=579997.0 and we still don't know which library you are trying to port to the arduino.

apologies for spamming, this one: https://github.com/Auburns/FastNoise

I don't know how the std and algorithm extensions are used in the gcc compiler for arduino. They are not used a lot. I think it should be possible to convert it to normal c++ code. The printf might be connected with the std and the cstdlib extension. The arduino preprocessor includes most common include files, only extra libraries needs to be included. Your title of this question is about FastNoise, but the problem is how to port code to the arduino. Perhaps you can change the title of the question to get attention from experts.

The FastNoise library compiles as it is for the Arduino MKR and Arduino Zero, but there is a "not cool" issue for the Due: https://github.com/arduino/ArduinoCore-samd/issues/308
A issue with assert can easily be solved, but the #include <algorithm> and #include <random> are somehow linked to a printf function.
I thought it was very hard, but then @Juraj wrote in his answer about the simple solution to comment out the #undef printf line.
In the file cstdio is a list of about fourty #undef lines. Only the printf requires to be commented out.
// #undef printf

The file is located in the hidden "Arduino15" folder in the build environment for the Due: Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio
Then it will also compile for the Arduino Due (even without removing the assert). There are many warnings.
I was able to run it on a SAMD21 processor and it produces random numbers. However, I am not sure that those numbers are correct. I don't know if the many compiler warnings can be ignored.
#include <FastNoise.h>

FastNoise myNoise; // Create a FastNoise object

float heightMap[32][32]; // 2D heightmap to create terrain

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("FastNoise");
  delay(1000);

  myNoise.SetNoiseType(FastNoise::SimplexFractal); // Set the desired noise type

  for(int x=0; x<32; x++) {
    for(int y=0; y<32; y++) {
      heightMap[x][y] = myNoise.GetNoise(x,y);
      SerialUSB.println(heightMap[x][y]);
    }
  }
}

void loop() {
}

Do you know the XY Problem? You did not explain the reason for trying to make that library run on a Arduino Due. Perhaps there is an other way for what you want to achieve.
The Arduino Due was a major update for the Arduino boards, but nowadays some say to avoid the Arduino Due because it has issues (hardware and software).

I have updated my answer with help of the answer from @Juray.

Thank you guys, I tried to remove that line before, but it just say the same error messages when no library was included (it misses the abs function and so on).
Moreover, I was unable to compile it for Zero or MKR. Is it possible that something is missing for me? I have the regular Arduino IDE and downloaded the latest boards. (the error message is around 1000 lines, maybe these are the warnings you mention? however for me it does not compile)

I'm experimenting with LEDs with the FastLED library and serial communication, but the communication wasn't perfect since these LEDs (WS2812B) require precise timing, and the interrupts are disabled while the Uno is sending the LED data. So on the FastLED help page advises to switch to Teensy or Due. Since Due seemed the easier step from the Uno, I chose that. And with the added computational capacity I thought I can use the FastNoise library for noise generation instead of the FastLED one (which is fine, but has its faults). So I'm not persisting on using Due at all.

Do you think the FastNoise could be run on Teensy? Or that would be even harder to make work? Teensy seems way more powerful on floating point math (which this library uses) than Zero. Unfortunately I'm not even sure how much processing power I need exactly, I was just about to check how fast the Due is with the library (since I had to switch anyway because of the serial communication issue with the Uno)..

@Gergo, you might try to get the FastNoise library files again, maybe something has been changed. It compiles for the zero and mkr and by commenting out that line also for the due. I have no experience with the teensy. Stackexchange is about questions and answers. You could update your question that you want to use it for ws2812b leds and that the teensy or due is advised, and so on.

FastNoise did not change in the last year or so according to github, so I was skeptical about downloading it again, but did it nevertheless, and now it complies. I'm not sure what went wrong, since I should have the same FastNoise, as it did not change seemingly. Anyways, thank you very much for your time and help in this matter. Additionally thank you for the guidance how to use this forum.

The workaround is in the issue found by Jot.
In file
C:\Users\aaaaaa\AppData\Local\Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio
comment the line
#undef printf
and it will compile

Thanks, I missed that. I have updated my answer.

@Jot, the line must be removed


text:
Are hardware interrupts used while controlling an LCD screen using the LiquidCrystal library?
I'm working on a tone generator project that uses Mozzi to make sound (sine waves mainly). As I understand, Mozzi can glitch if used along with hardware interrupts.
The plan is to use the classic 2x16 LCD screen, but I don't know the guts of the library or interface. Are hardware interrupts used while interfacing with an LCD screen, or by the LiquidCrystal library?

The LiquidCrystal code shows that delays are used. That can cause audio glitches in the sound.
The LiquidCrystal library does not use interrupts.
You could try to change the LiquidCrystal code according to the instruction on the Mozzi page.


text:
Interfacing MAX6675 with Arduino Mega 2560
I'm trying to use a thermocouple k type and a MAX6675 IC.  I bought the MAX6675 chip and made the circuit (just a 1 nf capacitor on +5 V and GND near the IC) with the help of the datasheet
I used the library from adafruit and for the sake of avoiding errors, I used the Example from the same library (serialThermocouple) with 52 as CLK, pin 50 as SDO and pin 53 as CS.
The program is producing numbers and the sensor appears to stabilize around 104.0C and 105.0C, but why? that is not the real temp or even close to it? Is there any other conversion to get the real degree around me?
oh !! and Another question..
Why is the 8 bit shift here?

  v = spiread();
  v <<= 8;
  v |= spiread();

I saw it in many code. Also this one
digitalWrite(_ssPin, LOW);
tcData = SPI.transfer(0x00)<<8;
tcData |= SPI.transfer(0x00);
digitalWrite(_ssPin, HIGH);
temp = (tcData>>3)/4.0;

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Maximum signal frequency obtained at the gpios of arduino mega 2560
Is it possible to obtain the rectangular pulse signals of freuency 10 MHz simultaneously at the GPIOs of arduino mega 2560?

If you ran it at 20 MHz clock speed, maybe. But it's quite a stretch.

But in that case I am not getting perfect rectangular shape pulses. Please help me to solve the problem. Thanks in advance.

Short of replacing the on-board resonator, the maximum you can get is 8 MHz. You can get that on any of the pins identified as “PWM” (i.e. pins 2 – 13).

You should learn something about "impulse response". There is nothing like perfect. You can get closer to it by reducing parasitic capacitances/inductances and by using stronger line driver.

16 MHz is also possible if one of the fuses is changed to output the system clock.  '2560 is only rated to 16 MHz as well, at 20 MHz you'd be overclocking it:   ATmega2560/ATmega2561: • 0 - 16MHz @ 4.5V - 5.5V

The maximum fundamental frequency you can generate is fcpu/2 - or 8MHz with the default 16MHz resonator / crystal.
What shape the actual signal is, though, is very much dependant on the load on the IO pin. The IO pin has a specific drive strength which will provide limited current into a load. Any capacitance or inductance within that load causes a change in the slew rate (also known as the rise time or fall time) of the IO pin, which affects the shape of the signal by limiting the highest harmonic frequencies you observe.  At the worst case scenario, you get an almost sine wave (only the fundamental frequency gets through). In general though you get more of a rounded-off square wave:

You can improve that slew rate by adding a buffer with a higher drive strength to the output (assuming your buffer has a high enough bandwidth).  However, the IO pin itself will always have a certain amount of curvature to the signal due to its own internal capacitances.
For generating higher frequencies you are better off using a chip that is designed to operate at higher frequencies.


text:
Multiple sensors connected to Arduino MEGA 2560 Serial ports
I am using Arduino MEGA 2560 to read values from two sensors. Sensor 1 is providing us two values separated by a comma and a space followed by a newline character. e.g.:
2.277, 7.942
2.269, 7.897
2.263, 8.040

Sensor 2 is providing us a single value followed by a newline character. e.g.
1.213
1.333
1.17

Sensor 1 gives twice as many readings as Sensor 2 in the same amount of time. Sensor 1 is connected via Serial1 and Sensor 2 is connected to Serial2 on MEGA board. I am using the following code to read the values:
void setup() {
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    {
      Serial.print(Serial1.readStringUntil('\n'));
      Serial1.flush();
    }
  }

  Serial.print("\t\t\t");
  if (Serial2.available()) {
    while(Serial2.available())
    {
      Serial.write(Serial2.read());
      Serial2.flush();
    }
  }
  Serial.println();
  delay(1000);
}

I am expecting an output similar to this:
2.409, 8.150            2.134
2.490, 7.851            2.133
2.603, 8.759            2.122
2.634, 8.305            3.12
2.727, 8.408            1.32
3.018, 7.982            2.543
3.030, 7.982            1.345
3.020, 8.587            2.435
2.844, 8.034            2.763
2.690, 8.690            5.433
2.721, 8.011            2.348
2.705, 8.242            7.654
2.670, 8.713            2.123
2.756, 8.563            2.098
2.899, 8.413            2.765
3.464, 8.196            2.654
3.705, 8.437            2.343
3.435, 8.558            1.245
3.446, 8.592            2.345
3.421, 8.075            1.234

Instead I am getting something like this:
2.770, 8.332.635, 8.281         2.345
2.690, 8.690            2.674
2.721, 8.011            2.356
2.705, 8.242            2.345
2.670, 8.713            3.002
2.756, 8.563            2.094
2.899, 8.413.102, 8.523         2.984
3.464, 8.196            2.398
3.705, 8.437            2.745
3.435, 8.558            2.789
3.446, 8.592            2.543
3.421, 8.075            2.984
3.504, 8.153.772, 8.770         2.183
3.705, 8.552            2.784
3.653, 8.443            2.567
3.908, 7.971            2.098
5.020, 8.581            2.20
3.913, 8.247            2.342
3.762, 8.023.575, 8.345         2.123

The sensor readings after every few lines are distorted. I understand this might has something to do with the serial buffers. How could I rectify this and obtain the desired output?

You should use a method similar to this: https://majenko.co.uk/blog/reading-serial-arduino - expand it to work with multiple line buffers and multiple serial ports.

Your serial buffers and moving in and out of phase, which is distorting your display.
Try something like:
void setup() {
  String sensor1;
  String sensor2;
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    sensor1 = Serial1.readStringUntil('\n'));
  }

  if (Serial2.available()) {
    sensor2 = Serial2.readStringUntil('\n'));
  }

  Serial.print(sensor1);
  Serial.print(sensor2);
  Serial.println();
  delay(1000);
}

I would also recommend the method suggested by @Majenko in his comment below your question.


text:
Gsm Sim800l Module
I am using below code for send sms but SMS Sent sucessfully but save in SIM memory & not able to see message text :
serialSIM800.write(“AT+CMGF=1\r”); //sending SMS in text mode
delay(1000);
serialSIM800.write(“AT+CMGS=“9827927887”\r”);
delay(1000);
serialSIM800.write(“Emergency at IIST\r”); // message
delay(1000);
serialSIM800.write(0x1A);
delay(1000);
Serial.println(“SMS sent successfully”);

Please help.

Set SMS Text Mode Parameters AT+CSMP to AT+CSMP=17,167,0,0
This setting  is resolve your issue.

Could you edit your answer and add an explanation as to why this solution works?

After few minutes of using Google, I found a library that contains everything you need to send/receive SMS and phone call. Here's the code I made in two minutes.
Currently I don't have SIM800L module, so I can't test it. Be sure you type a valid number format. For Croatia it's +385 XX XXX XXXX. +385 is an "international dialling code" for Croatia. Don't forget to put + before IDC.
serialSIM800.write("AT+CMGF=1\r");
serialSIM800.write("AT+CMGS=\"");
serialSIM800.write("PHONE_NUMBER");
serialSIM800.write("\"\r");
serialSIM800.write("Emergency at IIST");
serialSIM800.write("\r0x1A");

Thank you for the reply but my actual problem is i am from india and in my sim800l module the same network operator different sim card some are able to send proper message and i am able to receive it but some of them are not able to send the message and are sending the blank message to sim memory.


text:
Triggering an SPI transfer with an interrupt in Arduino Due
I have a DDS that is controlled by an Arduino DUE,  loop() waits for Serial commands and based on them calls one or another function that sets the DDS's frequency, phase, amplitude etc via SPI. In addition to that I want to be able to use an external interrupt triggered by a TTL signal to reset the DDS's phase accumulator. The phase reset is done by writing an SPI register - resetPhase().
Somehow the resetPhase() is triggered correctly, but as soon as I add a SPI.transfer to it the SPI communication stops working altogether, not just through interrupts, but also the functions triggered via serial commands stop working.
Is there a way to get it to work?
SPISettings spiSettings = SPISettings(10000000, MSBFIRST, SPI_MODE0);

void setup()
{
    pinmode(chipSelect, OUTPUT);
    int syncPIN = digitalPinToInterrupt( interruptPin);
    SPI.usingInterrupt(syncPIN);
    attachInterrupt(syncPIN, resetPhase, RISING);
}

void resetPhase():
{
    SPI.beginTransaction(spiSettings);
    digitalWrite(chipSelect, LOW);
    SPI.transfer(controlRegister);
    digitalWrite(chipSelect, HIGH);
    SPI.endTransaction();
}

Probably SPI transfers use an interrupt, which can't trigger because you're already in an interrupt.  You should have the SPI operations outside the interrupt and just update some variables and set a flag in your interrupt.

I am not familiar with the internal workings of the Due SPI library to be sure though.  Best to be safe and not do SPI in an interrupt regardless.

@Majenko I thought that the SPI.usingInterrupt is specifically for that purpose// If SPI is used from within an interrupt, this function registers  // that interrupt with the SPI library, so beginTransaction() can  // prevent conflicts.  The input interruptNumber is the number used  // with attachInterrupt.  If SPI is used from a different interrupt  // (eg, a timer), interruptNumber should be 255.  static void usingInterrupt(uint8_t interruptNumber);

In general, it's best to do as little as possible in your interrupt service routine (ISR).
resetPhase is your ISR here, and typically it would set a flag or semaphore to signal lower priority code that certain work needs to be done and, in this case, probably nothing more. Then your loop code on noticing the flag is set would clear the flag and do its work.
I imagine the library authors thought SPI.usingInterrupt would ease use of SPI, but performing I/O in an ISR seems a bit contrary to best practices. These concerns are echoed here, along with some other caveats regarding interrupts and ISRs. Possibly not the answer you're looking for, but I hope it helps.


text:
Send data to a pc localhost with ESP-01 wifi module
i use a linux machine with a localhost php server installed. Wifi machine is connected to the ESP-01 module (access point mode) and i can send several datas to the Arduino via the ESP-01 set as:
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

The php server can send data by GET method and Arduino receives pin=11:
 http://192.168.4.1:80/?pin=11

But, now, i would like to send to the php server datas from the Arduino. I tried this configuration but in my sketch but, it returns, error.
sendData("AT+CIPSTART=0,'TCP','http://localhost',80\r\n",1000,DEBUG);

Serial monitor:
   ERROR
   AT+CIPSTART=0,'TCP','http://localhost/test_php',80

   Link type ERROR

So please, how can i send and receive data with my ESP-01 module?

"localhost" is a name associated with the loopback interface of your computer. That is, 127.0.0.1.
It is not the address of your computer on the network. The only computer that can talk to "localhost" is the computer itself.
Instead of "localhost" you must use the IP address of your computer (or a FQDN that resolves to the IP address of your computer).
And you cannot open a TCP connection to a URL.  You open a TCP connection to an IP or FQDN.
You really should learn the basics of IP networks before trying to write software for them.

Since your PC can communicate with the ESP8266 on 192.168.4.1 I assume that you are running the ESP8266 in SOFTAP mode and you have a WiFi interface connected to that access point. If so that WiFi interface will have a 192.168.4.x address assigned to it.  That is the address you must open with a TCP connection on port 80 to connect to your apache server.
For example:
sendData("AT+CIPSTART=0,'TCP','192.168.4.3',80\r\n",1000,DEBUG);

Then you can craft a suitable HTTP request to send the data.

i replaced localhot by 127.0.0.1. Terminal returns same error Link type

I said not localhost.

And you deleted the protocol.

ERROR
AT+CIPSTART=0,'TCP','127.0.0.1/test_php',80
Link type ERROR

Do you read? I said do NOT use the localhost address. Use the IP address of your computer on the network. And put back in the protocol that you deleted.

Although you are using raw TCP commands to try and acess a URL. YOu want only an IP address in there. And not 127.0.0.1

Learn the basics of networking before you try working with networks.

Sorry, but i'm a beginner with arduino and i try to understand how it works with ESP-01 and distant php server. The ESP is not linked to my house network and i don't want it as. i need more help...

If your PC can communicate with the ESP8266 then there must be some form of network between them.

Yes, pc can send, but how can arduino do the same to the pc?

By opening a connection to the IP address of your PC.

Open command prompt and type ipconfig
Under IPv4 Address you can see IP or your PC.
That IP address is address of localhost(because your PC is a "server" within your local/home network).
Don't forget to config XAMP/WAMP to listen special addresses. And of course if you want use localhost, your PC must be on.

Yes, pc can send, but how can arduino do the same to the pc

Yes, it can. PC(localhost) is server and Arduino is client, like Stackexchange is host and your PC is a client (to Stackexchange). I hope you get it
 The ESP is not linked to my house network and i don't want it as

You can use public server, but you need to Know IP address of the server.

he connects to esp8266 as AP. so not the address on home network, but the address on WiFi interface connected to esp8266


text:
LED brightness and Arduino ports
Hi I am learning Arduino. Pin 13 lights the LED's very brightly. With subsequent LED's on other ports the LED's are much less bright than the one on 13.
Anyone know what is going on?
regards

Wiring? Code? We're not psychic, you know...

my guess is the you are using two different kinds of LEDs ..... no other guesses are possible because you provided zero information

I used the example program in Uno called Blink.

You probably have cheap crappy inefficient leds on the other pins. Or you have the wrong value resistor in series with them. If they are not from the same batch, with the same resistor, you can't really complain. Maybe they are for a higher voltage. (because of the resistor value)
Are you sure you set the port pins for output?
pinMode(Output_PIN, OUTPUT);

I used this basic code then cut and pasted it and added two more pins 12 and 11. The LED's all came in a starter kit so I assume they are the same.
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);

The leds in the starter kit are probably a different size compared to the led on the board. Probably through hole parts, so they are not the same as what was used on the board.  Can you provide a link to the kit you bought?

Haven't got supplier details for my kit. Can you recommend a good starter kit and supplier details.


text:
esp8266 WiFi Cannot Connect to a PHP Server
I am using a magnetic float switch sensor to monitor water level in a tank. I am using a ESP8266 board.
I am trying to send the data collected by it to a php page in a host called "weris.link". I've checked the WiFi ssid and password for a myriad of times, yet somehow the connection to server still failed.
Did i commit a mistake ?
Here's my code :
#include <ESP8266WiFi.h>
#define FLOAT_SENSOR  D2     // the number of the pushbutton pin
#define LED           D8      // the number of the LED pin

const char* server = "weris.link"; // alamat server
const char* ssid = "aBee"; // SSID router wifi
const char* password = "xxxxx"; // password wifi
const char* SensorID = "Water_Level_Kelompok_1.Unsrat"; // ID sensor

const char* count1= "Water Tank Full";
const char* count2= "Water Level Low";
const char* recommend1= "Turn Off Flow";
const char* recommend2= "Turn on Flow";

WiFiClient client;

void setup()
{
  Serial.begin(115200);
  // initialize the LED pin as an output:
  pinMode(LED, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(FLOAT_SENSOR, INPUT_PULLUP);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
  }

void loop()
{
  if(digitalRead(FLOAT_SENSOR) == LOW)
  {
    // turn LED on:
    digitalWrite(LED, HIGH);
    Serial.println(count1);
  }
  else
  {
    // turn LED off:
    digitalWrite(LED, LOW);
    Serial.println(count2);
  }
  // mulai Kirim data sensor
   if (client.connect(server,80 && LED == HIGH)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Tank Full: " + String(count1) + ", Tank Level Below Normal: " + String(count2));

// dengan GET /path file php penangkap data
client.println("GET /iot/terima.php?data1=" + String(count1) + "&data2=" + String(recommend1) + "&sid=" +SensorID+ " HTTP/1.1");
client.println("HOST: weris.link");
client.println("Connection: close");
client.println();
client.stop();
Serial.println();
digitalWrite(BUILTIN_LED, HIGH);
}

else if(client.connect(server,80 && LED == LOW)) {
  client.println("GET /iot/terima.php?data1=" + String(count2) + "&data2=" + String(recommend2) + "&sid=" +SensorID+ " HTTP/1.1");
  client.println("HOST: weris.link");
  client.println("Connection: close");
  client.println();
  client.stop();
  Serial.println();
  digitalWrite(BUILTIN_LED, HIGH);
 }
  else {
Serial.println("Koneksi ke server gagal");
 }
  delay(5000);
}

Below is the screen capture from the serial monitor

This line:
if (client.connect(server,80 && LED == HIGH)) {

is definitely not going to do anything useful. Nor is this line:
else if(client.connect(server,80 && LED == LOW)) {

In both lines you're take the logical AND of the number 80 and the result of testing the LED.
Put the closing parenthesis in correct place:
if (client.connect(server,80) && LED == HIGH) {

and
else if(client.connect(server,80) && LED == LOW) {

Written this way you're still connecting twice if the LED is LOW. The code would be better written:
if (client.connect(server,80)) {
    if(LED == HIGH) {
      do stuff
    } else {
      do other stuff
    }
}

Even better would be to have the do stuff and do other stuff sections just set some variables and then write the code to talk to the web server once, using those variables. Having a single instance of the code will help avoid bugs in the future if you ever need to change it - the DRY (Don't Repeat Yourself) principle of programming.
Also, I hope you didn't just publish your wifi password here. If you did, you should change it.

LED is a pin number not a pin state.

good point! I'm sure that @Kenneth W. A. can take it as an exercise for the reader to correct that part of his code :)

Thank you very much, i really appreciate the help, restructured my code, it's working now


text:
The Capacitive Sensor library on a D1 Mini
I want to set up a hand-made capacitive sensor on a D1 Mini, as in this tutorial, so that I can get specific capacitive readings. But I couldn't get the CapacitiveSensor library to work with the D1 Mini. Just to make sure I wasn't crazy, I fired up an Arduino Nano knockoff, and the library worked just fine.
I found a thread from early 2017 on this topic, which had various suggestions, none of which worked.
Does anyone know either how to make this library work with a D1 Mini, or another efficient way of getting capacitive readings on digital pins on a D1 Mini?

which pins are you using?

I've tried every combo I could think of. I know to avoid D0 / D3 / D4 / D8 (but tried them anyway).

Actually it looks like the answer was in the early 2017 thread all along. I switched to a 400k resistor and it works! (I've only verified this just for pins 5 -> 6, although I'd expect it works for any combination of pins not including D0 / D3 / D4 / D8.)
However, a caveat here -- it doesn't work well. With an Arduino and a ~6m resistor, you can sense a change in capacitance from several inches away, with a nice continuous increase in capacitance as you get closer. At least for me, the 400k resistor had very low operational range, only maybe 1/2 in. or so, and even then the differences were subtle. But increasing to a 600k resistor replicated the initial problem -- I just got the "-2" error message consistently. And going down to a 200k resistor just decreased the range as you'd expect. So there seems to be a very narrow operational range of resistance for the D1 Mini, with less utility than the Arduino.


text:
Actuating a Hobbywing Skywalker 50A-UBEC ESC with Arduino CNC Shield
I need to control a brushless motor that came connected to this ESC using the Arduino CNC Shield V3.00 and Grbl 0.9j.
I connected the ESC's black wire to a GND from the shield and the ESC's white wire to the shield's Z+ limit (end stop).
I then tested by connecting everything but leaving the ESC unpowered, sending several M3 S*commands, where 0 <= * <= 1000, then powering the ESC, but nothing happened.

very interesting post, but unfortunately working only for ATMEGA2560: reference line: #ifdef CPU_MAP_ATMEGA2560 any suggestion to make it possible also for ATMEGA328 chip? it would be really helpful for the most of Arduino UNO+GRBL Shield owner. TKS

After a lot of research, I found out that the variable spindle speed output is a PWM signal, while the ESC needs a PPM signal to be controlled. Although that, it's a specific PPM signal that actually looks like PWM, so it can be used.
The problem is that, instead of being controlled by the duty cycle, what actually controls it is the amount of time that each pulse stays on high, which depends on the period, which is the inverse of the frequency. Long story short, the frequency is too high.
I managed to change the frequency used by grbl and found one that works. I don't know if this frequency allows the whole throttle range to be controlled but, for my application that doesn't require a very strict RPM, it was enough. Here are the steps (some steps are already explained elsewhere):

Import grbl's library in Arduino IDE.
Find out where the library got installed and edit grbl/spindle_control.c, lines 89 and 94.
Change 0x02 to 0x05. Save and close the file.
Compile and download the library to Arduino Uno.
Connect everything but leave the ESC unpowered.
Send M3 S0 (that's a zero).
Power the ESC.
You should hear a 123 tone (three beeps of different frequencies). It will then continue to beep once from time to time — I have no idea why... It should have stopped after a few.
Send S600. It should start spinning. If it doesn't, first send lower values from 0 to 600.
Send S500 to stop.


text:
ESP8266 feather huzzah wiring for MFRC522
I'm trying to wire the mfrc522 and the huzzah but i can't seem to figure out the rst pin.
I found the pin out diagram but it doesn't show or idk how its labeled as.

use Wemos table from your link. here is the mapping to esp8266 io pins
RST/Reset   D3 = io 0
SPI SS      D8 = io 15
SPI MOSI    D7 = io 13
SPI MISO    D6 = io 12
SPI SCK     D5 = io 14

If you want, you can use any pin for SS and reset. See the examples.
#define SS_PIN 4
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);

@xiao-ning-er, did it help?

Use GPIO0 (D3 on the Wemos).  The reset signal is under program control in the library and isn't the same as the ESP8266 reset input.


text:
How to use php file_get_contents with ESP8266
A part of my project need to get datas from an ESP8266 with php script. I tested this script and i don't know why i can get the datas in an iframe element and nothing with file_get_content function. In iframe element my browser displayes "Hello my friend!" as wanted:
The ESP8266 server mode at 192.168.4.1 address, part of code:
String webpage = "
Hello
";
webpage += "
my
";
webpage += "
friend!
";

String cipSend = "AT+CIPSEND=";
cipSend += 0;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";

sendData(cipSend,1000,DEBUG);
sendData(webpage,1000,DEBUG);
sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);

The php script:

 <?php

 $url="http://192.168.4.1/?cmd=SS,0,0,";
 $lines_string = file_get_contents($url);
 echo htmlspecialchars($lines_string);

?>

If i replace the url by:
$url=https://arduino.stackexchange.com

It works with php script,so what is the issue with the ESP8266 ?

Where does the PHP run? I think your PHP is running on a remote server, while the ESP is on a local network (behind a NAT), with a local IP address. The remote server can't access your local network, while you browser can.

Php script is running on php home server Linux machine. I can send all i want to the ESP8266 by wifi.

Is your home server on the same network (/subnet)? Can you curl/gwet the url from your home server?

No home network. Just php server (localhost) and ESP8266 as access point.

To process the request by php, you must send valid HTTP response. The browser tolerates too much.
String webpage = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
webpage += "
Hello
";

PERFECT !!! I can get "Hello" with

file_get_contents("http://192.168.4.1/?cmd=SS,0,0,");


text:
Is arduino a single board computer?
First excuse me if tags are not reflecting the content,
While watching a video about single board computer (SBC) I got confused that it doesn't mention arduino as SBC. I always considered it as SBC.
After digging around a bit I got more confused. It seems single board computer is where processor, memory, I/O this things are built on single circuit board rather than using expansion card attached on to a circuit board (motherboard).
According to that is not arduino a SBC? It's processor, memory,storage are on single ATMega32A (for uno) attached on a single board which provides some I/O port (I/O pin, USB, UART, I2C etc.).
From some digging I learned that arduino code runs on bare metal unlike SBC like Rpi and that's the reason for it not being SBC. This seems weird reason.
(1) Is Arduino a SBC?
If (1) is no then next questions are,
(2) Is Being less powerful is the cause? If yes where do you draw the line?
(3) Not having an OS hosted environment for execution is the cause?
If (3) is Yes then,
(4) Arduino has some bootloader code to load the program through USB. Isn't it  kinda like OS, I admit it's not giving some nice api for h/w usage but is it all?
This link comment section kind of started a debate but ended without giving clear answer about my question.

It may be impossible to draw a sharp line that separates single board
computers from microcontroller boards. There are, however, several
attributes that can help differentiate them and, in a sense, draw a
blurry line. If a specific board has most of the attributes of SBCs it's
probably safe to call it an SBC. Same for MCU boards.
Processing power may be one of those attributes. A typical SBC is many
orders of magnitude more powerful than your typical Arduino. A Raspberry
Pi, for example, has half a million times the RAM of an Arduino Uno.
Although you can find microcontrollers that are a thousand times more
powerful than the Uno, you are unlikely to find many SBCs that are one
hundred times less powerful than a Raspberry Pi.
The operating system may also be a factor. SBCs are typically meant to
run mainstream OSes: some flavor of Linux, Windows or Android.
Microcontrollers, on the other hand, will most often run some kind of
RTOS (real-time OS) specifically designed for the embedded world, if
they do run an OS at all.
A factor that has not been mentioned yet is the I/O capabilities. On an
SBC, you will typically find the kind of I/O ports that are common on
desktop or laptop computers, like HDMI, USB host or Ethernet. A
microcontroller, on the other hand, is more likely to have analog inputs
or outputs, as these are more useful in the “electronics” world than in
the “computer” world. Of course, the lines are blurry: you may find SPI,
I2C and GPIOs on both SBCs and MCUs.
Neither of those factors may be enough to tell an SBC apart from a MCU
board. But taken together, they can allow you to say that board A is
clearly an SBC, board B is clearly an MCU board, and board C is
somewhere in between and hard to classify.

The Arduino isn't a computer. It is a programmable microprocessor / microcontroller.
Generally a computer can run multiple applications where most programmed devices like the Arduino are running only one program. This is not an official definition but it is one way to differentiate.
It can be difficult to draw a line where it is one but not the other.

(4) Arduino has some bootloader code to load the program through USB.
  Isn't it kinda like OS, I admit it's not giving some nice api for h/w
  usage but is it all?

No that isn't like an operating system. The Arduino does not have a real operating system when compared to a computer system. And someone being able to load in a new program is just changing the current single program that is runnable.

An operating system (OS) is system software that manages computer
  hardware and software resources and provides common services for
computer programs.

I think the programs being plural is an important factor, but this is only my opinion.
There is no one definition so you will get a number of different opinions. And most will be reasonable.

It all depends on your definition of "computer".  From the point of view that the Arduino is a "Turing complete" architecture, with CPU, memory, storage, IO, etc, then yes, it is a computer. But it's not a "computer" as in what you have on your desk.
Is a mobile phone a "computer"?
We can shift the definition elsewhere if you like:
In general an SBC is taken to be a SoC mounted on a board with the support components.  A SoC is a "System on Chip".  But now we just move the definition to "What is a SoC?" - a question that has been asked many times before.
There is no one specific thing that divides a SoC from a Microcontroller. For instance:

"A SoC runs an operating system, but a Microcontroller doesn't" - except that there are microcontrollers that can and do run operating systems, and you don't have to run an operating system on a SoC.
"A SoC relies on external memory, but Microcontrollers have it built in" - except that there are SoCs with built in memory, and Microcontrollers than need external memory to function

The list goes on.
My definition of what constitutes a "computer" as opposed to an "embedded system" has nothing to do with what the device is, it's what you do with it.
If the board is being used with a keyboard, mouse, screen, etc for generic operation then it's a computer. If it's being programmed for one specific task then it's an embedded system.  The same hardware could be used in both ways, and I would call it a computer if it were running "general" software (operating system, web browser, server software, etc), but I'd call it an "embedded system" if it were running one program only (with or without an OS) gathering data, reporting it back to a central system, etc.
For something to be termed a "Single Board Computer" I would say it has to be capable of running general software designed to run on a "traditional" computer.  Things like Linux with Apache etc, or a desktop environment.
Mind, this is only my opinion, and as such it will differ from other peoples' opinions.


text:
Is it possible to simultaneously acquire 2 values from the Arduino?
I am currently making a project using a resistive touch screen and an Arduino Uno. The resistive touch screen outputs an X and Y coordinate pair, which I then want to be able to read and output on an X-Y scatter plot in Visual Basic. I am wondering if it's possible to collect these X and Y coordinates at the same time, and read them through the serial port so they can be used in Visual Basic.

no you cannot collect the X and Y coordinates simultaneously ..... those two values would be collected one after the other, some microseconds apart

Since this is a Arduino forum I will answer the Arduino part of your question. Yes you can get the coordinates and get them into the computer via a serial port.


text:
Conflict between SD card shield and accelerometer
I'm trying to get the SD card (Adafruit microshield SD card) and an MPU6050 accelerometer to work at the same time. When I connect the SD card to the Arduino (without the accelerometer), it's ok; When I connect the accelerometer to the Arduino (without the SD card), it's also ok. The codes for the accelerometer and SD card work fine separately. But when I connect the shield to the Arduino, and then connect the accelerometer, and try to run a combined code, it's problematic. I've included the code I'm currently working on below.  I would really appreciate if you could help me find where the problem lies, and how to solve it.
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
//#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
//    #include "Wire.h"
//#endif

// A simple data logger for the Arduino analog pins

// how many milliseconds between grabbing data and logging it. 1000 ms is once a second
#define LOG_INTERVAL  1000 // mills between entries (reduce to take more/faster data)

// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// the digital pins that connect to the LEDs
#define redLEDpin 4
#define greenLEDpin 3

// The analog pins that connect to the sensors
//(not sure which pins on the accelerometer are the analog pins that connect to the sensor. Insert here!!)

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
#define OUTPUT_READABLE_YAWPITCHROLL
//#define OUTPUT_READABLE_QUATERNION
//#define OUTPUT_READABLE_EULER
//#define OUTPUT_READABLE_REALACCEL
//#define OUTPUT_READABLE_WORLDACCEL

RTC_DS1307 RTC; // define the Real Time Clock object

// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = HIGH;

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while(1);
}

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

  // use debugging LEDs
  pinMode(redLEDpin, OUTPUT);
  pinMode(greenLEDpin, OUTPUT);

#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START

  // initialize the SD card
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    error("Card failed, or not present");
  }
  Serial.println("card initialized.");

  // create a new file
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile = SD.open(filename, FILE_WRITE);
      break;  // leave the loop!
    }
  }

  if (! logfile) {
    error("couldnt create file");
  }

  Serial.print("Logging to: ");
  Serial.println(filename);

  // connect to RTC
  Wire.begin();
  if (!RTC.begin()) {
    logfile.println("RTC failed");
#if ECHO_TO_SERIAL
    Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  logfile.println("Hello,World,!!!");
#if ECHO_TO_SERIAL
  Serial.println("Hello,World,!!!");
#endif //ECHO_TO_SERIAL

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL);
}

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}
 #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(9600);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately
 // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}

void loop(void){

 if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }

  DateTime now;

  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

  digitalWrite(greenLEDpin, HIGH);

  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m);           // milliseconds since start
  logfile.print(", ");
#if ECHO_TO_SERIAL
  Serial.print(m);         // milliseconds since start
  Serial.print(", ");
#endif

  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
  logfile.print('"');
#if ECHO_TO_SERIAL
  Serial.print(now.unixtime()); // seconds since 1/1/1970
  Serial.print(", ");
  Serial.print('"');
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
  Serial.print('"');
#endif //ECHO_TO_SERIAL

  analogRead(photocellPin);
  delay(10);
  int photocellReading = analogRead(photocellPin);

  analogRead(tempPin);
  delay(10);
  int tempReading = analogRead(tempPin);

  logfile.print(", ");
  logfile.print(photocellReading);
  logfile.print(", ");
  logfile.print(temperatureF);
#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(photocellReading);
  Serial.print(", ");
  Serial.print(temperatureF);
#endif //ECHO_TO_SERIAL

}

// reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        fifoCount = mpu.getFIFOCount();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

  logfile.println();
#if ECHO_TO_SERIAL
  Serial.println();
#endif // ECHO_TO_SERIAL

  digitalWrite(greenLEDpin, LOW);

  // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
  // which uses a bunch of power and takes time
  if ((millis() - syncTime) < SYNC_INTERVAL) return;
  syncTime = millis();

  // blink LED to show we are syncing data to the card & updating FAT!
  digitalWrite(redLEDpin, HIGH);
  logfile.flush();
  digitalWrite(redLEDpin, LOW);

}

const int chipSelect = HIGH; HIGH is 1. you can't use pin 1 for this

you have not fully described what is happening ..... what happens if you connect both the modules and run the two separate codes?

Are both devices connecting via the SPI bus?

Based on the information that you've provided, it's quite likely that your problem  lies with how your SD card and accelerometer connect via the SPI bus.
The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.  The 'datasheet'/tutorial for the Micro SD Card Breakout Board (which is the device that I assume you mean when you say Adafruit microshield SD card), has the following schematic:

Which doesn't appear to include a tri-state buffer.
I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer (in that case, I used a 74HC125 4-channel tri-state buffer) in the MISO line for each of the SPI devices.

This page on Better SPI Bus Design in 3 steps is what finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).


text:
How to use -F option while Burn bootloader for ATtiny 85 using Arduino IDE
I'm very new to Arduino. I tried programming Attiny 85 module using Arduino as ISP. It worked fine few times. after that i'm getting below error.
Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

I understand that i can override this step using -F option. But really cannot figure out how to use -F option in Arduino IDE. Please Help!

don't use -F. solve the problem with wiring

i tried checking and changing jumpers multiple times. no luck.

For what I know there is no easy way to pass custom options to avrdude via the Arduino IDE, but Sloeber (to which I'm a contributor) does.
Beware though, the -F option of avrdude command doesn't solve the problem, just forces to skip the device signature verification, but if your Attiny is returning such signature something else is wrong and you'll end up with a failed firmware upload anyway.
If the device was working and suddenly stopped it's more than probably a wiring issue, as already suggested in the comments. The second most probable cause, in my experience, would be a hardware issue: you might have accumulated some static charge and then touched the Attiny or any wire connected to it, destroying one of the ISP pins...
My bet is on the former: my experience with the latter is you get changing signatures in the form of 0xFFFF00, 0x0000FF and 0xFFFFFF but, luckily for me, this didn't occur so often to accumulate a true knowledge.

Are you aware the Sloeber site is down (3pm EST 2018-12-28). There’s also a bad cert on the site


text:
How to / is it possible to change Vendor Name in ESP8266-12E?
I am aware of that it is possible to change hostname for ESP8266 but I want to change vendor name also so that it lists my company/product name in routers/firewalls.
Is it possible?

No. The Vendor Name is associated with the OUI.  The OUI is the first three parts of the MAC address.
The OUI's are all registered with IEEE here and Espressif's entries are:
18-FE-34   (hex)        Espressif Inc.
24-0A-C4   (hex)        Espressif Inc.
24-B2-DE   (hex)        Espressif Inc.
2C-3A-E8   (hex)        Espressif Inc.
30-AE-A4   (hex)        Espressif Inc.
3C-71-BF   (hex)        Espressif Inc.
54-5A-A6   (hex)        Espressif Inc.
5C-CF-7F   (hex)        Espressif Inc.
60-01-94   (hex)        Espressif Inc.
68-C6-3A   (hex)        Espressif Inc.
80-7D-3A   (hex)        Espressif Inc.
84-0D-8E   (hex)        Espressif Inc.
84-F3-EB   (hex)        Espressif Inc.
90-97-D5   (hex)        Espressif Inc.
A0-20-A6   (hex)        Espressif Inc.
A4-7B-9D   (hex)        Espressif Inc.
AC-D0-74   (hex)        Espressif Inc.
B4-E6-2D   (hex)        Espressif Inc.
BC-DD-C2   (hex)        Espressif Inc.
C4-4F-33   (hex)        Espressif Inc.
CC-50-E3   (hex)        Espressif Inc.
D8-A0-1D   (hex)        Espressif Inc.
DC-4F-22   (hex)        Espressif Inc.
EC-FA-BC   (hex)        Espressif Inc.

The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in /usr/share/ieee-data) and uses them to create a pretty display.
You would need to

Change the ESP8266's MAC address somehow
Subscribe to IEEE and pay the relevant fees
Be allocated an OUI
Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do).

You can change the MAC address in software, using wifi_set_macaddr(). Then you have the problem of storing that address in EEPROM and making sure every piece of code that you write for your product knows how to access it. You also need to add a step in your product release process that figures out what to store, and stores it, or you need to burn a different image in each unit that you sell. Plus you need to keep track of all the mac addresses you've ever issued so you don't issue duplicate ones. Plus, as @Majenko said, you would need to register your own OUI, which costs a few thousand dollars. So unless you plan to sell tens of thousand of your units, it's not worth doing.


text:
How to connect ESP8266-01 (AT-commands) to its web server using AJAX
I am just new on using AJAX in web server, I got an error on declaring "server" I am confused about this because I just used only a AT commands to used the ESP8266-01 (wifi-module) I hope you can help me, I want to get the data (distance) to print in the web server(page) in real-time(no refresh). So I used the AJAX for it but this code is still error. Advance thanks on anyhelp :)
 #include "NewPing.h"
 #include <SoftwareSerial.h>
 #define DEBUG true

 SoftwareSerial esp8266(10,11);
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.begin(9600);

 server.on("/",WebsiteContent);
 server.on("/xml",XMLcontent);
 server.begin();

 pinMode(TRIGGER_PIN, OUTPUT);
 pinMode(ECHO_PIN, INPUT);

 sendData("AT+RST\r\n",2000,DEBUG);
 sendData("AT+CWMODE=2\r\n",1000,DEBUG);
 sendData("AT+CIFSR\r\n",1000,DEBUG);
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

}

void javascriptContent(){
Javascript ="\n";

}
void WebsiteContent(){
javascriptContent();

 Website="\n";
 Website+="\n";
 Website+="";
 Website+="
"+data+"
";
 Website+=Javascript;
 server.send(200,"text/html",Website);
 }
 void XMLcontent(){

 XML ="<?xml version='1.0'?>";
 XML+="<data>";
 XML+=data;
 XML+="</data>";

 server.send(200,"text/xml",XML);

 }
 void loop()
 {

 delay(2000);
 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

 long duration,distance;
 duration= pulseIn(ECHO_PIN,HIGH);

 distance = duration/58.2;

 data=(String)distance;
 delay(500);

 server.handleClient();

 if(esp8266.available())
 {
 if(esp8266.find("+IPD,"))
 {
 delay(1000);
 int connectionId = esp8266.read()-48;

 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);

}
}
}
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
return response;
}

Do you actually have a question? And is it related to Arduino, and not Javascript or HTML?

I already edited it sir :) sir do you have any idea about it?

Looks like you're confusing ESP8266 native code for Arduino code.

try to add a include ESP8266WebServer server(80);

@abu-ahmedal-khatiri I also add that earlier but still error

i cannot see on your code. you need to make a index.h to store data on AJAX see my header and include it to your sketch see my sketch

@Majenko I used AT commands because when I program ESP8266 (directly) it's not working and always got error about it, so I switch on AT commands.

like a mentioned @Majenko answered "To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available." ,why you need AT Commands if you can store data to AJAX script directly?

ah so your example @abu-ahmedal-khatiri will work sir?

@abu-ahmedal-khatiri can you help me here sir? https://chat.stackexchange.com/rooms/85432/discussion-on-question-by-xiaomy-arduino-uno-with-esp8266-01-with-at

anyone can help me about this ESP8266WebServer server(80); is error because I am using AT commands? because once I delete it the "server" methods are error too. Is there any alternatives here?

as mentioned in your question "I want to get the data (distance) to print in the web server(page) in real-time(no refresh)". I THINK you will display data to Web Page and MY ajaxcreated.h will works!. if you're using APP INVENTOR, the AJAX will not work!

You're trying to mix code that is intended to run directly on an ESP8266 using ESP8266-specific libraries on an Arduino.  It can't ever work.
Likes like:
server.on("/",WebsiteContent);
server.on("/xml",XMLcontent);
server.begin();

are for use with the ESP8266's ESP8266WebServer library which doesn't run on an Arduino. To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available.
So, either:

Do it all with AT commands only, or
Ditch the Arduino and program the ESP8266 directly instead.

can you send me a link about that in AT commands?

You already use them in your code.

I thought there will be for AJAX or what

can you help me sir?

Do you know what the AT commands that you have in your sketch actually do?

it is for me to use it as alternative for coding esp8266 directly

Yes, but do you know what they do? What do they mean?

Delete all the server and such rubbish that you randomly added, and then work out how you can use what the ESP8266 sends you when you request a web page to decide what you should be sending and when you should be sending it.


text:
Teensy 2.0 usb xinput device
So I came across a library that lets you turn your TeensyLC/3.X into an xinput device. I only have a 2.0 on hand. I spend the past few hours messing around with the LC example to see if I could hack it over to work on a 2.0 board. Admittedly, it will take much more time analyzing everything before I can make a more educated attempt. I saw another project that is able to use the 2.0 as xinput devices but the firmware is only available in its hex form.
So I'm wondering what would be the best way to go here... all of the xinput code is in the /core/teensy3 directory. It has many spidering dependencies which will take a lot of time to go through and try and port(would that even work?). Is there a super "lite" version of the core that lets you fill out device descriptors/handshake/etc? If there is, the xinput just becomes a task of emulating the xinput packets.
Anyway, as this is my first usb input project, any suggestions would be greatly appreciated. Again, I already have the 2.0 and I know its possible so just getting a LC/3.X I'd like to avoid. I'm more just looking for direction on the best way to get started.

Teensy 2.0 has 8-bit Atmega 328p MCU. It doesn't have native USB port.
Teensy LC is a small Teensy 3.x. It has a 32 bit SAMD MCU with native USB port.

@Juraj the Teensy 2.0 has a Mega32u4 which does support native usb.

then it is like Arduino Micro. https://github.com/bootsector/XInputPadMicro

google GIMX firmware source and you will get this https://github.com/matlo/GIMX-firmwares/releases

The Teensy 2.0 is a completely different MCU from the 3.0 with very different libraries.
USB on the 32U4 on the 2.0 typically uses the LUFA library for USB.
So to answer your question: I doubt it will be possible to port code written for the 3.0 SAMD based teensy to the AVR based 2.0 teensy without basically rewriting it from scratch.
The Arduino Leonardo also uses a 32U4 so you might want to look for examples code written for the Leonardo.
The examples from the LUFA library may be useful but they are not designed to be used with the Arduino IDE.
UPDATE From the comments, there is this project:
https://github.com/bootsector/XInputPadMicro that uses LUFA and targets the Leonardo.