text:
Make WiFi Router Using Arduino board
void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post). The fourth and the fifth posts also works fine but the sixth is same as the third. Knowing

no "Connection: close" and client.stop()?

PS Host shouldn't contain the port number. That is; client.println("Host: 192.168.2.116:8040"); should be client.println("Host: 192.168.2.116");


text:
Saving a value with a click
I have a rotary encoder and 2 buttons to a. Store the encoder value b. Reset the encoder value to 0. The reset buttons work fine the issue is with the set/store button. Where the value changes without pressing the button as well. Any help is appreciated.
int encoderPin1 = 2;
int encoderPin2 = 3;

volatile int lastEncoded = 0;
volatile double encoderValue = 0;
long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

// buttons
int resetPin = 43;
int settPin = 22;
int val = 0;
int val2 = 0;

//reset-set
double setValue = 0.0;
double resetValue = 0.0;

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

  pinMode(encoderPin1, INPUT);
  pinMode(encoderPin2, INPUT);

  digitalWrite(encoderPin1, HIGH);
  digitalWrite(encoderPin2, HIGH);

  attachInterrupt(0, updateEncoder, CHANGE);
  attachInterrupt(1, updateEncoder, CHANGE);

  //buttons
  pinMode(resetPin, INPUT);
  pinMode(settPin, INPUT);

  pinMode(LED_BUILTIN, OUTPUT);

}
void loop(){
  //Serial.println(encoderValue); //print
  delay(1000);

  //
val = digitalRead(settPin);
if (val == HIGH){
  set();
  digitalWrite(LED_BUILTIN, HIGH);
}

/*val2 = digitalRead(resetPin);
if (val2 == HIGH){
  //reset
  encoderValue = resetValue;
  Serial.println(encoderValue);
  Serial.print("reset");
  delay(100);
}*/

}

void set(){
  //set the value
  setValue = encoderValue;
  Serial.println(setValue);
  Serial.print("setValue");
  delay(100);
}

 void updateEncoder(){
  int MSB = digitalRead(encoderPin1);
  int LSB = digitalRead(encoderPin2);

  int encoded = (MSB << 1) |LSB;
  int sum = (lastEncoded << 2) | encoded;

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded;
  }

what is the problem with your code?  ... are you getting errors?

Do you use external pulldown resistors?

the encoder does not require an interrupt on both signal pins ... enable an interrupt on raising (or falling)  on one signal pin ... the state of the other pin at the time of the interrupt signifies the direction of rotation

thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!

source: Stack Exchange

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

sort: votes


text:
Make a set LED dimming schedule?
I'm trying to made the LED's go from minimum brightness to maximum brightness and back to minimum in 2.55 seconds.
I really don't know where to begin. I have the following basic code for making it blink simultaneously, but how do I make it cycle through during the time I want:
int led = 10;           //the PWM (tilde) pin the LED is attached to

int led2 = 9;

int led3 = 11;

int brightness = 0;    //how bright the LED is

int delaytime = 25;

int fadeAmount = 5;    //how many points to fade the LED by

//the setup routine runs once you press the reset:

void setup() {

  // declare pins to be an output:

  pinMode (led, OUTPUT);

  pinMode (led2, OUTPUT);

  pinMode (led3, OUTPUT);

}

//the loop routine runs over and over again forever:

void loop() {

  // set the brightness of pin 10:

  analogWrite (led, brightness);

  analogWrite (led2, brightness);

  analogWrite (led3, brightness);

  //change the brightness for next time through the loop:

  brightness = brightness + fadeAmount;

  //reverse the direction of the fading at the ends of the fade:

  if (brightness <= 0 || brightness >= 255) {

    fadeAmount = -fadeAmount;

  }

//wait for set milliseconds to see the dimming effect

delay (delaytime);

}

**bonus: the next part includes making each LED go on its own schedule so the more thoroughly you can explain this first the better I can attempt the next part.
THANK YOU!

You can set the delay and fadeAmount for getting through in 2.55s.  And what do you mean by "on its own schedule"?

So I sort of get the initial delaytime and fadeAmount values based on this reasoning: You set the fade amount and delay to specific values or at least keep the same ratio
FadeAmount/510 = delayTime/TotalTime
5/510=25/2550
510 being the total brightness change from low to high to low again.

But I need my first LED to go from min to max to min brightness in 2.55 seconds, my second to go in 5. 1 sec, and my third in 10.2. How would I be able to set each of them on their own schedule, Like make LED each have its own fadeAmount if I kept the delaytime constant at 25? Does that make sense?

is this a school assignment?  ... the word "bonus" says that it is one

It is a school assignment, though I don't get bonus points for the second part...I just have to do it. Thankfully ya'll explained it well enough for me to do it on my own. thanks!

The way to go is the non-blocking coding style, that can be found in the BlinkWithoutDelay example, that comes with the Arduino IDE. There you use millis() to measure time. You save a timestamp for every LED and in every execution of the void loop() you check, if enough time has passed since the last timestamp. You have to do this for every LED.
Since this coding style has been explained numerous times through the internet and on this site, I will not go more into detail. You can google the rest, understand, how that style works and then transfer that to your case.

Have a look at these instructables...
One does the gradual fading of an led (on and off) via PWM: LED lighting in a staircase.
The second deals with the "there own schedule" bit - which I assume means cycle on and off independently of one another.:  cooperative multitasking.
Disclaimer.. they are my instructables posts, but they do address the question. There are also several libraries available for running "timed tasks" if you prefer an alternative solution.
Here is an practical example that should deal with both aspects of your question (hopefully it will stem the tide of negative feedback)...
It should work on an UNO or any other Arduino with PWM on pins 3, 5 and 6. Of course you are free to adjust the pins to suit your needs (including adding more or taking some out).

int pwmPin[] = {3, 5, 6 };        // Pins that are being used for PWM.
int pwmValue [] = { 0, 0, 0};     // Initial value of PWM duty cycle in the range 0 to 255.
int pwmIncrement[] = {1, 1, 1};   // The value by which the PWM will be incremented at each step.
                                  // NB, this can not be zero but you can start with negative numbers if you wish.
unsigned int pwmDelay[] = { 20, 30, 70 }; // The delay between steps for each PWM.

// To get a good effect select good initial values for the delay, value and increment.
// larger delays mean less frequent changes to the PWM duty cycle.
// larger increments means each adjustment to the PWM duty cycle is larger.
// Set the value at the starting point e.g. 0, for off, 127 for 50% brightness or 255 for 100%.

#define PINS sizeof(pwmValue)
unsigned long pwmNextStepTime[PINS]; // The point in time when the PWM will next be adjusted.

void setup() {
  for (int i = 0; i < PINS; i++) {   // Initialise each pin as:
    pinMode(pwmPin[i], OUTPUT);      // an output.
    pwmNextStepTime[i] = millis() + pwmDelay[i];   // The time when next the duty cycle shoud be adusted.
    analogWrite(pwmPin[i], pwmValue[i]);           // Set the duty cycle of the PWM.
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  for (int i = 0; i < PINS; i++) {    // On each loop, check the PWM pin to see if we need to do anything.
    unsigned long now = millis();     // What is the current "time"?
    if (now > pwmNextStepTime[i]) {   // Has the time passed the adjustment time for PWM pin i?
      pwmNextStepTime[i] = now + pwmDelay[i];  // Yes, calculate the next adjustment time.
      pwmValue [i] += pwmIncrement[i];         // Adjust the duty cycle as per the pin's increment.
      if (pwmValue [i] >= 255) {               // Have we gone too far up?
        pwmValue[i] = 255;                     // Yes, set the maximum value.
        pwmIncrement[i] = -pwmIncrement[i];    // Reverse the increment (so now we count down)
      } else if (pwmValue[i] <= 0) {           // Have we gone too far down?
        pwmValue[i] = 0;                       // Yes, set the minimum value.
        pwmIncrement[i] = -pwmIncrement[i];    // Reverse the increment (so now we count up)
      }
      analogWrite(pwmPin[i], pwmValue[i]);     // Finally, set the duty cycle for the LED.
    }
  }
}

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


text:
How to stop OLED flicker when using SSD1306Ascii.h?
Why does the OLED display flicker when using the SSD1306Ascii.h library? The Adafruit library does not have this issue, but I've been told uses a lot of memory and so I'm trying to use Ascii to conserve memory resources. The problem manifests itself when the void loop() begins. When using similar code with the Adafruit library, the display stays steady as a rock.
Here is my example code. many thanks in advance.
// Edit AVRI2C_FASTMODE in SSD1306Ascii.h to change the default I2C frequency.

#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;
//------------------------------------------------------------------------------
void setup() {

#if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(System5x7);
  oled.clear();
  oled.print("Hello World!");
  delay(2000);
  oled.clear();

}
//------------------------------------------------------------------------------
void loop() {

  oled.setFont(System5x7);
  oled.print("Hello fuuuzzzzyyyy world!");
  delay(1);
  oled.clear();

}

how do you know that the problem is caused by the library?

what debugging have you done?

I've played around with the frequency settings which speeds up or slows down the flicker, but like I say the more common Adafruit library doesn't produce this effect when running through the loop. I'm pretty new to this so any guidance is much appreciated.

Also, i think there may be ways around it using other methods in the library to only manipulate the areas where a value is changing, but it will get messy...

don't run clear(). make an array that fits the screen, fill the array as needed with data (don't forget to write spaces for blanks), and write the whole array to the screen each time.

Yes, I was thinking along those lines, thanks for the help I'll give it a try.

Your loop is repeatedly writing and clearing the display, nearly as fast as possible (minus the 1ms delay at the bottom), which is the reason for the flicker you're seeing. If instead, you only update the display when something changes, it will look much smoother. Even a clear-and-rewrite the entire display when something changes (assuming the changes are infrequent) will be a major improvement. Of course this assumes you'd eventually be writing dynamic data; your test program, of course, writes and re-writes static data.
Update:

If I run the same code structure with Adafruit library there is no
  flicker, even with no delay in the loop.

Can you compare the two libraries to see what they do differently?

The Adafruit library does not have this issue, but I've been told uses
  a lot of memory

There's a likely clue: Adafruit may be buffering the display contents in memory so it can find out which character positions changed and update only those. That would be a classic time/space trade-off.

I'm displaying values from a Gyro so needs to update continually. If you set the delay to 1 second, there is still a noticeable flicker as the display refreshes. If I run the same code structure with Adafruit library there is no flicker, even with no delay in the loop.

Yes, it's due to rewriting the whole display.  I generally only rewrite portions that have changed or at worst use the ClearToEOL command to make sure everything's obliterated.

You could only rewrite those parts of the display that change which is the gyro value


text:
Using the MIDI library in my own library

Error message :
"error: invalid declarator before 'MIDI'
         MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
                                                       ^
Plusieurs bibliothèque trouvées pour "libMidi.h"
/home/due32/Arduino/libraries/MIDI/midi_Defs.h:170:31: note: in definition of macro 'MIDI_CREATE_INSTANCE'
     midi::MidiInterface<Type> Name((Type&)SerialPort);"

libMidi.h
#ifndef libMidi_h
#define libMidi_h

#include <Arduino.h>
#include <MIDI.h>

    void midiSetup();
    void pmbMIDI();

//  void MIDI_CREATE_DEFAULT_INSTANCE(); //doesn't work

#endif

libMidi.cpp
#include "libMidi.h"
#include <MIDI.h>

void midiSetup(){

//midi::MidiInterface<Type> Name((Type&)SerialPort);

        void MIDI_CREATE_DEFAULT_INSTANCE();
        void MIDI.begin(MIDI_CHANNEL_OMNI);
}

void pmbMIDI(){
    if (MIDI.getType() == 144){
        digitalWrite(13, 1);}

    if (MIDI.getType() == 128){
        digitalWrite(13, 0);}
}

Thank you by advance

You should include the complete error message. Every error has a line number, where it happened. And please show us your complete code, including the Arduino sketch, that is using your library, so that we also can test.

void MIDI_CREATE_DEFAULT_INSTANCE();

This line should not be placed inside a function, because it is a forward function declaration.
However, I think there are more problems in your code.
My wild guess is to improve the following lines:

Uncomment line that doesn't work

Change
MIDI_CREATE_DEFAULT_INSTANCE();

to
MIDI_CREATE_DEFAULT_INSTANCE();

and place it outside a function.
Remove the word void  in the following lines
void midiSetup();
void pmbMIDI();

And also align the { and }
void MIDI.begin(MIDI_CHANNEL_OMNI);

So it's a function call.
Other improvements is to remove spaces or tabs  in
    void midiSetup();
    void pmbMIDI();

Also align { and } in
if (MIDI.getType() == 144){
    digitalWrite(13, 1);}

if (MIDI.getType() == 128){
    digitalWrite(13, 0);}


text:
Multiple 7 segment displays blinking
i just set up 2 displays ( 3 digit 7 segments ), and the displays seems to be blinkin ( i know they are suppose to blink but so fast that the human eye cannot detect it ).
I'm using the SevSeg Library and this is how my code looks:
void setup() {

   byte numDigits = 3;
   byte digitPins[] = {2, 3, 4};
   byte segmentPins[] = {5, 6, 7, 8, 9, 10, 11, 12};
   sevseg1.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);

   byte digitPins2[] = {14, 15, 16};
   byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};
   sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);

}

void loop() {

  while(true){
     sevseg1.setNumber(number,0);
     sevseg2.setNumber(number,1);
     sevseg1.refreshDisplay();
     sevseg2.refreshDisplay();
  }
}

I need to add 2 more 3 digits 7 segment displays so i was wondering what is it that is causing the blinking.
Im using Arduino Mega.

Could you give the link to SevSeg library? There several different libs with that name, I have checked 2 and none had the methods you use.

First of all, you have a while(true) in your loop, that makes no sense. The loop already loops for ever.
You are also changing the number every time the loop() is run, making it flicker. If you follow the Arduino library example, you can see they only use setNumber every so often and use refreshDisplay every time the code runs through the loop().
Also, you didn't setBrightness, which shouldn't be a problem since the library probably sets a default value, but I'd advise on including it in your code to eliminate unforeseen problems.
Try this code and let me know if it works:
#include "SevSeg.h"

SevSeg sevseg1; //Instantiate a seven segment controller object
SevSeg sevseg2;

void setup() {
  byte numDigits = 4;
  byte digitPins1[] = {2, 3, 4, 5};
  byte segmentPins1[] = {6, 7, 8, 9, 10, 11, 12, 13};
  byte digitPins2[] = {14, 15, 16};
  byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};

  sevseg1.begin(COMMON_ANODE, numDigits, digitPins1, segmentPins1);
  sevseg1.setBrightness(90);

  sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);
  sevseg2.setBrightness(90);
}

void loop() {
  static unsigned long timer = millis();
  static int deciSeconds = 0;

  if (millis() >= timer) {
    deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
    timer += 100;
    if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.
      deciSeconds=0;
    }
    sevseg1.setNumber(deciSeconds, 1);
    sevseg2.setNumber(deciSeconds, 1);
  }

  sevseg1.refreshDisplay(); // Must run repeatedly
  sevseg2.refreshDisplay(); // Must run repeatedly
}

Thanks for your response, i removed the while true, the thing that if i remove one 7 segment displays it doesn't blink.

Yes i did, but it is like if every time i do the   .refreshDisplay();  it takes its time and shuts down the other display

I have completely revised my answer. Please do try ;)

Actually, the while() does make a little sense; looping your code that way is a lot faster.

@Tom, actually this is Arduino's demo code, not mine. Using the while also makes it loop extremely fast. As you can see from this demo code, they only refresh the display ever 100ms, preventing it from continuously refreshing.

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


text:
Checking connection/ communication
Can I ping or “hello world” an Arduino.
Background:  My son and I bought a 3-D printer kit.
(EZ-3D)
We are having some issues talking with it.  (Well we can't talk at all.)  So we thought to upload the firmware,
It’s an Arduino Mega 2560, and when we upload the Arduino times out… but it takes a minute or two.  Can I try some simpler program just to try and talk to the Arduino?
I’m almost a “virgin” Arduino user so be gentle.

Do you have an actual programmer or do you only have the on-board USB?

@IgnacioVazquez-Abrams, Ahh.. I don't think we have a programmer, but I'm not sure.  (We downloaded the Arduino software... is that what you mean by programmer?)  I mostly an idiot in these types of things.

Something that can access the MCU at a low level, such as this or this.

Adafruit has a good set of guides to getting started with arduino:
https://learn.adafruit.com/series/learn-arduino
The "Blink" program is the equivalent of "hello world".
When testing you probably should disconnect the Arduino from the 3D printer.

Thanks Craig,  It's all built in so I can really remove anything.  (We (my son and I) did do some simple Arduino projects last year... talking to it was very easy.  Which surprised me at the time.

Blink is about the most basic Arduino program there is - it just flashes the on-board LED. But once you get that far you will have proven the Arduino software on your computer, the USB connection between your computer and the Arduino, and the basic functioning of the Arduino itself. It is a really useful step to take because you'll know that much of your system works and any troubles must be in the Arduino sketch, the Arduino itself, or the hardware connected to it. I do this whenever I update my Arduino software, connect to a new Arduino or to test a newly-built board.

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


text:
Need function to convert bool array to int- why doesnt this work?
Hey I wrote this function to convert an bool array to int:
(Math Lob included):
bool b_array[5];

int convertToInt(start_index,stop_index){
    int run=0;
    int result=0;
    for(int id=start_index;id<=stop_index;id++){
        result+=b_array[id] * pow(2.0,run);
        run++;
    }
    return result;
}

but it doesnt this work?
Thanks and kind regards
Nic

"Does not work" is a poor problem description. Explain what it actually does and what you expected it to do. Provide a minimal but complete test sketch, that shows the problem

You seem to want to convert an array of bools into the respective integer value, so e.g. { false, true, true, false} into  0b0110 = 6? Then you should use better casting, so (int)b_array[id] and (int)pow(2.0,run). Though it's a weird way to do it, since bitshifting would be more appropriate (result += b_array[id] ? (1 << run) : 0) . Also be aware of the numerical limits of your 16-bit signed int.

The pow function returns a float.  Floats are inherently inaccurate.  The index to the array has to be an int.  When you do powers of 2 with pow you don’t actually get 4.  You get 3.9999999 something.  So when that gets truncated it turns into 3 and not the 4 that you want.  Use bit shifting for integer powers of 2 and you won’t have this problem.

Thank you Guys a lot! It worked like a charm but I could not have made it without you!

Assuming little-endian bools (least significant bool first), you should use simple bit-shifting, not floating point power calculations:
for(int id=start_index;id<=stop_index;id++){
    result |= b_array[id] ? (1 << run) : 0;
    run++;
}

The ternary operation (b_array[id] ? (1 << run) : 0) means:

If b_array[id] is true,  then

Or result with 1 left-shifted run times and store in result

otherwise

Or result with 0 and store the result (no-operation).

You can simplify this in C++ because bool value promoted to an integer is 0 or 1. So (b_array[id] << run) can be used. In C there is no bool data type, so something like ((b_array[id] !=0) << run) should be used. And i like for example result = (result<<1) | b_array[id]; more (it can be result = result*2 + b_array[id] too)

Thank you for your Solution and your explaination, it worked on first try like a charm! Thank you a lot, I could not have solved that without your help!


text:
How to connect 2 Fingerprint Sensor to Arduino Mega? Please help
My project was to open the door from inside and outside the room using fingerprint sensors, currently I used separate arduino on 2 different fingerprint sensor. Please help, my arduino detected only 1 fingerprint sensor when I try to connect them both on 1 arduino. ps: I connected the fingerprint sensor to digital pins (2,3) and (10,11) of the arduino mega. Thank you in advance...
//Here is my code

//for Relay

int in1 = 8; //pin for opening door

int in2 = 9; //pin for buzzer

 #include (<)Adafruit_Fingerprint.h>

//it (<) i use only to post the code

//Arduino Mega

SoftwareSerial mySerial1(2, 3); //for fingeprint sensor outside

SoftwareSerial mySerial2(10, 11);//for fingeprint sensor inside

Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);

Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

void setup()
{

Serial.begin(115200);

pinMode(in1, OUTPUT);

 pinMode(in2, OUTPUT);

 digitalWrite(in1, HIGH);

 digitalWrite(in2, HIGH);

  while (!Serial);

delay(100);

  finger1.begin(57600);

finger2.begin(57600);

  if (finger1.verifyPassword() and finger2.verifyPassword()) { //To verify if 2

fingerprint sensor is working

 Serial.println("Found fingerprint sensors!");

} else {

 Serial.println("Did not find any fingerprint sensor!");

while (1) { delay(1); }

 }

  finger1.getTemplateCount(); //To show the numbers of enrolled fingerprint in sensor

 finger2.getTemplateCount();

  Serial.print("Fingerprint Sensor1 contains ");

Serial.print(finger1.templateCount); Serial.println(" templates");

 Serial.print("Fingerprint Sensor2 contains ");

Serial.print(finger2.templateCount); Serial.println(" templates");

Serial.println("Waiting for valid finger...");

}

void loop()
{

 //for fingeprint sensor outside the door
  getFingerprintID1();
  delay(50);

//for fingeprint sensor inside the door
  getFingerprintID2();
  delay(50);
}

uint8_t getFingerprintID1() {

uint8_t p = finger1.getImage();

switch (p) {

 case FINGERPRINT_OK:

//Serial.println("Image taken");

 break;

case FINGERPRINT_NOFINGER:

// Serial.println("No finger detected");

  return p;

 case FINGERPRINT_PACKETRECIEVEERR:

 //  Serial.println("Communication error");

  return p;

 case FINGERPRINT_IMAGEFAIL:

 //Serial.println("Imaging error");

return p;

 default:

 //Serial.println("Unknown error");

  return p;

 }

// OK success!

  p = finger1.image2Tz();

switch (p) {

case FINGERPRINT_OK:

 //Serial.println("Image converted");

  break;

case FINGERPRINT_IMAGEMESS:

 //Serial.println("Image too messy");

 return p;

case FINGERPRINT_PACKETRECIEVEERR:

 // Serial.println("Communication error");

 return p;

case FINGERPRINT_FEATUREFAIL:

// Serial.println("Could not find fingerprint features");

 return p;

case FINGERPRINT_INVALIDIMAGE:

 // Serial.println("Could not find fingerprint features");

  return p;

default:

 //Serial.println("Unknown error");

  return p;

}

  // OK converted!
  p = finger1.fingerFastSearch();

if (p == FINGERPRINT_OK) {

 Serial.println("Found a print match!");

digitalWrite(in1, LOW);  //Door will open for 5 seconds

 delay(5000);

 digitalWrite(in1, HIGH);

 delay(1000);

 Serial.print(finger1.fingerID);

 } else if (p == FINGERPRINT_PACKETRECIEVEERR) {

  //Serial.println("Communication error");

  return p;

} else if (p == FINGERPRINT_NOTFOUND) {

 Serial.println("Did not find a match");

 digitalWrite(in2,LOW); //if the fingerprint did not recognize buzzer will be ON

delay(1000);

 digitalWrite(in2,HIGH);

return p;

 } else {

//Serial.println("Unknown error");

 return p;

 }

return finger1.fingerID;

}

uint8_t getFingerprintID2() {

uint8_t p = finger2.getImage();

switch (p) {

case FINGERPRINT_OK:

 //Serial.println("Image taken");

  break;

 case FINGERPRINT_NOFINGER:

// Serial.println("No finger detected");

   return p;

case FINGERPRINT_PACKETRECIEVEERR:

//  Serial.println("Communication error");

  return p;

 case FINGERPRINT_IMAGEFAIL:

 //Serial.println("Imaging error");

  return p;

 default:

 //Serial.println("Unknown error");

   return p;

 }

  // OK success!
  p = finger2.image2Tz();

 switch (p) {

 case FINGERPRINT_OK:

  //Serial.println("Image converted");

  break;

case FINGERPRINT_IMAGEMESS:

 //Serial.println("Image too messy");

  return p;

 case FINGERPRINT_PACKETRECIEVEERR:

// Serial.println("Communication error");

  return p;

case FINGERPRINT_FEATUREFAIL:

 // Serial.println("Could not find fingerprint features");

 return p;

case FINGERPRINT_INVALIDIMAGE:

 // Serial.println("Could not find fingerprint features");

  return p;

default:

  //Serial.println("Unknown error");

 return p;

}

  // OK converted!

 p = finger2.fingerFastSearch();

if (p == FINGERPRINT_OK) {

 Serial.println("Found a print match!");

digitalWrite(in1, LOW);

 delay(3000);

digitalWrite(in1, HIGH);

 delay(1000);

 Serial.print(finger2.fingerID);

} else if (p == FINGERPRINT_PACKETRECIEVEERR) {

 //Serial.println("Communication error");

  return p;

  } else if (p == FINGERPRINT_NOTFOUND) {

 Serial.println("Did not find a match");

 digitalWrite(in2,LOW);

 delay(1000);

 digitalWrite(in2,HIGH);

 return p;

 } else {

 //Serial.println("Unknown error");

  return p;

 }

 return finger2.fingerID;

}

Don't ask your question again. You can edit your first question. Also please format the code correctly by selecting it in the question editor and clicking the {} button or pressing Control+K.

Why are you using software serial, when the Mega has 4 hardware serial interfaces?

sorry sir, I am a beginner thanks for the concerns

@chrisl im using adafruit library thats why i use 2 software serials, how can I use hardware serial properly? please help

I guess your problem is, that you are using SoftwareSerial. Doing Serial in software means, that you can only listen at one interface at a time, thus only one of the fingerprint sensors work at a time.
But you are using the Arduino Mega, which has 4 hardware Serial interfaces. They are named Serial and SerialX (with X being 1,2 or 3). You can give a reference to these Serial interfaces to the Adafruit library just like you are doing it with the SoftwareSerial interfaces. You are doing:
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);

Instead you could do:
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&Serial1);

That will give a reference of the second hardware serial interface (first whould be Serial) to the Adafruit library, which will then use it to communicate with the sensor. Hardware and Software Serial implement the same interface, they just work differently under the hood, so you can easily exchange them at this level.

For Hardware Serial you cannot define your own pins. You have to use the pins corresponding to the used interface. For Serial1 this is pin 19 (RX) and pin 18 (TX)

Thank you!!! now I know how to use hardware serial on arduino mega :)))

I use this link as reference thank you


text:
How do you count objects (using ultrasonic sensor HCSR04) as 1, after they leave the trigger/echo path?
I found a simple code online that meets my goal to almost 100%, however when I place my hand in front of it, the number continues to count. I am trying to only count "1" when the solid object has moved from initial view of the sensor, to ending view.
#define trigPin 13
#define echoPin 12
int counter = 0;
int currentState = 0;
int previousState = 0;

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 if (distance <= 10){
 currentState = 1;
 }
 else {

Your code is missing some part at the end. Maybe thats just a copy paste error. Please provide the full code

it's the same thing as counting the number of times a light has been turned on ....you don't count 1 every time the light is on when you look at it ... there is something else that you have to see before you can say that the light was just turned on


text:
What is the difference between serial begin() and wire.setClock() for I2C communication?
I am a new Arduino IDE user and have a simple question below
For I2C transmission speed setting, there are serial begin() and wire.setClock(). Some sample codes just use Serial.begin() without Wire.seClock(), some use both as shown below. What is the real differences between them? When to use just serial and when to use both of them? Thanks.
void setup() {
  Serial.begin(9600);          // start serial communication at 9600bps

  Wire.begin();                // join i2c bus (address optional for master)

  Wire.setClock(400000); //Increase  I2C clock rate to 400 kHz
}

Serial has nothing to do with Wire/I2C communication. The examples only have this, because mostly they use Serial out- and input for interaction in the example codes (like showing the data of an I2C sensor on the Serial Monitor).
If you don't want to use the Serial Montior/Serial communication, then you can leave all the calls to Serial out.

Serial.begin starts the communication on USB or RX/TX pins. It has nothing to do with Wire library and I2C communication.
I2C clock speed determines the speed of communication on the I2C bus. Wire.begin() among other settings, sets the I2C clock speed to some default value.
Wire.setClock() allows to set a different clock speed. This should be supported by all devices on the I2C bus or clock speed can be changed before communicating with a specific device on the bus.
Wire.setClock should be called after Wire.begin because Wire.begin sets the clock speed to some default.


text:
Using Arrays and LED's to represent Piano Scales
I am trying to use addressable LED's to show various piano scales using the semi notes formula for each scale as an array and an input to indicate the starting note.
int MajorScale[] = {2,2,1,2,2,2,1}; //represents the semi notes in a major scale
int t= 8 //represents the led number that represent the first C on the keyboard

The following leds should light up -
(8, 8+2, 8+2+2, 8+2+2+1, 8+2+2+1+2, 8+2+2+1+2+2, 8+2+2+1+2+2+2 , 8+2+2+1+2+2+2+1)  // This is first C Major Scale on the Piano
so..
(8,10,12,13,15,17,19) // This is first C Major Scale on the Piano where 8 is the first c
Then light up all the other C Major scales available on the piano limited by the number of keys on the piano in this case 76 keys
As there are 12 notes for each octave , add this to the array
if i take just the C note
8, 8+12, 8+12+12 ,8+12+12+12, 8+12+12+12+12  etc
My code so far just lights up the semitone that i set up in the array
enter code here
#include "FastLED.h"
#define DATA_PIN 5
#define NUM_LEDS 76
#define BRIGHTNESS 10
CRGB leds[NUM_LEDS];
int MajorScale[] = {2,2,1,2,2,2,1};
int delayValue = 1000;

void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
FastLED.clear();
}

void loop() {
for(int i = 0; i <=6; i++)
{
    leds[MajorScale[i]] = CRGB::BlueViolet;
    FastLED.show();
     delay(delayValue);

}

FastLED.clear();
}

And what is your question? What is the specific problem, that you have with coding the rest?

How do i make this happen .. From the initial array {2,2,1,2,2,2,1} to the first set of LED lights (8,10,12,13,15,17,19) . I cannot visualize the formula that adds each element of the array to its next element.  Feels like a running sum with an addition of a constant

Your current code will not show all notes of a scale. Only the notes at 1 and 2 will light up, since you don't sum up the numbers, that you have stored in MajorScale. But I think it is not a great idea to sum them up programatically, since this is a constant and you don't win much by representing the data this way. Instead you should directly initiate the MajorScale variable with the summed up values:
int MajorScale[] = {0, 2, 4, 5, 7, 9, 11};

Then you can enclose your for loop with another for loop, that adds an offset corresponding to the octave:
for(int j=0; j<NUM_LEDS; j+=12){
    for(int i=0; i<=6 && MajorScale[i]+j<NUM_LEDS;i++){
        leds[8+MajorScale[i]+j] = CRGB::BlueViolet;
        FastLED.show();
        delay(delayvalue);
    }
}

So we set the LED number 8+MajorScale[i]+j. 8 for the offset to C, MajorScale[i] as the position of the note in the current octave and j for the offset of the current octave relative to the C.
Note, that this is not tested in any way.

A fear you forgot to sum the MajorScale values. e.g.  leds[MajorScale[ 0 ]+j] ==  leds[MajorScale[ 1 ]+j] are pointing to the same LED. And must also be an poffset of 6 for each j. IMHO ;-)

Ah, you are right. I got that mixed in my head. I will change the answer

As I saw the edit, I realized that I did also a mistake. The idea of modyfing the MajorScale array is better than the offset of 6 (good idea).. I was wrong when I said that each j needs an offset of  6 This first MajorScale starts at LED no 8 but the second scale starts with the next LED; I guess. So if the first C is at LED 8 start with j=8 and add 0. The next LED is the D -> add 2 then E add 2 then F add 1 ... the next octave j++ the , 11} must be removed because j++ jumps to the next octave C where you add 0. and so on. Sorry for this "for each". Party fail ;-)

The position 11 corresponds to the B, which is still 1 half tone under the next octaves C. After that the number of i doesn't matter anymore, since the inner for loop wil exit. But I guess I should initialize i to zero in the for loop.

If you've seen my last comment. I removed it because it was complete nonsense. You're right the code is correct.

@chris thanks that worked.  I want this program to light up the LEDs required and then stop. Leave them on. I updated the for loop and when i did that the LED stopped blinking. I added 8 to the for loop    for(int i=0; i<=6 && MajorScale[i]+j+8<=NUM_LEDS;i++)  I don't quite know why it worked ?


text:
Problem with NodeMcu interrupt
I am Using Arduino IDE to program NODEMCU. I am expecting LED should remain ON for 4 sec. But it turns OFF in less than 2 sec. Please can anyone explain me why this happening? Also I noticed that if serial monitor is used, led ON timming changes with baudrate. I don't know why this is happening.
#include <ESP8266WiFi.h>
#define LED D1    // external LED is connected to pin D2
uint8_t GPIO_pin = D2;
void ICACHE_RAM_ATTR IntCallback();

void setup(){
  pinMode(D1,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(GPIO_pin),IntCallback,CHANGE);
}
void loop(){
  digitalWrite(LED,LOW);      // Turn off LED to indicated Interrupt routine ended
  delay(1000);               // Without this delay, LED just blinks too weakly for milliseconds
}

void ICACHE_RAM_ATTR IntCallback(){
 digitalWrite(LED,HIGH);  // Turn LED ON to indicate Interrupt Routine started
 delay(4000);             // Delay in order to keep LED ON
}

Calling delay() in an interrupt is really a bad thing to do. You should wait in the loop, not in an ISR

@chrisl ok thanks..I will follow that..


text:
i need to connect ultrasonic gas MQ2 and IR sensor(as blink counter) to count the number of blinks
im making a drowsiness detection using IR sensor as blink counter less than 30 and ultrasonic sensor distance should be less than 50cm and gas sensor MQ2 if the driver has consumed alcohol the gas will be detected and buzzer will be turned on and if the driver is drowsy the arduino will count the blinks if less than 30 it will turn on the buzzer and display on LCD as drowsy driver and led will blink.
can anyone pls help me with the codes?
i have managed the code
int trigPin = 6;
int echoPin = 7;
int IRSensor = 2; //connect ir sensor to arduino pin 2
int LED = 13;
int LED1 = 12;
int buzzer = 10;
int smokeA0 = A5;
int sensorThreshold = 50;
int sound=250;

void setup() {
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode( IRSensor,INPUT);//sensor pin INPUT
  pinMode(LED1,OUTPUT);
  pinMode(LED, OUTPUT);//LED pin OUTPUT
  pinMode(buzzer, OUTPUT);//Buzzer Pin OUTPUT
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop()
{
  long duration,distance,statusSensor;

  int IRSensor = digitalRead(IRSensor);
  int analogSensor = analogRead(smokeA0);
  Serial.print("Pin 2");
  Serial.println(statusSensor);
  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (distance<=30)
  if (statusSensor == 10)
  if (analogSensor > sensorThreshold)
  {
    digitalWrite(LED, HIGH);
    digitalWrite(LED1, LOW);
    tone(buzzer, 1000, 200);
  }

  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED1, HIGH);
    noTone(buzzer);
  }
  digitalWrite(LED, HIGH);
    digitalWrite(LED1, LOW);
    tone(buzzer, 1000, 200);
  }

  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED1, HIGH);
    noTone(buzzer);
  }
  else
  {
    digitalWrite(LED, HIGH);
    digitalWrite(LED1, LOW);
    tone(buzzer, 1000, 200);
  }

 else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED1, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

And what exactly is your problem?

You cannot use multiple else statements, but probably you want to have conditions there 'else if (condition)', except for the last else maybe.

what does less than 30 mean?


text:
Code help in Arduino ( Serial data)
I Need a help in this code
I am trying to assign the serial.write(OutData[i]) to byte data[]. Can anyone help me assign it.
Here is my code
#define ECHOPIN 11// Pin to receive echo pulse
#define TRIGPIN 12// Pin to send trigger pulse
int distance=0;
 byte OutData[] = {0x05, 0x03, 0x04, 0x43, 0x65, 0xBA, 0x7D, 0x04, 0xE8};
#include <Crc16.h>
Crc16 crc;
void setup()\
{
  Serial.begin(9600);
 pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  digitalWrite(ECHOPIN, HIGH);
}
void loop() {
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW); // Send pin low again
  distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
  distance= distance/58;
  Serial.print(distance, HEX);
   OutData[3] = 0x00;

  OutData[4] = 0x00;

  OutData[5] = 0x41;

  OutData[6] = distance;
for (int i = 0; i <= sizeof(OutData); i++) {

    Serial.write(OutData[i]);

    byte data[] = OutData[i];
    crc.clearCrc();
  for(byte i=0;i<9;i++)
  {
     Serial.print("byte ");
     Serial.print(i);
     Serial.print(" = ");
     Serial.println(data[i]);
     crc.updateCrc(data[i]);
  }
  unsigned short value = crc.getCrc();
  Serial.print("crc = 0x");
  Serial.println(value, HEX);

  Serial.println("The crc Check of the byte array");

  //Modbus
  value = crc.Modbus(data,0,9);
  Serial.print("Modbus crc = 0x");
  Serial.println(value, HEX);

  while(true);
}
int calcrc(char *ptr, int count)
{
    int  crc;
    char i;
    crc = 0;
    while (--count >= 0)
    {
        crc = crc ^ (int) *ptr++ << 8;
        i = 8;
        do
        {
            if (crc & 0x8000)
                crc = crc << 1 ^ 0x1021;
            else
                crc = crc << 1;
        } while(--i);
    }
    return (crc);
}

My Error is :
C:\Users\system3\AppData\Local\Temp\arduino_modified_sketch_307616\sketch_dec13a.ino: In function 'void loop()':

sketch_dec13a:34:25: error: initializer fails to determine size of 'data'

     byte data[] = sizeof(OutData);

                         ^

sketch_dec13a:34:25: error: array must be initialized with a brace-enclosed initializer

sketch_dec13a:60:1: error: a function-definition is not allowed here before '{' token

 {

 ^

sketch_dec13a:77:1: error: expected '}' at end of input

 }

 ^

Multiple libraries were found for "Crc16.h"
 Used: C:\Users\system3\Documents\Arduino\libraries\Crc16-master
exit status 1
initializer fails to determine size of 'data'

I don't see any Serial.read() call in your code (and this method does not have a parameter, I think). Also you should include the complete error message, including information about the problematic line.

I am really sorry its Serial.write(). And the complete error message is initializer fails to determine size of 'data'

With complete error message I meant the complete output of the compiler or at least the complete section, where the error is described. When the compiler finds an error, it also outputs, where it found the error. That makes it easier for us to find the problem. Also sometimes the error is caused by a previous error, so the complete compiler output is the best way to include all information, that might be relevant.

I have added the additional error message which is showing now.

The following code block does not make sense:
for (int i = 0; i <= sizeof(OutData); i++) {
    Serial.write(OutData[i]);
    byte data[] = OutData[i];
    crc.clearCrc();
} // I added this bracket for you.

It is formally wrong to create an array this way. The compiler does not have any way to know, how big the array should be. I think the declaration with [] works only, when you initialize the array, but you are simply assigning 1 byte value to it. byte is not the same as array of byte. So this cannot work. To make it formally correct, you can either change data to a simple byte variable (not an array), or define the size of the array via byte data[3]; and then assigning the OutData[i] value to one of it's elements in the next line;
Above I added the closing curly bracket for you after the first for loop. It seems, that you forgot it, thus you would get more errors due to imbalanced brackets.
You are create a variable/array inside your for loop, that is not used anywhere. As soon as the current for loop iteration is finished, the variable/array is out of scope and will vanish. You have to declare it outside of the for loop (either inside the loop() function or globally), so that you can use it in the following code.
It seems, that you try to copy the data from the OutData array into the  data array to output the values in the later code and calculate the CRC value. I don't see, why you are doing this. Is there a reason, why you could not do this directly with the OutData array? I don't see the need for copying the data in an extra array.
The following line can easily be a problem:
OutData[6] = distance;

distance is defined as an int, which is a 16bit/2byte signed number. OutData is defined as an array of byte, which is a 8bit/1byte unsigned number. pulseIn() returns an unsigned long (32bit/4byte unsigned number). Since you have configured a timeout of 26000, you won't get in conflict there, but easily, when trying to assign the distance value to an element of OutData. You can get distance values up to 448, but a byte can only hold numbers between 0 and 255. So you will get an overflow and thus garbled data. You will have to send both bytes of distance to always get the full value. (You can easily google how to get the individual bytes of an int; The Arduino framework even has defines for this, lowByte and highByte, I think).

Thank you so much

@JoshEarnest If you think, that one of the answers is correct, you can mark it as the correct answer. That way others know, that this question was successfully answered and which of the answers helped you the most

byte data[] = OutData[i]; is an invalid statement.
You try to initialize an array with unknown size [] with a single element.
you must use an array to initialize an array and not a single element.
byte data[] = { 0xca, 0xfe, 0xba, 0xbe };
would initialize data with an array of four elements.

Thanks for your valuable comment


text:
Determine XBee Packet Route
I am trying to build a ZigBee network using XBee Pro S2 devices (API Mode).
Setting up the network and sending packets is easy enough.
Is it possible to trace the route a packet travelled from the end-device to the coordinator?
Example:
I have 2 routers, one in area A connected to the coordinator, and the other in area B connected to the router in area A. End-device enters area B, and transmits a packet to the coordinator. Path: end-device->routerB->routerA->Coordinator.
Is it possible to know the end-device is in area B as it is the first router device the packet travelled through?

I'm not sure what you mean by  “Coordinator”.  If it's an ordinary computer, run traceroute (or tracert) on it

The "Coordinator" refers to the device type used in the ZigBee network protocol. Every network must have at least one Coordinator. Just note, the ZigBee mesh network is not like standard WiFi protocol. But thank you, I found the answer.

It is done by using Source Routing
The 16-bit addresses of the hopped devices are added to the RF payload space, thus it will reduce the number of bytes that can be sent in one RF packet.


text:
AtTiny analog read always 1023
I am trying to replicate Low power LED firefly project. So what I'm trying to do is to do an analog read from a LED, to detect light. To simplify it a bit, I am using different pins and different leds for IN and OUT. The code:
#define PIN1 don't use this pin! /*this is RESET*/
#define PIN2 3
#define PIN3 4
#define PIN4 don't use this pin! /*this is GND*/
#define PIN5 0
#define PIN6 1
#define PIN7 2
#define PIN8 don't use this pin! /*this is VCC*/
#define ANL1 PIN7
#define ANL2 PIN3
#define ANL3 PIN2

// the setup function runs once when you press reset or power the board
void setup() {
  digitalWrite(PIN3, LOW);
  pinMode(PIN3, INPUT);
}

#define BLINK true
// the loop function runs over and over again forever
void loop() {

  const int value = analogRead(PIN3);
  if(value>=1023) {
    pinMode(PIN2, OUTPUT);
    digitalWrite(PIN2, HIGH);
    delay(500);
    digitalWrite(PIN2, LOW);
    delay(3);
  }
  else {
    delay(1);
  }
}

This is the setup. I am using much smaller resistor, but I'm still getting 1023 on analog read, as indicated by the output led always being on:

simulate this circuit – Schematic created using CircuitLab
What's wrong?

In this article the following steps are used when using an LED as a light detector:

Light up the LED by making the anode positive (logic one) and the
cathode negative (logic zero) - this fully discharges the LED as a
capacitor.
Charge up the capacitor by making the anode negative and the cathode
positive, as this is a small capacitor it will take no time at all
in other words for as short a time as you can.
Put the diode into the measurement mode, by making the anode
negative (it already is) and the cathode connected to an analogue
input.
Make a measurement of the analogue voltage, this is a reference
level to be used later.
Wait while the photon current is integrated - the longer the more
sensitive but too long and effects other than photo current
dominate.
Measure the voltage again and subtract it from the reference value
you took before the integration time. This figure is your light
reading.

Looking at the code in the above question it is not apparent where you switch from forward bias to revers bias.  Also, it does not appear there are two samples taken and the difference between the two samples is found.

Thanks for the explanation. But I was more concerned about the fact that the analog read doesn't return zero, or close to zero, when it's shorted to GND via the resistor.

Since you are not using "value" to, say, dimension an array, then you should not use "const".  This may be the root of the problem you are having.  Also, ADC are not all that accurate.  If you don't take several readings and average them then you usually only get a few significant bits out of the range of the ADC.


text:
Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing
I followed this guide to program AtTiny using Arduino as ISP. The problem is that it has some file missing:
java.io.FileNotFoundException: C:\...\arduino-1.6.8\hardware\attiny\variants\platform.txt

The attiny directory is clone of this repository. How do I make it work?

Open the "Preferences" dialog in the Arduino IDE.
Click on the symbol next to "Additional Board Manager URLs"

Paste the following into the box (possibly on a new line under any existing URLs), then click OK.
https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

Note that you can click on the circled link for a list of boards. This will open in your web browser. You may have to switch to your browser to notice it.

Click OK to close the Preferences dialog box.
In the Tools menu / Board select the Boards Manager:

Scroll down until you see the Attiny entry (or the one for the board you want), click on it to select it, and then click "Install".

Once done, close the Board Manager dialog box.
You should now be able to select Attiny from the Boards menu:

Now in the Tools menu you can select which Attiny you want to use:

Notice you can also select the appropriate clock speed in an adjacent menu item.
To program the Attiny you will need a suitable ISP (In System Programmer) such as the AVRISP programmer, or the USBtinyISP programmer.

The way of adding boards has changed in the newer version.
Try finding a tutorial for 1.6, or download the older 1.0 version.

I tried to find up to date tutorials and what I found is linked in my question. I think this answer would better qualify as a comment since it's like link-only, but without the link...

The tutorial was using version 1.0, while you are using 1.6.8. That is why you are getting the error. So that is an answer. PS The tutorial is more than 4 years old, and the github repo is from 2011.


text:
When I verify the sketch I get several errors
I am extremely new to Arduino coding and have downloaded a sketch for the PCA9685 to use with model railroading and turnout control.  When I verify the sketch I get several errors ... I don't even know how to resolve and could use some assistance.  There are two sketches:
1:
    /***************************************************
  This sketch can be used to operate any number of turnouts on a
  Model Railroad. Code blocks can be added to accomodate any number
  of servos. This sketch uses only two servos for this demonstration.

  The pushbutton can be replaced with a SPST switch
  commonly used on a control panel. Three pin Bicolor LED can be used
  in place of two seperate LEDs in each circuit.

  10K Ohm pulldown resistor used on switch
  330 Ohm resistor used on LEDs. One per pair of LEDs

  Created 03/02/2019 by Tom Kvichak
  https://tomstrainsandthings.com/
  Additional Arduino Projects can be found at the above web address

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

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

int buttonPin0 = 2;   // Can add as many buttons as needed
int ledPin0C = 3;     // C designates Closed position of turnout
int ledPin0T = 4;     // T designates Thrown position of turnout
int buttonState0 = 0;

int buttonPin1 = 5;
int ledPin1C = 6;
int ledPin1T = 7;
int buttonState1 = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("pca9685_TurnoutFinal!");
  pwm.begin();
  pwm.setPWMFreq(60);
  delay(30);

  pinMode(ledPin0C, OUTPUT);
  pinMode(ledPin0T, OUTPUT);
  pinMode(buttonPin0, INPUT);
  pinMode(ledPin1C, OUTPUT);
  pinMode(ledPin1T, OUTPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {
  ///////////
  buttonState0 = digitalRead(buttonPin0);
  if (buttonState0 == HIGH) {
    pwm.setPWM(0, 0, 370);
    digitalWrite(ledPin0T, LOW);
    digitalWrite(ledPin0C, HIGH);
  }
  else  {
    pwm.setPWM(0, 0, 285);
    digitalWrite(ledPin0C, LOW);
    digitalWrite(ledPin0T, HIGH);
  }
  //////////
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH) {
    pwm.setPWM(1, 0, 370);
    digitalWrite(ledPin1T, LOW);
    digitalWrite(ledPin1C, HIGH);
  }
  else  {
    pwm.setPWM(1, 0, 285);
    digitalWrite(ledPin1C, LOW);
    digitalWrite(ledPin1T, HIGH);
  }
  //////////
}

2:
    /***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 8 servos, one after the other on the
  first 8 pins of the PCA9685

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These drivers use I2C to communicate, 2 pins are required to
  interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

#define SERVOMIN  110 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  510 // this is the 'maximum' pulse length count (out of 4096)

// May have to adjust values to match your servos
// Test your servo with the procedures below

// our servo # counter
uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("pca9685_TurnoutTest!");
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  delay(50);
}
///////////////////Functions//////////////////////

void driveMin() {
  pwm.setPWM(servonum, 0, SERVOMIN);    //Use to test low range
}
void driveMax() {
  pwm.setPWM(servonum, 0, SERVOMAX);    //Use to test high range
}
///////////////End Of Functions//////////////////

void loop() {

  for( int angle =0; angle<181; angle +=15){  // testing only right now
    delay(500);
    pwm.setPWM(1, 0, convert2angle(angle) );   // May only need this for sweeping the servo
  }

}
int convert2angle(int myang){
   int pulse = map(myang,0, 180, SERVOMIN,SERVOMAX);// map angle of 0 to 180 to Servo min and Servo max
   Serial.print("Angle/Pulse: ");Serial.print(myang);
   Serial.print(" / "); Serial.println(pulse);
   return pulse;
}

ERROR MESSAGES:
pca9685_TurnoutTest:23:25: error: redefinition of 'Adafruit_PWMServoDriver pwm'

 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                         ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:21:25: note: 'Adafruit_PWMServoDriver pwm' previously declared here

 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                         ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void setup()':

pca9685_TurnoutTest:35:6: error: redefinition of 'void setup()'

 void setup() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:33:6: note: 'void setup()' previously defined here

 void setup() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void loop()':

pca9685_TurnoutTest:52:6: error: redefinition of 'void loop()'

 void loop() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:48:6: note: 'void loop()' previously defined here

 void loop() {

      ^

Using library Wire at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\Wire
Using library Adafruit-PWM-Servo-Driver-Library-master at version 2.0.0 in folder: C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master
exit status 1
redefinition of 'Adafruit_PWMServoDriver pwm'

The errors are shown in the Arduino IDE under the sketch. Mark the corresponding text, press Control+C, click "edit" on this site, click at the end of the text in the appearing text editor. Press Control+V to paste the text into the question. Then select the whole text of the error message and click on the {} button, that you can see above the text in the text editor.

You seem to compile a sketch from a folder, where more than 1 .ino file is placed. I guess this from the paths, that are mentioned in the error messages.
The Arduino IDE supports you to organize your code into multiple .ino files, so that big code can be read way easier. For this it put's together all .ino files in the folder of the main sketch, so that they get compiled together.
Since you have at least 2 full sketches in the same folder, this leads to a redefinition error, since these resources (the variable pwm and the functions setup() and loop()) are already defined by the first sketch, when the compiler gets the second sketch.
You have to put all your individual sketches into own folders. Then the error will not appear. I tried to compile your two sketches individually and that worked fine.

Thanks so much ... I will work on creating individual sketches!

Great! Every sketch in an individual file in an individual folder

@WayneHensley If this answer solved your question, you can accept it as correct :)


text:
How to send and receive unsigned int from one arduino to another arduino
I'm trying to send some big numbers ranging from 0-62000 from one arduino to another via serial communication. I'm using unsigned int to hold values from 0 to 65535. And I'm using serial.print() and serial.write () to send numbers and serial.read()-'0' ; to receive numbers, but I'm unable to send and receive numbers above 9. Please help me.
Here is my code -
(For master)
const int Button_1 = 2;
unsigned int s =0;
void setup ()
{
   Serial.begin(115200) ;
   pinMode(Button_1,INPUT);
}
void loop()
{
  if (digitalRead(Button_1))
  {
     s = 61805;
     Serial.write(highByte(s)) ;
     Serial.write(lowByte(s));
     delay (5);
     s=0;
  }
  else
  {
     s = 60005;
     Serial.write(highByte(s)) ;
     Serial.write(lowByte(s));
     delay (5);
     s=0;
  }
}

(code for slave)
unsigned int upperByte, lowerByte, r=0,p=0;
void setup()
{
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT) ;
}
void loop ()
{
  If (Serial.available()>1)
  {
     upperByte = Serial.read();
     lowerByte = Serial.read();
  }
    r = (upperByte << 8) + lowerByte ;

   while (r==61805)
    {
        digitalWrite(LED_BUILTIN, HIGH) ;
    }
    while (r==60005)
    {
        digitalWrite(LED_BUILTIN, LOW) ;
    }
}

hint: with serial.write(b) you get to 256. with two serial.write(b) you get to 256*256 (65536)

If you want to do this in ASCII (opposing to byte values like Juraj suggested), you should use a message delimiter - a special character that marks the end of a number. You can use the newline character \n for this. Then you can read the digits one by one, adding them together to the big number. For further help, we need to see your code.

Using two serial.write (b)  is nice idea, but I can't get many numbers which lies between 0-65536 with that logic. And my code is very basic, I'm just using serial.write ()  to send and serial. read() to receive.. I don't think if it will help you.

What do you mean "I can't get many numbers which lies between 0-65536 with that logic"? You can send as many ints as you want. You would send each int as a pair of bytes, as shown in CrossRoads' answer. Each unsigned int can hold a value from 0-65535.

i can move up to 32 bytes from one arduino to another using master/slave architecture.  if that helps, i can post an answer

There are 2 ways to transmit data over serial: As byte data or in ASCII codes

Byte data: Everything, that is digitally stored or processed, is a series of 0s and 1s (bits) (electrically HIGH and LOW level), which are grouped into bytes (8 bits). So all data is just numbers at low level. The different datatypes (like numbers, Strings, executable code) are only reached by different interpretation of the byte data. You can take the number value of a byte directly. A byte like 0b00000101 for example is equivalent to the decimal value 5. So every byte can hold numbers between 0 and 255. (Google the binary system for more information). To hold bigger numbers, more bytes are put together. For example an integer consists of 2 bytes (16 bits) and can hold numbers between 0 and 65535. Note: These are the unsigned types. There are also signed types, that also can hold negative values. To understand this, google binary two's complement. To transmit such a bigger type over serial (which is byte based), you need to seperate the bytes of the type, send them consecutively and put them back together at the receiving side. You can do this with the following code:
unsigned int number = 54321;
Serial.write(number & 0xFF); //getting the lower byte of the number by using bitwise AND
Serial.write(number >> 8); // getting the high byte of the number by shifting the bits of the value 8 bits to the right

There are macros defined for Arduino, that can do this for you:
Serial.write(lowByte(number));
Serial.write(highByte(number));

In long term, you should learn, how the bitwise operators work. They are often needed. To put the data back together, you can look at CrossRoads answer.
Note: Serial.write() will send the byte data unchanged, while Serial.print() will convert the data to ASCII before sending. They are not equal.
ASCII Data: One interpretation of byte data is the ASCII standard (which is really old). Every byte value between 0 and 127 get's a corresponding ASCII value, meaning characters of the alphabet, digits, some special characters and some control characters. Numbers, that are transmitted as ASCII data, consist of multiple bytes, one for each digit. Thats, what you tried. Since the receiver has to seperate the different numbers to process them correctly, you have to mark the end of each number. This is commonly done with the newline character \n (optionally preceeded by the carriage return character \r, windows style). You add this at the end of every number. Serial has an extra function for that: Serial.println() will print the parameter as ASCII and will add a carriage return and newline character. On the receiving side you read the bytes into a buffer, until you see this delimiter sequence. After that, you process the whole buffer. If you want to know, how this Serial communication is done in code, look at the SerialEvent example, that comes with the Arduino IDE.

What way you use for transmitting data, is up to you and depends on your needs. If you only want to transmit number data, nothing else, you can use byte data. For complex or diverse data types, you can use the ASCII representation.

EDIT: I have described above, that - when using ASCII data - you can use one or more special characters to delimit one message/number. The receiver can then distinguish between the numbers in that row of digits. This is just some kind of protocol, that you impose on the data. You state, that every message is ended with this special character, much like very sentence in the english language is ended with a dot.
An important requirement is, that the special character does not occure inside of a message/number. So cannot use the character '1' as delimiter, since it will also occur inside of your numbers and you would chop the numbers in the wrong way.
The same principle can be imposed as protocol onto a byte stream. For example: You define, that every message/number will be ended with a special byte sequence, so that the receiver always can say: "This is the whole data of a number and not just a part of it." As above, the special byte sequence must not occur inside of the valid data. You wrote, that your numbers are always in the range of 0 to 62000. This means, that the value 65535 will never occur as valid data, thus you can use it as delimiter. In hex 65535 is written als 0xFFFF, which means, that you send two bytes with every bit set to 1 (each byte having a decimal value of 255). In your code everytime, that you are receiving something, you can check, if you have got 2 consecutive bytes with the value 255 (or written as 0xFF). If not, write the data into a buffer. If yes, that means, that you can process the data inside the buffer to a number.
For sending that would look like this:
Serial.write(lowByte(number));
Serial.write(highByte(number));
Serial.write(0xFF);
Serial.write(0xFF);

Note: This protocol will make sure, that sender and receiver cannot get out of sync. But still the first reading after a transmission problem (for example that a byte got send before the receiver was ready) will be garbage. That will happen very very rarely, so for most people it's not a problem. There are more principles, that you can use in your protocol to mitigate those problems, if you want to. For example you can define another special byte sequence as the start of a message/number. Or you can calculate a checksum of the number and only use messages/numbers, that fit to that checksum.

Oh ok ty, I think it will help for sure (:

I have posted my code, sry it is not arranged coz I'm using it on my phone so can't see any option to arrange it.. It is not working, I'm trying a basic program to send and receive those high numbers.. Please check it, ty (:

Logic is not working I don't know what's the problem, please help me to solve it

@Mayank How it is not working? What behaviour do you actually see with that code? Do you use an external pulldown resistor for the button? And the receiver code will only react once, since it will get stuck as soon as one of the two values for r are received, because in the while loops r cannot change. Instead of while use an if statement for testing.

Note that, with binary transfer, if the receiver misses the first byte (maybe it takes longer than the sender to boot), it will get out of sync. It will stick the second byte of the first number together with the first byte of the second number, and get a bogus result. There are ways out of this (checksums, frame delimiters + escape code...), but they are not so simple. ASCII is way easier and should be preferred as long as throughput is not an issue.

Yeahhhhhh, I'm using external pull down resistor for button. I will try internal resistance if you want? Oh ok I will do those changes and see ty (:

Does ASCII way is much better tha Byte? I don't know how to use it, I will be happy to learn (:

Actually servo is stucked at 0° and not moving

Oh, so do I put \n and \r after every number in my previous code?  Does it will work fine?

Yes, after every number. The receiver has to distinguish the numbers, so you need a delimiter. Servo? Your code is not using a servo. Byte transmission is not that capable. It depends on what you want to send. Numbers are still ok. You can mitigate the out of sync due to startup problem by waiting a bit, before sending data. You can also impose some protocol onto the byte stream. For example you can choose a short byte sequence, that will not occur in your data (for example 0xFFFF), which can mark the end of a number. Then you cannot get out of sync.

If you want to use ASCII, look at the SerialEvent example of the Arduino IDE. That shows, how this is often be done.

Ty so much!! ((: after those changes it is working..  Ohh? Where I put that 0×FFFF.. Can you please explain it with a small example code?

Try something like this to send and receive/recombine two bytes:
Send side:
Serial.write (highByte (your unsigned int));
Serial.write (lowByte (your unsigned int));

Receive side:
if (Serial.available() >1){ // two byte received
upperByte = Serial.read();
lowerByte = Serial.read();
}
newInt = (upperByte <<8) + lowerByte;

Does I can get 257 as a output too? With that logic?

257 decimal = 0x0101.  highbyte = 0x01, lowbyte = 0x01.  x01 << 8 + 0x01 = 257 decimal, so sure.

Yes, you can use this method to send any value from 0 to 65535 (2^16 - 1). If you need larger values than that you can send an unsigned long using 4 bytes. That will give you a huge range of values. (0 to 2^32-1, which is over 4 billion.)

Oh cool! Ty ((:

What are upperbyte and lowerByte ? Int type data type?

bytes.  I declare them before setup() so they are global.  I declare all my variables there. Probably an abuse of how scope of variables was intended, but it works ok for the small embedded programs I create.

Oh got it... ty! (:


text:
Nesting loops - if statement in a while loop
I have been trying many variations of code like this, cannot seem to get this to work with how I logically would think it would work.  Am I missing something with syntax or breaking some rules?  Everything works independently but not jointly.
int switchS = 0;
int var = 1;

void setup() {
    pinMode(1,INPUT);
    pinMode(7,OUTPUT);
    digitalWrite(7,LOW);
}

void loop() {
    switchS = digitalRead(1);
    while(var == 1)
    {
        digitalWrite(7,HIGH);
        delay(100);
        digitalWrite(7,LOW);
        delay(100);
        if(switchS == HIGH)
        {
            var = 0;
        }
    }
    delay(5000);
    var = 1;
}

I wrote an answer to what I think you are asking, but please be more specific in your question. "work with how I logically would think it would work" We cannot see in your head, so we don't know, what you are thinking how it should work. In every "does not work" question, you should clearly state, what you expected the code to do and what it actually does. That way we can provide way better answers.

I guess you want the while loop to exit, when the switch goes to HIGH. (You didn't explain this in your question)
Currently the variable switchS cannot ever change while the code is in the while loop. The variable var only changes, when switchS is HIGH. So, if switchS is LOW at the start of the while loop, you have an infinite loop.
Instead, you can actually read the switch state inside the while loop, not outside of it. The variable switchS will not automatically track the state of the switch. You have to explicitly read it. Like this variant of your code:
int switchS = 0;
int var = 1;

void setup() {
    pinMode(1,INPUT);
    pinMode(7,OUTPUT);
    digitalWrite(7,LOW);
}

void loop() {
    while(var == 1)
    {
        digitalWrite(7,HIGH);
        delay(100);
        digitalWrite(7,LOW);
        delay(100);
        switchS = digitalRead(1);  // I moved this line in the while loop, to read the switch on every loop iteration
        if(switchS == HIGH)
        {
            var = 0;
        }
    }
    delay(5000);
    var = 1;
}

Note: You are using pin 1 as input pin. On the Uno this is a Serial (UART) pin, which is used to communicate with the PC. If you have enough pins, that are free, you should not use pins 0 and 1, so that you don't block the serial communication, unless you really need it and know, what you are doing.

Yes that is what I was trying to do, I was just about to clarify but you already you answered.  Thank you so much, can't believe I missed that.

@eatsmypasta Please mark the answer.


text:
light leds from an array
I have the project to build a robot for my school. It will record button pushes then move according to this record.
Before usig motors, i'm trying to do this using leds.
Thanks from posts from this community, I've succeed in recording button pushes in an array.
Now I'm trying to light the leds according to this array.
I have 4 buttons with 4 leds and one button tu run the recording when it's ready.
I'm stuck in lighting the leds when I push the play_button.
I hope someone can help me...
Here's my script :
int arr[10];
boolean previous = LOW;
unsigned long time1 = 0;
int debounce = 200;
unsigned long time2 = 0;
int index_state = 0;

int play_button = 13; //define pin # for play button

int button[4] = {2,4,6,8}; //store button pins in an array
int leds[4] = {3,5,7,9}; //store led pins in an array

void setup()
{
  for(int n=0;n<10;n++) arr[n] = 0;//initialisition
 Serial.begin(9600);
}

void loop(){
 boolean mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);
 while(mode == LOW) mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);//wait here till one of the pushbutton goes high;
 //Serial.println("value");
 if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {
 //find out which one is high and store that value in array;
 if(digitalRead(2)) arr[index_state] = 2;
 else if(digitalRead(4)) arr[index_state] = 4;
 else if(digitalRead(6)) arr[index_state] = 6;
 else if(digitalRead(8)) arr[index_state] = 8;
 else ;

 //print the value and the index;
 Serial.print(arr[index_state]);
 Serial.print(" Stored in index: ");
 Serial.println(index_state);
 index_state = (index_state + 1) % 10;
 //update value of time1 for button debouncing
 time1 =  millis();
}

  //update the value of previous button state
  previous = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead(8);

  }

Thank you

You have problems in including the further functionality (the playback), since your loop() function is solely written for providing the first part of functionality (the recording). You need an overall structure, that will execute the correct functionality at the correct time/logic order.
For this, an Finite State Machine (FSM) is the best way. It will help you to structure your code and the logic. It is an important principle to learn.
First you would have to divide your program logic into different states and transitions between them (don't look too close at the actual code at this point, but with a higher abstraction). Currently I see 2 states in your project: A state, where you are recording the button presses in an array, just like you already did. And a state, where the array is used for playback. The transition from the first to the second state happens, when the playback button is pressed. The transition back happens, when the playback is finished. It helps to draw a graph for this, to visualize the the states and their transitions. In my answer to this question I explained this further including an example of such a graph.
When you are finished creating the states and transitions, you can create the necessary code structure. The easiest way for a beginner is to use a simple state variable (simply an integer, or - if you want to use names for the states - an enum) in a switch()-case statement. You can also see this in the linked answer. Your code then goes into the case statements. The switch statement will only execute the code for the current state. To do a transition to another state, you simply change the state variable. So in the case statement of the first state, you put the code that you already have for reading the buttons, and an if statement, that checks the playback button. If the playback button was pressed, change the state variable to the second state.
You could also solve this problem without an FSM, but the structure won't be that good and easy to expand. Also you might get some extra points for implementing an FSM :D

Currently your code is blocking. That means, that it will block any further operation, until something happened, in this case, that one of the 4 buttons gets pressed. Often this is only a hindrance, when adding functionalities. It is better to use do-maybe code, means code, that will only do something, if some condition is met (like time). You are already doing this in the if statement
if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {

(it only triggers the recording of a new button, if a button was pressed and the debounce time has passed) so why are you blocking before this with the while loop? You could just write to mode without the while loop.


text:
How to rotate a servo continuously?
I'm new in robotics. I bought a mini robot ( Link ), which i rebuilt a little. Now it has legs and arms. This little robot has 4 little servos (Link). There are two wheels attached to two of these servos. I'd like to spin them, so the robot will "roll", but unfortinatly it is trickier than i tought. The servos can rotate in 360 degrees(i can manually turn them), no problem with that. The problem is, that no matter how i try, the servo will turn only 180 degrees. So obviously i am making something wrong. If i write myServo.write(0) the servo rotates 180 degrees, and if i write myServo.write(180), the servo rotates 180 degrees but in the other direction. How can i make it spin in only one direcvtion(360 degrees, more than 360 degrees)?
Thanks in advance!

Normally servos are not supposed to rotate continuously. However, now you can buy some "continuous rotation" servos that do. You can even transform your own servos into continuous (but this is not a super easy manipulation); check this link: http://www.instructables.com/id/How-to-modify-a-servo-motor-for-continuous-rotatio/

@jfpoilpret: thanks, but i think you misunderstand me. I can rotate the servo manually. So basicly it can be rotated continuasly, i just don't know how to code it. Or is there something else i need to do?

If this was a continuous servo, that would be indicated in the link you mentioned, and using Servo library would work with it, except that the value passed to myServo.write() would not specify an angle but a rotation speed, making it turn forever, until myServo.write(90). The fact you can force it turn more than 360° does not mean it can do it programmatically.

@jfpoilpret: thank you! I thought if i can turn it around manually means that it is a continuous servo. So i have to solder and hopefully it will work then.


text:
Arduino Ethernet Shield vendor is null
I bought Ethernet Shield for Arduino Uno! from AliExpress. It is good work but I scanned my network with Fing and device Vendor name is null.
Can I change/set device Vendor?
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 106 };

void setup()
{
  Ethernet.begin(mac, ip);
}

The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software.  Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.
Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.
And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.
Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.
If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.


text:
Arduino Yun RFID-RC522 module not working
I have tried to use Arduino Uno with RFID-RC522 module. It is good work[1] and read rfid cards. But Arduino Yun doesn't work with RFID-RC522 module.
What is diffrent Uno and Yun?
1- http://www.grantgibson.co.uk/2012/04/how-to-get-started-with-the-mifare-mf522-an-and-arduino/

According to the link you provided, we can see that the RFID-RC522 uses SPI to communicate with Arduino.
On Arduino UNO, the SPI pins are located as follows:

pin 11: MOSI,
pin 12: MISO,
pin 13: SCK

On the Arduino YUN, this is different though; as stated there (bold highlight is mine):

SPI: on the ICSP header. These pins support SPI communication using
  the SPI library. Note that the SPI pins are not connected to any of
the digital I/O pins as they are on the Uno, They are only available
  on the ICSP connector. This means that if you have a shield that uses
  SPI, but does NOT have a 6-pin ICSP connector that connects to the
  Yún's 6-pin ICSP header, the shield will not work.

Hence you can not wire the RFID-RC522 module the same on UNO and Yun.
For the Yun, you'll have to follow this wiring picture:

Pin 1 in image above is the pin that is marked with a dot on the Yun PCB.
Also see the ISP-header layout, at the lower-right corner of the yun_by_pighi Yun pinout diagram.

I wired as described, (but I wired the 3.3v on the rc522 to the 3.3v on Yun, not the icsp pin because apparently the voltage isn't specified in icsp .) Unfortunately even after installing the library, successfully uploading their example, it doesn't seem to do anything - only shows a red light on the device, and blank serial monitor when tag is right on it. I think there's a step missing somewhere here.

I had the same issues Thanks for help .However I made the  following connections then above mentioned
RC522 RFID borad     Arduino YUN  (as per the github example code dumpinfo)
chip select (nss ) - Pin 10
Rst                - Pin 9
Link for Gihub RFID RC522
Hope it helps someone who is stuck


text:
How do I repeat else if (cmd == '3') until I press another cmd?
This code is for automatically opening and closing a window using a motor with senors such as dust, humidity, temperature, and rain sensor with bluetooth module through phone. With this code if I press 1,2 it would close or open the window and 3 would let the window open or close regarding the measures that the  sensor reads. Right now pressing 3  would only simulate this once and then turn off untill I press it again
So I would want this part
 else if (cmd == '3')
to repeat itself until I press another cmd button so the window keeps opening and closing.
//////////////////////////////////////////////////////////////////////////
#include <SoftwareSerial.h>
#include <Stepper.h>
#include <DHT.h>
#define DHTPIN A1
#define DHTTYPE DHT11
#define D_IN 3
#define A_IN A0

int Txpin = 7;
int Rxpin = 8;
int stepsmotor = 1024;
const int stepsPerRevolution = 64;
SoftwareSerial BTSerial(Txpin, Rxpin);
DHT dht(DHTPIN, DHTTYPE);
int measurePin = 0;          // measurePin을 0으로 설정합니다.
int ledPower = 2; // ledPower를 2로 설정합니다.
int samplingTime = 280;    // samplingTime을 280으로 설정합니다.
int deltaTime = 40;           // deltaTime을 40으로 설정합니다.
int sleepTime = 9680;       // sleepTime을 9690으로 설정합니다.
float voMeasured = 0;      // voMeasured를 0으로 설정합니다.
float calcVoltage = 0;       // calcVoltage를 0으로 설정합니다.
float dustDensity = 0;       // dustDensity를 0으로 설정합니다.

Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(9600);
  myStepper.setSpeed(550);
  pinMode(ledPower,OUTPUT);
  pinMode(D_IN, INPUT);
}

void loop()
{
 if (BTSerial.available())
  {
    char cmd = (char)BTSerial.read();
    if(cmd == '1'){
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
      }}
    else if (cmd == '2')
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
   }
    else if (cmd == '3'){
     int dIn = digitalRead(D_IN);
  double aIn = analogRead(A_IN);
    int h = dht.readHumidity();
    int t = dht.readTemperature();
digitalWrite(ledPower,LOW);
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin);
  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH);
  delayMicroseconds(sleepTime);

  calcVoltage = voMeasured * (5.0 / 1024.0);

  dustDensity = (0.17 * calcVoltage - 0.1) * 1000;

    Serial.print(dustDensity);
    Serial.println(" ug/m3");
  Serial.print("Digital Input = "); Serial.println(dIn);
  Serial.print("Analog Input  = "); Serial.println(aIn);
  Serial.println();
    Serial.print("humidity:");
    Serial.println(h);
    Serial.print("temperature:");
    Serial.println(t);
    delay(1000);

    if (t >= 25 or h >= 70 or dustDensity >= 100 or aIn <= 50)
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
    }
    else
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
    }

  delay(3000);
    }
    else if (cmd == '4'){

    }
      }
    }

Please no code as image. It is difficult to read and nobody will type the code for testing into their own computer. You already had correctly formatted code. Why did you replace it with an image?

I would suggest to rewrite your program as a Finite State Machine (FSM). It's a simple but powerful concept. You first model your program into multiple states, that are connected through state transitions. It is a good way to first draw this as a graph. You can see one example in my answer to this question.
For your case I would use your "modes" as states for the FSM plus an idle state, where simply nothing happens. You would start in the idle stat and then change to different states depending on the Serial input. In the states/modes 1 and 2, which are only one time actions, you would execute the action in the state and then directly change to the idle state again.
From the programming side a FSM can be implemented in multiple ways. I have seen FSMs using a variable and switch cases, but also FSMs, that use a function pointer. The last is elegant, but not as easy to understand for beginners. So I suggest you use the switch-case variant, as you can see in the answer linked above. Basically you use a variable (something like int or char) to represent the current state. In your loop() function you then build a switch-case statement for different values of your state variable. Often an enum is used as variable type to make the code more readable. In each case statement you write the code for the corresponding state. In your state/mode 3 you would check your sensors and close/open the window as needed, then leaving the case statement. When the next iteration of the loop() function happens, the FSM will still be in this state, checking again the sensors. In your states/modes 1 and 2 you would check, if the window already has the needed state and - if not - drive to motor to close/open the window. Then - still in the case statement - you would set the state variable to the idle state, then leave the case statement. So in the next interation of the loop() function the FSM will be in the idle state, doing nothing, making the states/modes 1 and 2 a one-shot everytime, that you activate them.
In contrast to the code in the linked answer, I would read the Serial data outside of the switch statement, since you will write directly to the state variable in there.
I strongly suggest, that you try to implement this. It is an important principle, that makes your more structural sound and easier to extent. A great learning experience.

Thanks  a bunch!


text:
trying to do a security motion sensor using the peizer and hc-sr04 but i am not able to find the errors the error code is all the way down
#define trigPin 10
#define echoPin 9
#define buzzer 12
long duration;
int distance;

void setup() {
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600);
pinMode(buzzer,OUTPUT);
}

 void loop() {
 digitalWrite(trigPin,LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin,LOW);
 duration=pulseIn(echoPin,HIGH);
 distance=duration*0.034/2;
 Serial.print("DISTANCE=");
 Serial.println(distance);
 if (distance<=15){
 tone(buzzer,450);
 delay (500);
 noTone(buzzer);
 }
 else{
 noTone(buzzer);
 }
 }

this is the error code
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

sketch_nov27a:9:15: error: stray '\342' in program

 void setup() {

               ^

sketch_nov27a:9:16: error: stray '\200' in program

 void setup() {

                ^

sketch_nov27a:9:17: error: stray '\213' in program

 void setup() {

                 ^

sketch_nov27a:9:18: error: stray '\342' in program

 void setup() {

                  ^

sketch_nov27a:9:19: error: stray '\200' in program

 void setup() {

                   ^

sketch_nov27a:9:20: error: stray '\213' in program

 void setup() {

                    ^

sketch_nov27a:14:2: error: stray '\342' in program

 }

  ^

sketch_nov27a:14:3: error: stray '\200' in program

 }

   ^

sketch_nov27a:14:4: error: stray '\213' in program

 }

    ^

sketch_nov27a:14:5: error: stray '\342' in program

 }

     ^

sketch_nov27a:14:6: error: stray '\200' in program

 }

      ^

sketch_nov27a:14:7: error: stray '\213' in program

 }

       ^

sketch_nov27a:18:14: error: stray '\342' in program

 void loop() {

              ^

sketch_nov27a:18:15: error: stray '\200' in program

 void loop() {

               ^

sketch_nov27a:18:16: error: stray '\213' in program

 void loop() {

                ^

sketch_nov27a:18:17: error: stray '\342' in program

 void loop() {

                 ^

sketch_nov27a:18:18: error: stray '\200' in program

 void loop() {

                  ^

sketch_nov27a:18:19: error: stray '\213' in program

 void loop() {

                   ^

sketch_nov27a:28:19: error: stray '\342' in program

 if (distance<=15){

                   ^

sketch_nov27a:28:20: error: stray '\200' in program

 if (distance<=15){

                    ^

sketch_nov27a:28:21: error: stray '\213' in program

 if (distance<=15){

                     ^

sketch_nov27a:28:22: error: stray '\342' in program

 if (distance<=15){

                      ^

sketch_nov27a:28:23: error: stray '\200' in program

 if (distance<=15){

                       ^

sketch_nov27a:28:24: error: stray '\213' in program

 if (distance<=15){

                        ^

sketch_nov27a:32:2: error: stray '\342' in program

 }

  ^

sketch_nov27a:32:3: error: stray '\200' in program

 }

   ^

sketch_nov27a:32:4: error: stray '\213' in program

 }

    ^

sketch_nov27a:32:5: error: stray '\342' in program

 }

     ^

sketch_nov27a:32:6: error: stray '\200' in program

 }

      ^

sketch_nov27a:32:7: error: stray '\213' in program

 }

       ^

sketch_nov27a:33:6: error: stray '\342' in program

 else{

      ^

sketch_nov27a:33:7: error: stray '\200' in program

 else{

       ^

sketch_nov27a:33:8: error: stray '\213' in program

 else{

        ^

sketch_nov27a:33:9: error: stray '\342' in program

 else{

         ^

sketch_nov27a:33:10: error: stray '\200' in program

 else{

          ^

sketch_nov27a:33:11: error: stray '\213' in program

 else{

           ^

sketch_nov27a:36:1: error: stray '\342' in program

 }

 ^

sketch_nov27a:36:2: error: stray '\200' in program

 }

  ^

sketch_nov27a:36:3: error: stray '\213' in program

 }

   ^

sketch_nov27a:36:4: error: stray '\342' in program

 }

    ^

sketch_nov27a:36:5: error: stray '\200' in program

 }

     ^

sketch_nov27a:36:6: error: stray '\213' in program

 }

      ^

sketch_nov27a:36:8: error: stray '\342' in program

 }

        ^

sketch_nov27a:36:9: error: stray '\200' in program

 }

         ^

sketch_nov27a:36:10: error: stray '\213' in program

 }

          ^

sketch_nov27a:36:11: error: stray '\342' in program

 }

           ^

sketch_nov27a:36:12: error: stray '\200' in program

 }

            ^

sketch_nov27a:36:13: error: stray '\213' in program

 }

             ^

exit status 1

stray '\342' in program

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

Nice error there. I copied your code into my Arduino IDE and also got many errors with "stray X in program".
Then I looked at the file in the text editor vim and made all non-printable characters visible (that are characters, that cannot be seen, like control characters). Here is the result (as image, so that you can see the unprintable characters)

As you see, you have some extra characters marked as <200b>. Google gives me the description for it as

zero width space

so a space character, that has zero width and is thus not visible.
The compiler doesn't know, how to interpret these characters. I removed them and the compilation succeeded. Here again your code as text without the unprintable characters (and autoformatted to make it easier to read):
#define trigPin 10
#define echoPin 9
#define buzzer 12
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  Serial.print("DISTANCE=");
  Serial.println(distance);
  if (distance <= 15) {
    tone(buzzer, 450);
    delay (500);
    noTone(buzzer);
  }
  else {
    noTone(buzzer);
  }
}

How these unprintable characters got into your code can only be guessed. Maybe you have copied parts of it from some website, which had these extra characters in it. Maybe you inserted them with some kind of text editor by accident.

For reference: The used FAQ section of vim with the commands to display non-printable characters here:

11.5. How do I highlight all the non-printable characters in a file?
You can use the following commands and search pattern to highlight all the
non-printable characters in a file:
:set hlsearch
/(\p|$)@!.
For more information, read
:help /\p
:help /bar
:help /$
:help /(
:help /@!
:help 'hlsearch'


text:
Wind speed measuring using Hall effect Anemometer
I need your help regarding a problem I am facing while measuring wind speed. In my sketch I get a reading every 20 counts which the magnet goes past the sensor. I need to change it in order to get a reading every 20 seconds. How can I do it with minimum changes to the sketch?
volatile byte revolutions;

float rpmilli;
float speed;

unsigned long timeold=0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), rpm_fun, RISING);

  revolutions = 0;
  rpmilli = 0;
  timeold = 0;
}

void loop()
{
  if (revolutions >= 20) {
    //Update RPM every 20 counts, increase this for better RPM resolution,
    //decrease for faster update

    // calculate the revolutions per milli(second)
    rpmilli = ((float)revolutions)/(millis()-timeold);

    timeold = millis();
    revolutions = 0;

    // WHEELCIRC = 2 * PI * radius (in meters)
    // speed = rpmilli * WHEELCIRC * "milliseconds per hour" / "meters per kilometer"

    // simplify the equation to reduce the number of floating point operations
    // speed = rpmilli * WHEELCIRC * 3600000 / 1000
    // speed = rpmilli * WHEELCIRC * 3600

    speed = rpmilli * 0.6597 * 3600;

    Serial.print("RPM:");
    Serial.print(rpmilli * 60000);
    Serial.print(" Speed:");
    Serial.print(speed);
    Serial.println(" kph");
  }
}

void rpm_fun()
{
  revolutions++;
}

You can use the millis() function to measure time intervals and do things regularly in these intervals. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE, or to one of the many tutorials for the millis() function on the web.
Basically you will need to do the following:

Declare a timestamp variable to hold the time when the data was displayed last time (in global scope):
 unsigned long timestamp = 0;

Declare the interval, that you want the display to happen in:
 #define DISPLAY_INTERVAL  20000

In your if statement check if the time difference between now and the timestamp is bigger than the interval
 if(millis() - timestamp > DISPLAY_INTERVAL){

Note that you should do millis() comparisons always this way (by calculating the difference), so that the rollover of millis() will not affect the result.