text:
Can RX and TX be temporarily transposed on demand?
Only 2 arduinos can normally be linked via serial port because TX and RX need to be cross-linked, and connecting multiple TXs together would cause conflict.
RS485 allows multiple nodes connected in parallel on a 2 wire differential 'bus', using a TX ENABLE pin to allow one master to transmit while all other slaves listen.
I suspect it should be possible to similarly connect multiple serial RXs together to give a common listening bus, and be able to use TX ENABLE on any one node at a time to transpose its RX and TX to allow its TX to transmit to the other RXs. This might be physically done using a changeover relay swapping RX with TX, but is it possible to somehow temporarily switch the TX and RX assignments on demand by software?
I doubt the actual pin assignments can be changed in-situ, but perhaps the same results are achievable with some programming wizards sleight-of-hand trickery?

What about SPI? That's designed for single-master multi-slave. Perhaps you could explain what you're trying to achieve in greater detail.

I am trying to create a text-based arduino clustering system for circumventing arduino resource limitations, which I try to explain in this link...
http://arduino.stackexchange.com/questions/19608/arduino-cluster-functionality-feasibility-advice-for-arduinos-to-communicate-u

How much do you know about network protocols? What it seems that you need answers an age-old situation of multiple nodes with interlinked communication. This is answered todaywith Ethernet as the 'default' machine to machine link, but there have been several iterations of network communications/protocols/topology. Start with ALOHA, and then maybe Token Ring. Working through the timeline of network comms I'm sure you'll find something that balances your needs versus advantages/disadvantages.

TX and RX pins are fixed to the hardware, so you can't swap assignments (Assuming Arduino Uno here). You could try softwareSerial, if you want a software only solution. Or do something like this half-duplex UART

You can try by connecting RX and TX together and then setting the TX in high impedance with pinMode(1,INPUT). If this does not work (because the atmega overrides that), you can just put a tristate buffer on the TX pin. Or, better, a SPDT analog switch: it's the same as the "changeover relay", except that it is integrated. An example is the Analog ADG839, but there are tons of that.

I don't know much at all about protocols, I'm just trying to implement an easy method of sharing functionality between several arduino compatable nodes (possibly including ESPs) that requires using the least resources on each node, and with my limited knowledge and experience it seems that Nick Gammons RS485 library may offer me the best chance for achieving those goals. Thank you all for your helpful comments and advice, it makes exploring the unknown a much less daunting experience.

@frarugi87: Yes, the ATmega overrides your pin mode. C.f. the datasheet: “When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.”

@EdgarBonet yes, but in the PortManipulation page on the Arduino wiki they say It would be very easy to accidentally cause your serial port to stop working by changing pin 0 into an output pin!. So I think that when you enable the serial port it modifies the pin mode, but then you can modify it. Or not? This should be investigated ;)

@frarugi87: You think wrong. And it appears that the authors of that page do not know what they are writing about... and they did not try either! Atmel seems to know better how they chips behave.

@EdgarBonet it looks like you are right... Of course Atmel knows their chip better, but that sentence could also be interpreted as "when you enable it, it turns the pin to output" instead of "when it is enabled the pin is forced to be an output". It appears that the author of that page should fix that ;)

On an AVR-based Arduino, you can selectively enable the transmitter and
receiver side of the UART (c.f. the datasheet of your MCU). Thus, you
could in principle just connect all the TX and RX together, and make
sure only one transmitter is enabled at a time, while all the others are
in high impedance. If you do this, I would strongly recommend you put a
current-limiting resistor in series with each TX, just in case.
For example, on an Arduino Uno
(Atmega328P),
you can use the following functions:
static inline void enable_tx()  { UCSR0B |=  _BV(TXEN0); }
static inline void disable_tx() { UCSR0B &= ~_BV(TXEN0); }
static inline void enable_rx()  { UCSR0B |=  _BV(RXEN0); }
static inline void disable_rx() { UCSR0B &= ~_BV(RXEN0); }

Edit: Beware that Serial.begin() enables both the transmitter and
the receiver.

Thank you Edgar Bonet, that is the type of 'wizardry' I was wondering if was possible.

It sounds to me like you are misunderstanding the purpose of the TX Enable pin and you are trying to come up with some convoluted method to do exactly what TX Enable actually does.
Under normal circumstances, in RS485, the UART's RX pin is connected to the bus.  When TX Enable is asserted the RX pin is disconnected and the TX pin is connected, thus allowing any node on the bus to be a transmitter and all the other nodes a receiver.
The main thing to watch out for though is that only one node is ever a transmitter at a time, otherwise you get a collision which means that the data is completely garbled.
The simplest way of stopping that happening is to have one node nominated as the master and all the other nodes as slaves.  The master first initiates communication by making a request to a slave.  The slave will then respond with data (it becomes the transmitter and the master a receiver) to send data to the master.  That way the only node that is a transmitter is either the master making the request, or the slave that is responding to a request.
If you want "random" peer-to-peer communication where any node could become a transmitter at any time it becomes a whole lot more complex.  There are things you should implement to try to avoid, or deal with, collisions, including monitoring the bus and only transmitting after a certain amount of idle time has been detected, reading the bus while writing to it (requires more hardware) and confirming that the data you read from the bus is the same as the data you wrote to the bus, and random delays before retrying a failed communication.  That last one is probably the trickiest to get right, since random numbers on Arduinos aren't really random unless you "seed" them from a truly random source. You don't want both ends delaying for the same amount of time to retry otherwise it will never complete.

Since you apparently want to achieve that kind of thing but without using RS485, it all gets much more complex.
No, you cannot "swap" the functionality of the TX and RX pins in the Arduino.  BUT you can do serial communication (albeit somewhat heavyweight) using pure software.  Take a look at the SoftwareSerial library - you will most likely need to make modifications to that to achieve what you want.
To do it externally with hardware is possible, but the end result will most likely be more complex than just using a simple RS485 interface chip which are very inexpensive and easy to get hold of.
Yes, you could use relays (clunky) or buffers, or multiplexers, etc, but why would you when RS485 does what you want?

No, what I am trying to do is achieve the same sort of master/slave multi-node capability as RS485, but WITHOUT using RS485, just using the standard serial port TX and RX.

Ah, I see. Your question wasn't clear at all. You should make it more explicit in your question.

It was just a thought that popped into my head when I discovered my batch of RS485 interfaces came as conjoined siamese twins which I cannot snap apart even after scoring the join with a sharp blade, so I must now try to carefully hacksaw them apart.
If it was possible to achieve similar RS485 multi-node capability via software using the standard serial RX and TX it could have made my initial steps for developing arduino cluster capability using Nick Gammons RS485 library a liitle bit less 'hardwarey' is all, and perhaps may even have made the clunky little interfaces unnecessary.


text:
"EVERY_N_MILLISECONDS"
One of the FastLED examples that I've seen was using code that looks like this:

EVERY_N_MILLISECONDS( 300 ) { transition_step(); }

I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.
A Google search finds no reference anywhere at all.
I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?

Yes, it is defined in the FastLED library.  It is a preprocessor macro which is replaced by a block of code when compiled:
It is a very convoluted bit of preprocessing code that is difficult (even for me) to follow through with lots of concatenations and multiple layers of definition, so my advice is to just not worry about it and just use it.
If you want to try and decypher it all it's in the file lib8tion.h in the FastLED library.

Excellent answer, thank you Majenko. If it's that complicated then I almost certainly won't be able to decypher it without a lot of headache, I mainly wanted to be sure I wasn't misunderstanding something fundamental about the language. I'm guessing that I can't have the thing appearing twice then if it defines Functions...?

Do you happen to know if it is blocking or just a NOP if the timer has not cone yet?

As @Majenko has said it is defined in the FastLED library http://fastled.io/.  There is also EVERY_N_SECONDS.
It is not necessary to call any other FastLed function in the run loop (such as FastLED.delay()) in order to use these functions.
include <FastLED.h>

void loop() {
   ....
   EVERY_N_MILLISECONDS( <mseconds> ) {
     <your timed code here>;
   }

   EVERY_N_SECONDS( <seconds> ) {
     <your timed code here>;
   }
}

Its a macro that wraps the code you put inside of it to only be run based on the time interval you pass to it. The purpose of it is to allow for timer based code to be ran without having to block the main loop(). When the code is compiled it gets wrapped by other code that governs how the code inside it should run.
Lets say you want to run a method every 100ms. A simple approach would be the following:
// loop() runs the code within it over and over at a rate based on the
// how fast the microprocessor runs - specifically how long it takes
// for the processor to get through the code inside of it.
void loop(){

doMethod();
delay(100);

checkForButtonInput();

}

The issue here is that during the delay(), the delay() function, by its design, hogs all the processor time for 100ms, and so the checkForButtonInput() is not able to check for input, as the program is currently stuck looping inside of delay() until 100ms has passed.
EVERY_N_MILLISECONDS( <mseconds> ){} is the answer here, and you can think of it working to add code to you code like this (although this isn't exactly accurate):
void loop() {
   EVERY_N_MILLISECONDS( 100 ){
  //pseudocode
  //if ( it has been 100ms since last time we did doMethod() ) {
      doMethod();
      // reset time since we did doMethod() to 0
  //}
  //else {
  //  continue...
  //}
  }
  checkForButtonInput();
}

so if it hasn't been 100ms since the last time we were in the EVERY_N_MILLISECONDS wrapped code then we just move on, and so the checkForButtonInput() is called as much as possible and inputs wont be missed.

source: Stack Exchange

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

authors: น้ำส้ม น้ำส้ม

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

sort: votes


text:
Shift Register Not Working
I am trying to learn how to use a shift register to control 8 LEDs but for some reason my shift register is misbehaving and none of the LEDs are lighting up. I imagine that it's a problem with my wiring? I have replicated the circuit on 123D Circuits.

//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  // count from 0 to 255 and display the number
  // on the LEDs
  for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
    // take the latchPin low so
    // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(500);
  }
}

I don't see anything wrong with the image or the code. Try jiggeling all the connections. I've sometimes had wires not connecting properly in a breadboard.

Rejiggling the pins seemed to do it,

It's always the stupidest thing that takes the most time to debug (-:  Glad you got it working.

From the Arduino website:

shiftOut()
Description
Shifts out a byte of data one bit at a time. [...]
Note: if you're interfacing with a device that's clocked by rising
  edges, you'll need to make sure that the clock pin is low before the
  call to shiftOut(), e.g. with a call to digitalWrite(clockPin, LOW).

You need to pull clockPin low before each shiftOut() call, as the documentation says.
Also, you have misunderstood the behaviour of the latchPin. This can be high or low at any time; it's the change from low to high that latches the data into the output cells.

digitalWrite(latchPin, LOW); shiftOut(...); digitalWrite(latchPin, HIGH);. Isn't he doing that already?

No, clockPin should be low, according to the blurb.

Aha, clockPin; not latchPin. Missed that after you edited your answer.

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


text:
How to make two wheels turn only for a particular amount of time?
I am trying to make a robot turn (dc motors are being used) back 180 degrees. So I used an l289n for it and made one wheel turn clockwise and vice-versa.
But as I wan't it to make only a 180 degrees turn, I wanted to set an amount of time for it to turn.  Is there any other way to do the same thing, if yes, please tell, if no, help me...

delay()

@CharlieHanson how do you plan on using the delay function. It occurred to me once but it will just be like the wheels will turn for an undefined period of time and then there will be a delay.

Really? turn motor 1 CW; turn motor 2 CCW; delay for some time; turn motor 1 off; turn motor 2 off.

yea maybe thats a good idea....Thnx..

Use the delay() function.
Pseudo code as follows:
1) Turn clockwise motor on;
2) Turn counterclockwise motor on;
3) delay(<time>);
4) Turn CW motor off;
5) Turn CCW motor off.

Thank you very much....I still can't believe that this simple logic didn't occur to me :P


text:
Send data from computer to phone through bluetooth - Bluetooth SeeedStudio Shield V2.1
So I bought a Bluetooth Shield from SeeedStudio lately (V2 model) and goofed around with it a little bit. I'm using my HTC One M8 to communicate with it just to send some dummy words. Whenever I send something from my phone to the Android, it works great and I'm pleased to see it's fast too.
The code is fairly simple. I just send data from my phone, gets received to my arduino, prints it on the Arduino IDE terminal. Same thing for communication in the other way. Write something in the terminal, send it to the arduino and then, the phone. The last on doesn't work and I've tried a couple of things in the past 36 hours. Now, I'm just banging my head against the wall (literally). Here's my code (I'm sure you've seen it a couple of times before):
#include <SoftwareSerial.h>   //Software Serial Port
#define RxD 6
#define TxD 7

#define DEBUG_ENABLED  1

SoftwareSerial blueToothSerial(RxD,TxD);

void setup()
{
  Serial.begin(9600);
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  setupBlueToothConnection();

}

void loop()
{
  char recvChar;
  while(1){
    if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield
      recvChar = blueToothSerial.read();
      Serial.print(recvChar);
    }
    if(Serial.available()){//check if there's any data sent from the local serial terminal, you can add the other applications here
      recvChar  = Serial.read();
      blueToothSerial.print(recvChar);
    }
  }
}

void setupBlueToothConnection()
{
  blueToothSerial.begin(9600); //Set BluetoothBee BaudRate to default baud rate 38400
  blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
  blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
  blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
  blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
  delay(2000); // This delay is required.
  blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
  Serial.println("The slave bluetooth is inquirable!");
  delay(2000); // This delay is required.
  blueToothSerial.flush();
}

On my phone, I use a simple Bluetooth SSP to pair and communicate. Btw, something odd: I can't change the name of the bluetooth device. When I try to connect it, it shows the same name in the SSP.
Note: When I upload my code, I make sure I reset the arduino everytime. Oh and I changed the jumpers on my board to make sure it was set on the right one.
Note 2: I tried to see if the pins on the Shield (for RdX and TdX) were not starting with 0 by moving the jumpers.
Still, it's pretty odd.
Thanks in advance for any help and don't hesitate to ask me question! It's my first time here!


text:
Arduino to DAC to ADC back to Arduino?
My question is simple. Is the following possible?
I am using one Arduino Mega 2560 board and its SPI functionality to adjust voltages (0-4.096V) through a 12-bit DAC (MCP4822).
I would like to measure the output voltages from the DAC by feeding them through a 12-bit ADC and back to the Arduino. The DAC's output voltages that will be directly measured by the ADC will be displayed on an LCD and on LabVIEW.
Is this possible, given that both the DAC and the ADC have to be connected to the same SDI and SCK pins on the Arduino for SPI to work?

Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.

Perfect.. Given that the DAC and ADC have to be connected to the same SCK and SDI pins, I'm assuming that the ADC cannot update the voltages (send data) until the CS pin on the DAC is inactive (low with the MCP4822). The CS pins on both the DAC and the ADC cannot be active at the same time, correct?

That is correct. You set the DAC first then read the voltage second.


text:
DCMotorTest from the Adafruit site – got fatal error exit status 1
New to Arduino, I plugged in DCMotorTest from the Adafruit site and got this error message: a fatal error exit status 1
/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

My error message was:
Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

/Users/student/Downloads/Adafruit_Motor_Shield_V2_Library-master/examples/DCMotorTest/DCMotorTest.ino:11:34:
 fatal error: Adafruit_MotorShield.h: No such file or directory
 #include <Adafruit_MotorShield.h>
                                  ^
compilation terminated.
exit status 1
Error compiling.

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

Did you install the Adafruit_MotorShield.h library? 2. If you did, did you do it without the IDE running, or restart the IDE afterwards?

Based on the error report it seems that you have just opened the example program from the downloaded folder. In order to add library files (which includes the header files, c++ source code, etc.) you have to move the Adafruit_Motor_Shield_V2_Library-master folder to the libraries folder.

Documents > arduino > libraries

If no such folder exist, then create a new folder and name it libraries.
To check weather the libraries have been installed, open arduino IDE goto

file > example and check weather the example programs are added (you will see "adafruit" in the list)

Now, restart the arduino IDE and things should get going.
Note:
Do not use "-" and do not include space while naming a folder, as the compiler may throw up error. Instead you are free to use "_","$". Name of a folder should always start with a letter.
For more detail visit https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library


text:
ESP8266 Analog read interferes with wifi?
Short version:
I have a program that connects my ESP8266 to WIFI so I can control a relay connected to it over the internet or a button. I also have a sensor for my door. This software works perfectly, if I add a light dependent resistor to it (which is connected correctly since I do get readings from it) and start reading data I lose my WIFI connection. Has anyone got any idea why this is happening?
Long version:
So I have this program running on my Esp8266

#include <ESP8266WiFi.h>

IPAddress ip(192, 168, 0, 150);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

const char* ssid = "mySSID";
const char* password = "myPSW";
const char* host = "192.168.0.228";

const int buttonPin = 0;
const int relayPin =  4;
const int doorPin = 5;
const int ldrPin = A0;

//int ldrState;
//int serialCount = 0;
//int ldrMin = 0;
//int ldrMax = 1024;
int buttonState = 0;
int doorState = 0;
byte Main_Light_State_Begin;
bool Main_Light_State;
bool doorNotified = false;
bool button_action_taken = false;
bool Main_Light_DBR = true;
String HTTP_Get_Response;

WiFiServer server(80);

//Functions
String HTTP_Get(char* Adress, String URL, bool Last_Line_Bool) {
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(Adress, httpPort)) {
    Serial.println("connection failed");
    return "Failed";
  }

  Serial.print("Requesting URL: ");
  Serial.println(URL);
  Serial.println("at adress");
  Serial.println(Adress);
  client.print(String("GET ") + URL + " HTTP/1.1\r\n" +
               "Host: " + Adress + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  String Response;
  String Last_Line;

  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
    Response = Response + line;
  }
  return Response;

  Serial.println();
  Serial.println("closing connection");

}

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

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

  server.begin(); -
  Serial.println("Server started");

  Serial.println(WiFi.localIP());
  pinMode(relayPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(doorPin, INPUT);
//  pinMode(ldrPin, INPUT);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wifi NOT Connected");
  }
  //Sensors
  buttonState = digitalRead(buttonPin);
  doorState = digitalRead(doorPin);
  //ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  //Serial.println(analogRead(ldrPin));
//  if (serialCount == 1000) {
//    Serial.println(ldrState);
//    serialCount = 0;
//  } else {
//    serialCount ++;
//  }

  //Doorsensor
  if (doorState == HIGH) {
    if (doorNotified == false) {
      Serial.println("DOOR");
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?door_opened=true", false);
      doorNotified = true;
    }
  } else if (doorState == LOW) {
    if (doorNotified == true) {
      doorNotified = false;
      delay(500);
    }
    else {
      doorNotified = false;
    }
  }

  //Button
  if (buttonState == LOW) {
    if (button_action_taken == false) {
      if (Main_Light_State == true) {
        Serial.println("SWITCH");
        Main_Light_State = false;
        digitalWrite(relayPin, HIGH);
        delay(500);
        Main_Light_DBR = false;
      }
      else if (Main_Light_State == false) {
        Serial.println("SWITCH");
        Main_Light_State = true;
        digitalWrite(relayPin, LOW);
        delay(500);
        Main_Light_DBR = false;
      }
      button_action_taken = true;
    }
  } else if (buttonState == HIGH) {
    if (button_action_taken == true) {
      button_action_taken = false;
      delay(500);
    }
    else {
      button_action_taken = false;
    }

  }
  //Main_Light_State
  if (Main_Light_State == true) {
    digitalWrite(relayPin, LOW);
    if (Main_Light_DBR == false) {
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_on_dbr=true", false);
      Main_Light_DBR = true;
    }

  } else if (Main_Light_State == false) {
    digitalWrite(relayPin, HIGH);
    if (Main_Light_DBR == false) {
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_off_dbr=true", false);
      Main_Light_DBR = true;
    }
  }

  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  Serial.println("new client");
  while (!client.available()) {
    delay(1);
  }

  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  if (req.indexOf("/main_light/on") != -1) {
    Main_Light_State = true;
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/off") != -1) {
    Main_Light_State = false;
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/switch") != -1) {
    Serial.println("SWITCH");
    if (Main_Light_State == true) {
      Main_Light_State = false;
    }
    else if (Main_Light_State == false) {
      Main_Light_State = true;
    }
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/state") != -1) {

  } else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  client.flush();

  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  s += (Main_Light_State) ? "1" : "0";

  client.print(s);
  delay(1);
  Serial.println("Client disonnected");
}

With the lines I commented like above everything works fine. I have a light dependant resistor connected (correctly, I get correct measurements from it) to A0. From the moment on I uncomment the lines involving this LDR and thus start reading data from it I lose my wifi connection. Has anyone got any idea why this is? Thank you!

Which ESP8266? There are many versions each with different abilities and facilities.

@Majenko The one with a serial chip and power regulator on board. (Diymall NodeMCU Devkit 1.0 CP2102 IIC SPI for Apple's MAC OS https://www.amazon.co.uk/dp/B00XJG7GEK/ref=cm_sw_r_other_awd_UnhOwbBSFS1GS)

I came across this while looking for info on analogRead problems. I think the "more elegant solution" may have a couple of problems. Problem 1. If the sensor read and processing takes less than 1 ms, the loop may return and you will get multiple executions of analogRead within the same millisecond - not the desired result. Considering that analogRead(A0) itself only takes about 70 microseconds, if the processing is quick you could easily have 10 or so executions of analogRead(A0) in that millisecond. Problem 2. If there are other things goind on which take multiple millieconds to complete (eg

I have found that this was caused by reading the analog pin to many times in a short period of time. I replaced
  ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  Serial.println(analogRead(ldrPin));
  if (serialCount == 1000) {
    Serial.println(ldrState);
    serialCount = 0;
  } else {
    serialCount ++;
  }

with this:
if (serialCount == 10000) {
  ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  Serial.println(ldrState);
  serialCount = 0;
} else {
  serialCount ++;
}

Although I thought of this approach before, my mistake was that I was still reading the sensor every time the code loops, I just wasn't printing it to the serial monitor until each 100th loop.
This still gives me a reading several times per second, which is way more then I need. Anyway, now I know that I can't read my ESP8266 Analog pin to many times per second or the wifi will disconnect (at least when using it with the Arduino IDE)

This works great, just had this exact problem 4 years on. Does anyone know if this is a reported bug? It probably should be.

This is an old question that has been answered, but I would like to offer a slightly more elegant solution (IMO!):
In my method which reads the analog data, I check and only read every 50 milliseconds:
void readAnalogSensor() {
   if( millis() % 50 != 0 )
       return;
   .
   .  // Do your sensor read and processing here
   .
}

This avoids having to keep a loop count and seems more deterministic - the loop count value will not necessarily increase in a consistent fashion depending on what else is going on in the loop.  Having the millis values available is also useful if you need to implement some button debounce code.

Wow this has indeed been a while, man I should pick this project back up! This is indeed a more elegant solution, thank you!

If for some reason the main loop is very slow and the loop goes from ...49 to ...51 it causes a skipped a analogRead. That is why I find the serialCount solution more durable.

Here is what I usually do to give repetition at fixed intervals:
void readAnalogSensor(){
  if (millis()<taskTime) return; // time is not expired yet
  taskTime += 50; // set time for the following execution
  // .... more code for the task that is done every 50 ms
}

This requires an unsigned long variable taskTime. You may also use a constant instead of the 50.
taskTime should be set to some value close to millis() at the end of setup(), otherwise there will be a rapid sequence of executions while taskTime catches up with millis().

Almost correct. You forgot the Timing Rollover (https://playground.arduino.cc/Code/TimingRollover). Every 49 days, millis() rollover to zero and your will comparing a very low value (millis) against a very large one (taskTime). The right ways is always compare the difference between millis() against the interval duration in milliseconds.

Thank you. I wanted to avoid doing the arithmetic at every pass of the loop, but it seems this is not possible without causing the rollover error.

You have lot of time to spent. Don't forget that yours is the only program running. There is no reason to save cycles if you are already waiting.

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


text:
Arduino and PHP communication only work if I open the Arduino IDE
I have a problem. I try to open a channel to arduino and PHP talk, the PHP would send a command and the Arduino should answer that. It works, but only if I execute some steps before:

sudo chmod 777 /dev/ttyACM0
sudo arduino
Open the serial monitor in arduino IDE
Close the serial monitor
Now everything is ok, they can talk

The first step is ok, I really need to do this, the 2-4 seems irrelevant, but the communication do not start without it. I put one LCD in arduino to print what he receive, when I send "HEYARD" with PHP to him, the RX led blinks and the TX led also, but nothing is printed on LCD. If I do the 2-4 steps, when PHP send "HEYARD", LCD show HEYARD and arduino answer with "HEYPHP"
Anyone could help? There is some way to open it via Terminal, or, at least, open the Serial Monitor from arduino and close to see if this start

Does the PHP code set the correct baud-rate, parity etc.?

Yes, everything seems ok, the baud-rate is right, parity is "none", they can talk normally, but only if I open the serial monitor before.
I tried open the screen in terminal, but also do not worked, need to be the serial monitor.
Thank you

Try a proper terminal emulator like Minicom.

It could be that Arduino is setting the correct settings for /dev/ttyACM0, so others after it won't have to but should. Could you post the PHP code and screen command?

I tried use the minicom, until now, I could not read anything, but I will try make it start the port.

Here the setup block:
<?php
    require("php_serial.class.php");
    $serial = new phpSerial();
    $serial->deviceSet("/dev/ttyACM0");
    $serial->confBaudRate(9600);
    $serial->confParity("none");
    $serial->confCharacterLength(8);
    $serial->confStopBits(1);
    $serial->confFlowControl("none");
    $conect = mysql_connect("localhost", "root", "") or print (mysql_error());
    mysql_select_db("ANM", $conect) or print(mysql_error());
?>

And here the connection block:
<?php
    $serial->deviceOpen();
    exec("echo 'HEYARD' > /dev/ttyACM0");
    sleep(1);
    $read = $serial->readPort();
?>

stty -F /dev/ttyACM0 ignpar
stty -F /dev/ttyUSB0 ignpar

IGNPAR Ignore framing errors and parity errors.

That is what you need to fix minor framing issues.
Screen switches this by default; but NONE of the serial drivers do.
Especially when connecting PIs or BBB to Arduinos


text:
Serial Monitor Just Stops Working
I am communicating with two Arduinos with serial. The program works great for a while but then the serial monitor stops showing values in the RX code and will not work again unless the code is uploaded again. Why is this happening?
TX code:

/*
  Transmitting Code
  Reads potentiometers and sends them through serial
*/

int data [12];     // to send bytes
int start [2];

int Pin1A = A0;
int Joystick1A;  //crab

int Pin1B = A1;
int Joystick1B;  //up down

int Pin2A = A2;
int Joystick2A;   // pitch

int Pin2B = A3;
int Joystick2B;  // up down

int Pin3A = A4;   // yaw r-l
int Joystick3A;

int Pin3B = A5;
int Joystick3B;   // forward-back

unsigned char checksum0;
unsigned char checksum1;
unsigned char checksum2;
unsigned char checksum3;
unsigned char checksum4;
unsigned char checksum5;
unsigned char handshake;
unsigned char handshake2;
unsigned char handshake3;

void setup() {
  Serial.begin(4800);
  Serial1.begin(4800);
  pinMode(19, INPUT);
  pinMode(18, OUTPUT);
}

void loop() {

// READ THE POTENTIOMETERS:

  Joystick1A = analogRead(Pin1A);   // reads the value of the potentiometer (Joystick1Aue between 0 and 1023)
  data[0] = Joystick1A & 0xFF; //least significant 8 bit byte
  data[1] = (Joystick1A >> 8); //most significant 2 bits

  Joystick1B = analogRead(Pin1B);
  data[2] = Joystick1B & 0xFF;
  data[3] = (Joystick1B >> 8);

  Joystick2A = analogRead(Pin2A);
  data[4] = Joystick2A & 0xFF;
  data[5] = (Joystick2A >> 8);

  Joystick2B = analogRead(Pin2B);   // reads the value of the potentiometer (Joystick1Aue between 0 and 1023)
  data[6] = Joystick2B & 0xFF; //least significant 8 bit byte
  data[7] = (Joystick2B >> 8); //most significant 2 bits

  Joystick3A = analogRead(Pin3A);
  data[8] = Joystick3A & 0xFF;
  data[9] = (Joystick3A >> 8);

  Joystick3B = analogRead(Pin3B);
  data[10] = Joystick3B & 0xFF;
  data[11] = (Joystick3B >> 8);

// CREATE CHECKSUMS:

  checksum0 = ~(data[0]+data[1]) + 1;

  checksum1 = ~(data[2]+data[3]) + 1;

  checksum2 = ~(data[4]+data[5]) + 1;

  checksum3 = ~(data[6]+data[7]) + 1;

  checksum4 = ~(data[8]+data[9]) + 1;

  checksum5 = ~(data[10]+data[11]) + 1;
// WRITE VALUES AND CHECKSUMS TO SERIAL:

while (Serial1.available()<3) {
  ; //wait for request from receiver
}
  handshake = Serial1.read();
  handshake2 = Serial1.read();
  handshake3 = Serial1.read();

  if ((handshake == 1) && (handshake2 == 2) && (handshake3 == 3)) {

Serial1.write(1);

  Serial1.write(data[0]);
  Serial1.write(data[1]);
    Serial1.write(checksum0);

  Serial1.write(data[2]);
  Serial1.write(data[3]); //bytes sent
    Serial1.write(checksum1);

  Serial1.write(data[4]);
  Serial1.write(data[5]);
    Serial1.write(checksum2);

  Serial1.write(data[6]);
  Serial1.write(data[7]);
    Serial1.write(checksum3);

  Serial1.write(data[8]);
  Serial1.write(data[9]); //bytes sent
    Serial1.write(checksum4);

  Serial1.write(data[10]);
  Serial1.write(data[11]);
    Serial1.write(checksum5);

Serial1.write(2);

   delay(10);     // delay in between reads for stability
  }

// VIEW IN SERIAL MONTIOR:

}

RX code:
/*
  Receving Code
  Reads bytes from Transmitting Code and put thems back together
  Applies the read bytes to our motor control board
*/

unsigned char val[12];    // variable to read the value from the analog pin
int Joystick1A;      // 0-1024 received from serial
int Joystick1B;
int Joystick2A;
int Joystick2B;      // 0-1024 received from serial
int Joystick3A;
int Joystick3B;

unsigned char checksum0;
unsigned char checksum1;
unsigned char checksum2;
unsigned char checksum3;
unsigned char checksum4;
unsigned char checksum5;
unsigned char FirstByte;
unsigned char LastByte;

unsigned char checkit0;
unsigned char checkit1;
unsigned char checkit2;
unsigned char checkit3;
unsigned char checkit4;
unsigned char checkit5;

//ALL MOTORS:
int V1Direction = 31;
int V1PWM = 2;     //MOTOR V1
int V1Motor;

int V2Direction = 33;
int V2PWM = 3;     //MOTOR V2
int V2Motor;

int V3Direction = 35;
int V3PWM = 4;     //MOTOR V3
int V3Motor;

int V4Direction = 37;
int V4PWM = 5;     //MOTOR V4
int V4Motor;

int H1Direction = 39;
int H1PWM = 6;     //MOTOR H1
int H1Motor;

int H2Direction = 41;
int H2PWM = 7;     //MOTOR H2
int H2Motor;

int H3Direction = 43;
int H3PWM = 8;     //MOTOR H3
int H3Motor;

int H4Direction = 45;
int H4PWM = 9;     //MOTOR H4
int H4Motor;

void setup() {
  Serial.begin(4800);
  Serial1.begin(4800);
//  Serial1.begin(4800);
  pinMode(10, INPUT);
  pinMode(18, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  delay(1000);
}

void loop() {

  Serial1.write(1);
  Serial1.write(2);
  Serial1.write(3);

  if (Serial1.available()>18) {

  FirstByte=Serial1.read();

  if (FirstByte == 1) {
    val[0]=Serial1.read();         // least significant 8 bits
    val[1]=Serial1.read();         // most significant 2 bits
     checksum0=Serial1.read();     // checksum

    val[2]=Serial1.read();
    val[3]=Serial1.read();
     checksum1=Serial1.read();

    val[4]=Serial1.read();
    val[5]=Serial1.read();
     checksum2=Serial1.read();

    val[6]=Serial1.read();         // least significant 8 bits
    val[7]=Serial1.read();         // most significant 2 bits
     checksum3=Serial1.read();     // checksum

    val[8]=Serial1.read();
    val[9]=Serial1.read();
     checksum4=Serial1.read();

    val[10]=Serial1.read();
    val[11]=Serial1.read();
     checksum5=Serial1.read();

   LastByte = Serial1.read();

// get the checksum last

    checkit0 = val[0]+val[1]+checksum0;
    checkit1 = val[2]+val[3]+checksum1;
    checkit2 = val[4]+val[5]+checksum2;
    checkit3 = val[6]+val[7]+checksum3;
    checkit4 = val[8]+val[9]+checksum4;
    checkit5 = val[10]+val[11]+checksum5;

if (LastByte == 2) {
  if (checkit0==0)  {
    Joystick1A = val[1]<<8 | val[0]; }

  if (checkit1==0)  {
    Joystick1B = val[3]<<8 | val[2]; }

  if (checkit2==0)  {
    Joystick2A = val[5]<<8 | val[4]; }

  if (checkit3==0)  {
    Joystick2B = val[7]<<8 | val[6]; }

  if (checkit4==0)  {
    Joystick3A = val[9]<<8 | val[8]; }

  if (checkit5==0)  {
    Joystick3B = val[11]<<8 | val[10]; }

}
else (Serial.println("Goodbye"));
    Serial.print(Joystick1A);
    Serial.print(" ");
    Serial.print(Joystick1B);
    Serial.print(" ");
    Serial.print(Joystick2A);
    Serial.print(" ");
    Serial.print(Joystick2B);
    Serial.print(" ");
    Serial.print(Joystick3A);
    Serial.print(" ");
    Serial.println(Joystick3B);
    delay(10);

  }
  }
  }

Please edit question and tell what happens in the following cases: (a) restart serial monitor (ie exit from it then restart it; (b) push reset button on the Mega; (c) replug USB cables (ie unplug them and then plug in again).  Also, please edit question and indicate whether you are referring to serial communications via USB link, whether each Arduino is plugged into a USB port, etc.

And when does it stop? Is it always at the end of a cycle, or is it at a random point half way through? Also, how long does it work for before it fails - is it the same each time?

You might want to think about refactoring you code by using loops it will make it easier to track down the fault.


text:
Changing how a longpress is executed
I have an RGB LED common Anode attached to my Uno and this code detects a long press to turn the LED on and off.  Short presses cycle through colors, then off.
The problem is that a longpress is 2+sec, but it doesn't register until I release the button.  How would I set this up to execute the code at 2sec regardless of whether the button is released?
It's probably not worth my time if it requres too much modification.  I have a working item, it's just not... ideal.
Xhunsigned long keyPrevMillis = 0;
const unsigned long keySampleIntervalMs = 25;

int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int LEDcolor=0; // 0=White, 1=Red, 2=Green, 3-Blue, 4=Yellow, 5=Purple, 6=Pink, 7=Orange, 8=Off
int LEDstatus =0; //0=Off, 1=On
int changed =0; //has the LEDstatus just changed?
byte longKeyPressCountMax = 80;    // 80 * 25 = 2000 ms
byte longKeyPressCount = 0;

byte prevKeyState = HIGH;         // button is active low
const byte keyPin = 2;            // button is connected to pin 2 and GND

// called when button is kept pressed for less than 2 seconds
void shortKeyPress()
{
   Serial.println("short");
   if (LEDstatus==1)
   {
      LEDcolor = LEDcolor +1;
      if (LEDcolor==0) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 0);Serial.println("White");}
      if (LEDcolor==1) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Red");}
      if (LEDcolor==2) {analogWrite(redPin, 255);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Green");}
      if (LEDcolor==3) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 0);Serial.println("Blue");}
      if (LEDcolor==4) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Yellow");}
      if (LEDcolor==5) {analogWrite(redPin, 175);analogWrite(greenPin, 255);analogWrite(bluePin, 175);Serial.println("Purple");}
      if (LEDcolor==6) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 155);Serial.println("Pink");}
      if (LEDcolor==7) {analogWrite(redPin, 5);analogWrite(greenPin, 215);analogWrite(bluePin, 255);Serial.println("Orange");}
      if (LEDcolor==8) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Off");LEDstatus=0;}
   }
}

// called when button is kept pressed for more than 2 seconds
void longKeyPress()
{
   Serial.println("long");
   if (LEDstatus==0 && changed==0)
   {
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
      LEDcolor=0;
      changed=1;
      LEDstatus=1;Serial.println("On");
   }
   if (LEDstatus==1 && changed==0)
   {
      analogWrite(redPin, 255);
      analogWrite(greenPin, 255);
      analogWrite(bluePin, 255);
      LEDcolor=0;
      changed=1;
      LEDstatus=0;Serial.println("Off");
   }
   changed=0;
}

// called when key goes from not pressed to pressed
void keyPress() {
   Serial.println("key press");
   longKeyPressCount = 0;
}

// called when key goes from pressed to not pressed
void keyRelease() {
   Serial.println("key release");

   if (longKeyPressCount >= longKeyPressCountMax) {
      longKeyPress();
   }
   else {
      shortKeyPress();
   }
}

void setup()
{
   Serial.begin(9600);
   pinMode(keyPin, INPUT);
   digitalWrite(keyPin, HIGH);
   pinMode(redPin, OUTPUT);
   pinMode(greenPin, OUTPUT);
   pinMode(bluePin, OUTPUT);
   analogWrite(redPin, 255);
   analogWrite(greenPin, 255);
   analogWrite(bluePin, 255);
}

void loop() {
// key management section
   if (millis() - keyPrevMillis >= keySampleIntervalMs) {
      keyPrevMillis = millis();

      byte currKeyState = digitalRead(keyPin);

      if ((prevKeyState == HIGH) && (currKeyState == LOW)) {
         keyPress();
      }
      else if ((prevKeyState == LOW) && (currKeyState == HIGH)) {
         keyRelease();
      }
      else if (currKeyState == LOW) {
         longKeyPressCount++;
      }

      prevKeyState = currKeyState;
   }
}

The button watcher will have to become aware of time, or be able to be alerted that the short-press time has been exceeded. How much trouble and whether it's worth it is up to your own cost (labor) vs. benefit preference, but it's probably a worthwhile learning exercise.

I've rewritten the code entirely. Not that yours was terrible, it was just easier for me to start from scratch. You are left with a very empty loop(), which I always prefer.
The code contains three 'colours' and an OFF state. You can add as many other colours as you wish: add an enumeration to _LED_STATE and then add a corresponding case(<NEW_COLOUR>) statement in LEDcontrol(). I haven't included any analogWrite() functions - or in fact any declarations for the LED pins at all - because I'm a little too lazy but it should be obvious where to put them within the case statement.
Note that in the final case() statement, the LED state is changed from green to off. This means that a short press will turn the LED off after it has cycled through all the other colours, but will stay off until a long press. If you only want long pressed to switch off/on, change line 103 to eLED_STATE = _LED_STATE_RED;, or whichever the first colour is.
#define btn 3   // button pin

#define SHORT_PRESS 100     // useful for debouncing, can be changed
#define LONG_PRESS  2000    // defines how long a 'long press' is
#define CYCLE       false
#define SHOW        true

//--// You can add new colours in this enum block
enum _LED_STATE
{
    _LED_STATE_OFF,
    _LED_STATE_RED,
    _LED_STATE_BLUE,
    _LED_STATE_GREEN
};

_LED_STATE eLED_STATE = _LED_STATE_OFF;

void setup()
{
    pinMode(btn, OUTPUT);
    LEDcontrol(SHOW);
}

void loop()
{

    if (digitalRead(btn))
        btnPressed();
}

void btnPressed()
{
    unsigned long tStart = millis();

    //--// Loop continuously while button is pressed
    while (digitalRead(btn))
    {
        //--// If LONG_PRESS is exceeded...
        if (millis() > tStart + LONG_PRESS)
        {
            //--// If LED is off, turn it on
            if (eLED_STATE == _LED_STATE_OFF)
                eLED_STATE = _LED_STATE_RED;        // Choose 'starting' colour
            //--// If LED is on, turn if off
            else
                eLED_STATE = _LED_STATE_OFF;
            //--// Update LED to display new eLED_STATE
            LEDcontrol(SHOW);
            //--// Now loop here until button is released
            while (digitalRead(btn));
        }
    }

    //--// If button is released in between the two press times
    if ((millis() > tStart + SHORT_PRESS) && (millis() < tStart + LONG_PRESS))
    {
        //--// Ignore if LED is off         ////// REMOVE ////////////////////
        if (eLED_STATE == _LED_STATE_OFF)   ////////// IF ////////////////////
            return;                         ///////////// NECESSARY //////////

        //--// Change the LED colour
        LEDcontrol(CYCLE);
        //--// Update LED to display new eLED_STATE
        LEDcontrol(SHOW);
    }

    //--// This helps to debounce; experiment with it
    delay(10);
}

void LEDcontrol(bool SHOW_OR_CYCLE)
{
    switch (eLED_STATE)
    {
        case(_LED_STATE_RED) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it red
                return;
            }
            eLED_STATE = _LED_STATE_GREEN;
            return;
        }
        case(_LED_STATE_GREEN) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it green
                return;
            }
            eLED_STATE = _LED_STATE_BLUE;
            return;
        }
        case(_LED_STATE_BLUE) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it blue
                return;
            }
            //--// What happens after last colour? Next colour or OFF?
            eLED_STATE = _LED_STATE_OFF;
            return;
        }
        case(_LED_STATE_OFF) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it black
                return;
            }
            eLED_STATE = _LED_STATE_RED;
            return;
        }
    }
}


text:
Could I use metal buttons as a capacitive button for my arduino project?
Could I use something like this as a capacitive button for my arduino project?
http://www.banggood.com/10pcs-25mm-Vintage-Round-Metal-Buttons-Craft-Scrapbooking-Sewing-Suit-Shirt-Button-p-1011485.html
If I connect it into something like this... http://www.banggood.com/MPR121-Capacitive-Touch-Sensor-Module-For-Raspberry-Pi-Arduino-p-969002.html
Would that make that button a capacitive button? Or am I totally barking up the wrong tree here?
Thanks :)

What type of wires are you going to use? Wearable design? You might be able to do capacitive button detect directly without the module. Use an analog pin and a 1-10 M resistor, and some software. http://tuomasnylund.fi/drupal6/content/capacitive-touch-sensing-avr-and-single-adc-pin

I don't know. When I designed a capacitive button the IC I used required a metal plane with a dielectric, and you had to touch the dielectric (so you created a capacitor between the metal plane and your finger). Maybe there are other capacitive button controllers that require direct metal...

Yes, that would work.
The only thing to watch out for is that the buttons might be plastic with a thin layer of metal on top (Chemical vapor deposition).


text:
How to read bitmap image on Arduino
I want to convert a bitmap into binary array. My bitmap image is 272*208 pixel monochromatic 1bpp image. I'm confused when the width I get from my image is 16 instead of 272, the height is corrected. And when I skip the bitmap header to get bitmap infomation, I got string of meaningless number in my text file.
#include <SPI.h>
#include <SD.h>
#include <TFT.h>

File bmpImage;
File textFile;

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

Serial.print("Initializing SD card...");
if (!SD.begin(53)) {
  Serial.println("initialization failed!");
  return;
}
Serial.println("initialization done.");
int height = 0;
int width = 0;

// Open
bmpImage = SD.open("Circle.bmp", FILE_READ);
textFile = SD.open("test.txt", FILE_WRITE);

bmpImage.seek(0x12);// width in pixel = 16
width = bmpImage.read();
bmpImage.seek(0x16);// height in pixel = 208
height = bmpImage.read();
Serial.println(width);
Serial.println(height);

int imageSize = height*width;

bmpImage.seek(0x36);//skip bitmap header

for(int i = 0; i < height; i ++) {
  for (int j = 0; j < width; j ++) {
    textFile.write(bmpImage.read());
    textFile.write(" ");
  }
  textFile.write("\n");
}

bmpImage.close();
textFile.close();

Serial.println("done write");
}

void loop()
{
  // nothing happens after setup
}

That was a very raw way of trying to read a BMP file. There are a lot of assumptions that might give errors.

The file is a BMP file. The header signature is not checked.
The image offset is assumed to be directly after the file header. It is not read.
The image width is less than 256. Only the lowest byte of the 32-bit image width is read. As 272>256 the low byte is 16.
The image height is less than 256. Only the lowest byte of the 32-bit image height is read.

It is a small bitmap but it will take a very long time to read when reading a single byte at a time. There are methods to improve performance but that is an answer to another question.
A more robust method to read the BMP header and image information is to define them as a struct and read.
struct bmp_file_header_t {
  uint16_t signature;
  uint32_t file_size;
  uint16_t reserved[2];
  uint32_t image_offset;
};

struct bmp_image_header_t {
  uint32_t header_size;
  uint32_t image_width;
  uint32_t image_height;
  uint16_t color_planes;
  uint16_t bits_per_pixel;
  uint32_t compression_method;
  uint32_t image_size;
  uint32_t horizontal_resolution;
  uint32_t vertical_resolution;
  uint32_t colors_in_palette;
  uint32_t important_colors;
};

bmpImage = SD.open("Circle.bmp", FILE_READ);
...
// Read the file header
bmp_file_header_t fileHeader;
bmpImage.read(&fileHeader, sizeof(fileHeader));
...
// Check signature
...
// Read the image header
bmp_image_header_t imageHeader;
bmpImage.read(&imageHeader, sizeof(imageHeader));
...
// Check image size and format
...
// Locate the pixels
bmpImage.seek(fileHeader.image_offset);

The file and image information are stored in little-endian so that works just fine on an AVR.

First of all I suggest you to read the full specification of the bmp file header (for instance on wikipedia).
Particularly see that

You can have a color table (palette): consequently the starting address of the bitmap data CAN not be 0x36
The pixels are not stored one per byte, but can be packed (see Pixel storage)
There are different type of headers
Width and Height are 4 byte integers, so your width is fine (272 = 256 + 16)

This said, if your bitmap has a standard BITMAPINFOHEADER header, and if your bitmap has a 24 bit standard coding (16 millions of colors) you can do something like this:
int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result;
}

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    File bmpImage = SD.open("Circle.bmp", FILE_READ);
    File textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}

The text output of this should be a file with an array of strings like R10G100B25, where R is the red component of the pixel, G is the green component and B the blue one.
Now, this is only compatible with the 24bpp format. If you want to support more formats you will need to read the specs and code them.
Let me know if this works for you

Or you could keep your old code with some adjustments, if you just want to read your image without bothering with too many checks.
Change the type of imageSize to unsigned long.
The height and width are 4-byte fields, so a single read() wont cut it. You have to declare the height and width as long or int32_t variables and then read 4 bytes at each offset, while using bit shifting to assemble the bytes into one number and remembering that it's little endian.
Something like this:
long width |= bmpImage.read();
width |= (long)(bmpImage.read()) << 8;
width |= (long)(bmpImage.read()) << 16;
width |= (long)(bmpImage.read()) << 24;

Repeat this to get the height but use abs() to get the absolute value since its usually negative.
You can also check for a colour table; usually the ColorDepth field is a good indicator (offset 28); if its less than 16, then you should expect a colour table. But if you know this already, you can skip it and get to the start offset, usually 0x36.
Your current code doesnt take the padding into account (even though your image doesn't have any padding) and it also isnt using the actual image width in bytes. To get this width, assuming the BMP uses RGB888 24 bits per pixel:
width = ((width * 24) + 31) / 32;
width *= 4;

With this, you can now read each row, though its usually arranged bottom-up. However, you arent writing properly to the file. You should use textfile.print() and not write(); the former will write the decimal value of each byte to your file while the latter will write the exact un-encoded byte to the text file, which would result in a lot of gibberish when you try to display the file's contents, say on Notepad, since the range of printable characters (under default ASCII encoding) is between 32 - 127 and your image probably has lots of bytes outside that range.


text:
Is Arduino uno SPI comunication can be also master and slave in the same time?
Is Arduino uno SPI comunication can be also master and slave in the same time?
OR master 2 slaves in the same time?
I want to recevice data from a sensor and display on OLED (all data transfer with SPI bus)
Can I master those two device (sensor & OLED) in the same time? (with SS pin to select slave )
OR Can I be both slave(recevices the data from sensor) and master (sent data to OLED) in the same time ?
What should I do ? and How can I do?
(I read the SPI example code on the Official website , but I still have no ideal about it)

See my post about using SPI on the Arduino

You can have several devices on an SPI bus. Each must have a chip select. The Arduino SS pin (Uno pin 10) is often used for chip select. Chip select pins should then be in output mode.
Connect the sensor and display to the SPI bus (MOSI, MISO, SCK) and use a chip select pin for each.
A driver (library) for a device connect to the SPI bus will typically assert the chip select pin and transfer commands and data. The SPI transfer is both read and write at the same time.

Thanks a lot for your rely.  !! Do you have any reference code or example code ...I still have no ideal about how to implement.

Start by reading this tutorial. https://learn.adafruit.com/monochrome-oled-breakouts/wiring-1-dot-3-128x64

SPI is bi-directional, so sending data or receiving data doesn't indicate if it's a master or a slave.
The master is the one that initiates the communications, that's all. So the arduino is a master in both cases. The master send data to the OLED. The master requests data from the sensor.

Thanks a lot about your answer ! I got it.  But can I ask you more about this condition ? What example code should I read,I still  have no ideal about how to implement this system.


text:
How to dim background LEDs on TFT display with ILI9341
I have bought a 2.5" TFT shield online, which is equipped with the ILI9341 controller. I need to dim the intensity of the background LEDs to match ambient light.
This particular shield does not provide a pin to control the intensity of the LEDs with PWM via a separate input, so I need to dim the background LEDs of this display via software.
The zip file with the libraries can be downloaded here.
Does one of you know how can issue a command to the TFT display to dim the background LEDs?
Thanks in advance!
UPDATE 1:
I wrote a new function to set the display's brightness by controlling the background LEDs, but something is missing as I can seem to be writing correctly to the display. So I'm trying to get the display to answer to a known command first, like 0x28 (Display Off).
The new function is defined in Adafruit_TFTLCD.cpp:
// Set display brightness (background LED's)
void Adafruit_TFTLCD::setDisplayBrightness(uint8_t x) {
  // Try with 0x28 (Display Off) to see if display reacts
  writeRegister8(0x28, 0);
  return;
}

The function prototype is defined in Adafruit_TFTLCD.h
// New functions
void setDisplayBrightness(uint8_t x);

Then I call the function in my main loop. To make sure, I first write some rectangles on screen, wait 5 seconds, then fill the screen with blue, call the new function and enter an endless loop so no other commands can interfere:
  tft.fillScreen(BLUE);
  tft.setDisplayBrightness(10); // Which really is command 0x28 to test

Any clues what I might be missing?
Thanks!
UPDATE 2:
I got so far as to have the ILI9341 react to some commands, but not all the time, and not to all commands. I suspect there is something in the way you issue the commands that I'm missing( timing?, sequence?, other?)
Here is what I have found out so far:
I can get the display to react to the Display Off command (0x28), but only when I issue it in the begin(..) function. So, the original code in Adafruit_TFTLCD.cpp is like this:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);

If I change it to the following the display reacts by remaining white:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
writeRegister8(ILI9341_DISPLAYOFF, 0); // Display off is declared as 0x28
delay(500);

So, I have a reaction to command 28h.
Then I tried function 0x51 like this in the begin(...) function:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);
writeRegister8(0x51, 0x80); // Test command 0x51 - background intensity
delay(500);

To no effect :-(
I even added command 0xBE (background PWM frequency) to see if it had any effect, but nothing :-(
void Adafruit_TFTLCD::begin(uint16_t id) {
  ...
  writeRegister8(ILI9341_DISPLAYON, 0);
  writeRegister8(0xbe, 0x80);
  delay(500);
  writeRegister8(0x51, 0x0);
  delay(500);

Also if I issue the 0x28 command:
writeRegister8(ILI9341_DISPLAYOFF, 0)

elsewhere in Adafruit_TFTLCD (e.g. in FillScreen, Fill Rect etc, it doesn't work either).
Any ideas? They would be highly appreciated!

What shield? We need to know that to know if it is even possible. The ILI9341 doesn't provide back-light control like chips such as the SSD1963 does, so you can't do it with the driver. If it is hard wired to +5V you are out of luck.

Other than command 0x51?

Ok, that's a new one on me. I was going on my experience of other ILI chips and this is the first I have seen with an LED driver in it. TBH I haven't used a 9341 display, only a 9340. It's a display I have been meaning to get hold of to implement in DisplayCore but just not got round to it.  Ok, so ignore that comment about no control - there may be control if it is used, and the library may be able to do it or be changed to do it. However, we still need to know what shield it is so we know how it's wired up.

That was an interesting challenge. There seems to be a set of commands for backlight control according to the product specification; brightness level, pwm frequency, brightness transition, etc. It will require writing some new driver functions.

Gents, This is indeed an interesting challenge :-). I bought the board here: http://www.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html    And I asked for the schematic which is here:  https://www.copy.com/s/t%3AwTDo10LVmZFHSxZc%3Bp%3A%252F2.4%2520schematic%25209325.pdf%3Boid%3A74    There are detailed photos on their site and you can see how the shield looks. Unfortunately, the seller doesn't have more information.

@Ignacio: would you have a snippet of code showing how to issue command 0x51? I would like to give it a try.

Nope, just follow the datasheet.

I tried command 51h (Write Display Brightness) by writing 0x51, xx (for xx I tried different values) to no avail. I also combined it with command 53h (Write CTRL Display) with 0x53, 0x28  and 0x53,00 also without results. Looks like I need the correct sequence of commands + parameters

Did the 0x28 command work as expected?

I could get the display to react to 0x28, but only at display initialization, not elsewhere. Please see my update #2

That is insane that they would hard wire it. Why write a datasheet if it's not going to be correct?
I evidently have the same display!
Maybe we can put the display to sleep. That is another command "10h" and leave sleep is "11h."

I agree it's insane to kill this functionality :-(  Putting the display to sleep doesn't work because I still need the display to be alive at night (but dimmed down).

I got in contact with the manufacturer of the shield, they informed that the background LEDs are hardwired and not controllable via the ILI9341. So, it is not possible to dim the background light in this shield
:-(
I will look for another TFT shield and make sure it's dimmable before buying.

That's strange. there is no BL pin? Have you got the schematics or at least a picture of the module?

No, there's no BL pin available on this board. I asked the manufacturer and they responded that this pin is hardwired and I don't feel like cutting/soldering PCB tracks.

Too bad :/ Such a stupid decision by the manufacturer.

Yep. In the end I abandoned the project because of other reasons. I found out that other boards communicate serially and provide a way to dim the backlight with a command. It means researching TFT shields before buying :-)

Most of thees cheap Chinese LCD modules have the LED backlight hardwired to Vcc and GND and cannot be controlled.
However, after inspecting the module I have and some similar ones online I found that most have the Back-light LEDs pins available through the LCD panel flex cable. If yours is similar to the one in the picture then you will notice that the main flex cable is for the LCD itself, and there are usually two other flex cables connected to it. The one on the left is for touch panel (if equipped), and the one of the right is for the back light LEDs (sometimes it is connected on the backside of the flex).

In this panel and on mine (a little different from this) they are labeled as K1, K2, K3 and K4 which are mostly the Cathode side of the LED (negative side) and they are exposed as separate pins in the main flex cable, while the Anode is soldered to the main flex cable Vcc plane and cannot be easily accessed without desoldering the LED flex cable.

So in ordered to control the backlight you have to cut the trace on the PCB (not the flex cable) and connect it to a transistor which you control through the Arduino.

Double check the polarity in your LCD panel, it could be different from mine.

It looks like it should be controllable with command 0x51.
I would modify the library and add a new method to the Adafruit_ILI9341_8bit_AS class - something like:
void Adafruit_ILI9341_8bit_AS::setBacklight(uint8_t brightness) {
    writeRegister8(0x51, brightness);
}

Then you can change the brightness by calling that method on your TFT object in your sketch.  (Don't forget to add the prototype to the class definition in the header file of course).

Hi Majenko, I followed your advise but I still can get this to work. Please see my update in the original question

After looking at the schematic (mine is different) but on pin 16 is labeled as BL. If that is indeed the power for the LED backlights then a voltage applied to it should vary the brightness.  Caution:You need to know how much current the LEDs are pulling. If over the limit for a PWM pin you will have to run it through a transistor to boost the current.

I have successfully dimmed the backlight on a ili9341 by simply modulating the pin the LED pin is connected to.
Note, I am using a teensy 3.2 your mileage may vary.
ledPin=32;

void loop() {
analogWrite(ledPin, 60);


text:
Error uploading Arduino Micro Sketch using Kubuntu
I have an arduino micro which I want to program from my Kubuntu 15.10 system. I installed the arduino software using apt-get, but when I try to upload the program (for test purpose I use the Basics\BareMinimum sketch) I get the following error:
Found programmer: Id = "0.00 V1"; type =
    Software Version = 0..; Hardware Version = 0.0
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

The proper device "Arduino Micro" is selected and also the proper port "/tty/ACM0". I found people on the internet which have the same error and could solve it by using another USB port or cable. But I tried it with two different cables and different ports and didn't manage to get it working. I even tried it on my Laptop running an older version of Kubuntu which produced the same error.
Therefore I tried the newest version of the Arduino software from the arduino homepage. With this I get a different error:
avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
avrdude: ser_send(): write error: Bad file descriptor

My user is added to the dialout group, so I should have access to the port. It is also the right port as the port disappears from the arduino menu when I unplug the board.
The arduino itself shouldn't be the problem, as I can upload the sketch from another windows laptop without problems.
EDIT: when I plug in the arduino, the following is added to the dmesg output:
[ 8390.293960] usb 1-2: new full-speed USB device number 6 using xhci_hcd
[ 8390.424861] usb 1-2: New USB device found, idVendor=2341, idProduct=8037
[ 8390.424863] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 8390.424864] usb 1-2: Product: Arduino Micro
[ 8390.424865] usb 1-2: Manufacturer: Arduino LLC
[ 8390.425283] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[ 8390.426815] input: Arduino LLC Arduino Micro as /devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.2/0003:2341:8037.0007/input/input21
[ 8390.482163] hid-generic 0003:2341:8037.0007: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC Arduino Micro] on usb-0000:00:14.0-2/input2

Try hitting reset before upload.

Hitting the reset button also doesn't solve the problem. Not I get an "upload completed", but the arduino still has the previous program loaded.

Which version of the IDE are you using?

I tried the one from the ubuntu package repository and one directly from the arduino.cc page. I have to look the version numbers up.

The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

Are you in the dialout group?

Yes I am, as stated in the text of the question.

I know this is a long shot and I'm expecting the answer to be no, but just confirming, you don't have any other serial monitors running that is monitoring the port do you?

and/or you have rebooted somewhere along the lines and that no other copy of the Arduino IDE is running and has control of the port? (sorry for the silly questions, just trying to help you rule everything out)

No I don't have any serial monitor running I know of. Maybe Kubuntu ships something I don't know of. And yes, as I am trying for quite a while, I have shutdown and rebooted the system a couple of times.

I now tried to install a fresh Linux on my Laptop. I used now Ubuntu 15.10., downloaded the newest stable Arduino software and added my user to the dialout group. The same error occurs again. So doesn't Arduino Micro work with Ubuntu? Because it now doesn't seem to depend on my settings and the Arduino and Cable works with another Windows Laptop, so it should also be ok. Anyone an idea?

Do you have a Uno to test with? The Micro/Leonardo devices are harder to upload to, if they have code loaded on them. The Uno (or similar) are somewhat more reliable.

No I only have an Arduino Micro.

Therefore I tried the newest version of the Arduino software from the arduino homepage.
The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.
I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.
I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

Have you followed the instructions here? Arduino Troubleshooting.

I installed the arduino software using apt-get ...

Personally I download the IDE from this page: https://www.arduino.cc/en/Main/Software

Update
I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:
Forcing reset using 1200bps open/close on port /dev/ttyACM1
PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
Found upload port: /dev/ttyACM1
/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/nick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM1
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
avrdude: writing flash (4456 bytes):

Writing | ################################################## | 100% 0.33s

avrdude: 4456 bytes of flash written
avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.03s

avrdude: verifying ...
avrdude: 4456 bytes of flash verified

avrdude done.  Thank you.

Can you please compare to what you get? Or post exactly what you see?

What do you see in your Port menu? This is what I see:

Installing Arduino on a fresh Ubuntu system
I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.
Download and install

Downloaded Linux IDE 1.6.7 (64 bit) from https://www.arduino.cc/en/Main/Software
Un-archive downloaded file into ~/development folder
Executed from terminal:  ./arduino

Compile "blink"

Selected Uno device type
Loaded "Blink" from examples
Uploaded (checked Uno showed in menu as shown above)
Got error:
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Check permissions, join dialout and tty groups
See owner of /dev/ttyACM*
$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

Am I in that group? (No)
getent group dialout
dialout:x:20:

Add to group dialout:
$ sudo usermod -a -G dialout nick

Am I in that group? (Yes)
$ getent group dialout
dialout:x:20:nick

Try again:
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Add to group tty:
$ sudo usermod -a -G tty nick

Check groups I am in:
$ groups nick
nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

Try again (same error).
Log out and log back in
After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).
Check USB for Micro
After reset:
$ lsusb | grep Arduino
Bus 002 Device 014: ID 2341:0036 Arduino SA

After about 3 seconds:
$ lsusb | grep Arduino
Bus 002 Device 015: ID 2341:8037 Arduino SA

Did my suggestion (of using the latest IDE) help? You have a bounty on the question, but we aren't getting much feedback on the suggested solutions.

I already had the newest version. Maybe I did read the version number wrong. I downloaded the newesest version 1.6.7 again and also tried the nightly build 1.6.8 (just downloaded). But I still get avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy and avrdude: ser_send(): write error: Bad file descriptor as error messages in two subsequent lines.

In the arduino IDE (Version 1.6.7, on Kubuntu 15.10) I get: http://pastebin.com/a77ctPEn
With avrdude in the terminal I get: http://pastebin.com/N7AZAhjW

See screenshot of Port menu in my answer.

http://www.renderclonks.de/files/ScreenShotArduino.png  I see nothing special or suspicious

I don't see it detecting the device type, like in my screenshot.

Ah hmm. What could be the problem? Do I need a driver for the Arduino Micro? But https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro says There is no need to install drivers for Ubuntu 10.0.4

See http://playground.arduino.cc/Linux/All - can you please do ls -l /dev/ttyACM* on the terminal, and paste the results into your question.

The result is just crw-rw---- 1 root dialout 166, 0 Jan 28 21:41 /dev/ttyACM0

Are you in group "dialout"? Please do: getent group dialout

dialout:x:20:richard (richard is my username)

Let us continue this discussion in chat.

Do you have any suggestions left what I could try? As mentioned above I tried to use a fresh Ubuntu 15.10 installation and it didn't work neither.

See updated answer where I got it to work on a Ubuntu 14.04 system which did not previously have Arduino IDE installed.

I will look through it and test it this evening. As the bounty period is already over and you had the most effort, I will assign the bounty to you.

You might consider removing the detour through the tty group, since that isn't relevant and the fact that it wouldn't be relevant was already evident from the ownership of the device node.  Without that, it will be clearer to future readers what the effective steps are.

I have been meaning to try the Arduino IDE on Ubuntu. (I'm on Ubuntu 14.10 LTS and using an original Arduino UNO).
From the top, I installed using:
sudo apt-get update && sudo apt-get install arduino arduino-core

(from: http://playground.arduino.cc/Linux/Ubuntu)
It's the older version 1.0.5 and loaded up the basic sketch. It worked straight off the bat.
Just some quick thoughts:
Keyboard and mouse emulation
I noticed the hid-generic and was reminded of the caution on:
https://www.arduino.cc/ re codig practices for keyboard and mouse emulation
regarding coding practices for keyboard and mouse emulation. Does your old sketch utilise the keyboard/mouse libraries at all? It might come down to REALLY timing the reset perfectly.
The reset problem
Given that you're getting a communication error based on the virtual USB device in the Leonardo/Micro (single chip as opposed to the previous versions), and you're seeing it in the IDE but not via the avrdude software, have you followed the reset instructions from the above link? So back to timing the reset (emphasis mine):

In general, you upload code to the Leonardo or Micro as you would with the Uno or other Arduino boards. Click the upload button in the Arduino IDE and your sketch will be automatically uploaded onto the board and then started. This works more or less the same way as with the Uno: the Arduino software initiates a reset of the board, launching the bootloader - which is responsible for receiving, storing, and starting the new sketch.
However, because the serial port is virtual, it disappears when the board resets, the Arduino software uses a different strategy for timing the upload than with the Uno and other boards. In particular, after initiating the auto-reset of the Leonardo or Micro (using the serial port selected in the Tools > Serial Port menu), the Arduino software waits for a new virtual (CDC) serial / COM port to appear - one that it assumes represents the bootloader. It then performs the upload on this newly-appeared port.
These differences affect the way you use the physical reset button to perform an upload if the auto-reset isn't working. Press and hold the reset button on the Leonardo or Micro, then hit the upload button in the Arduino software. Only release the reset button AFTER you see the message "Uploading..." appear in the software's status bar. When you do so, the bootloader will start, creating a new virtual (CDC) serial port on the computer. The software will see that port appear and perform the upload using it. Again, this is only necessary if the normal upload process (i.e. just pressing the uploading button) doesn't work. (Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it; this won't work if something interferes with the board's USB communication - e.g. disabling interrupts.)

avrdude command line
Next, share your avrdude command line and we can see if something is odd there. As an example with my UNO I see this:
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build1362089533882735765.tmp/Blink.cpp.hex:i

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/madivad/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
.... and so on ....

USB 3 vs USB 2
I probably could have put this closer to the top, but are you using a USB 2 or USB 3 port? If USB 3 are the correct drivers loaded? Have you tried a USB 2 port (if available)
Good luck

Thank you for your comment.
I tired different USB ports, also USB 2 ports. I don't use any mouse or keyboard functions in the arduino, so this souldn't apply. I uploaded the bare minimum sketch before (using a windows laptop) to rule out problems from the previous sketch. Holding down the reset button now results in the arduino IDE pretending to upload correctly, but the sketch doesn't work (the LED doesn't blink, and it does if I upload from windows. The avrdude gives an output with "programmer is not responding": http://pastebin.com/iPwFK7yK

You may find that there is a process on Ubuntu that is grabbing the newly created CDC/ACM port as soon as it enters programming mode.
With the Leonardo and Micro you have a CDC/ACM port while it's running, and when the board resets to enter programming mode that CDC/ACM port is destroyed and an entirely new one (hopefully under the same name) is created.  The process modem-manager can grab that newly created CDC/ACM device thinking it's a modem and try to configure it as such, thus locking you out of the port.  A similar process in Debian is brltty which tries to configure the CDC/ACM port as a braille TTY interface.
You can check to see what process has the CDC/ACM device node open if any with the lsof command:
sudo lsof /dev/ttyACM0

If you find that you do have modem-manager running on your system (I'm not sure if it's still default or not, it's been a while since I used Ubuntu, preferring the purity of Debian) it's best to completely remove it:
sudo apt-get remove modemmanager

sudo lsof /dev/ttyACM0 gives an empty output.

Then nothing is locking the file at that moment then.  Still, check to see if modem-manager is running: ps ax | grep -i modem

  787 ?        Ssl    0:00 /usr/sbin/ModemManager  4497 pts/1    S+     0:00 grep --color=auto -i modem
so it appears to be running I think. I will try to remove it.

I uninstalled it as well as brltty, but it didn't change anything.

Make sure that the processes have actually gone - they may still be lingering even after uninstall.

The command ps ax | grep -i modem now doesn't display any processes. I also did a reboot of the laptop and plug out and in again of the arduino to be on the save side. The same holds for brltty

Ok, I think we have exhausted my ideas for the moment. I will keep thinking it over and see if I can come up with anything else.

sudo apt-get remove modemmanager thank you, that solved my problem too !

This is all the symptoms of not having the correct board selected in the IDE.
The fact that the LEDs are flashing during uploading means it's probably not a comms issue.
I understand you wrote that you have selected the correct board already, but please double/triple-check.
I work with both UNOs and Nanos, this is a classic mistake I make all the time.

No, I chose the right board: http://www.renderclonks.de/files/ScreenShotArduino.png

sudo chmod 666 /dev/ttyACM{for your arduino board}
mine happens to be "/dev/ttyACM1" so i did
sudo chmod 666 /dev/ttyACM1

There are two problems here: first, the error is not one of permissions, but that the device is busy, so this won't help.  The other is that this solution is not lasting - if there were an actual permission issue, you'd have to do this each time the Arduino enumerated.  The correct way is to add one's user to the group which owns serial devices, which the asker seems to have already attempted to do.  It's worth noting also that the question is a year and a half old.


text:
Send analog value over IR?
for my rc robot I want to use ir to send/receive the value from a jostick.
Is it possible ? I can't use any other radio chip like nrf24l01.

Yes. It's possible.

documentation ? library? website?

I don't know any of those. I know it is technically possible though, which is what you asked. Maybe Google knows where the websites are?

Yes, it is possible. That is already supported by the IR library. Please see this tutorial for further details. The outline of the sender is:
 uint16_t sample = analogRead(A0);
 irsend.sendSony(sample, 16);

And the receiver:
 if (irrecv.decode(&decodedSignal)) {
    uint16_t sample = decodedSignal.value;
    ...
 }

Cheers!


text:
Error compiling Arduino
I've just installed the last version of Arduino 1.6.7 plug my Arduino SmartEverything (http://www.smarteverything.it/) to OS X 10.11.2, try to compile this project: https://github.com/nicolsc/sigfox-weather-station/blob/master/sigfox_smart_weather.ino But i got this error
/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
Build options changed, rebuilding all
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/preproc/ctags_target_for_gcc_minus_e.cpp"
exec: "-w": executable file not found in $PATH
Error compiling.

Your installation is broken.

I've reinstalled Arduino with the same problem

You must reinstall the Board. That is where the problem is. The board build settings are not read correctly. The compiler setting is missing.

I guess I can't do it through the USB

What has USB got to do with the board and compiler definition installation?  Just delete and reinstall the whole thing, not just the IDE. Delete all the boards and reinstall them.

I 've reinstalled with the same result :-(

Reinstalled the IDE, or reinstalled the boards / compilers etc packages?

Please avoid posting duplicate questions on multiple SE sites

Install Arduino SAMD Boards (32-bits ARM Cortex-M0+) board (using "Tools" -> "Board" -> "Boards Manager" menu).
Just search for "SAMD" in the search bar, choose the latest version and install.

Are you saying this fixed the problem?

yes !!!   indeed, this fixed the problem