body:
I used Programmer "AVRUPro+" for Uploading Program. I downloaded its Software "Progisp" Then I did some few steps....

1) After downloading it, Run the Progisp.exe file.
2) Then went to Command tab, and clicked “Program Fuse”, It just did my fuse  set.
3)Then I just did the simple process of burning the bootloader to my Atmega Controller.
4)After this I was able to upload my program to my new Atmega Controller.

Thank you


sender: user

message:
Problem up loading to board

I'm a newbee to Arduino programming and hoping someone can help me with this. These are the errors when uploading the proceeding sketch. Thanks in advance!

avrdude: stk500_rcv() : programmer is not
responding

avrdude: stk500_getsync() attempt 10 of 10:not in sync:

Problem uploading to board.

<!-- language: c -->

    //www.RobotLinking.com
    //2015.5.7
    /************************************************/
    #include <Servo.h>
    /************************************************/
    Servo myservo;//create servo object to control a servo
    /************************************************/
    void setup()
    {
      myservo.attach(9);//attachs the servo on pin 9 to servo object
      myservo.write(0);//back to 0 degrees
      delay(1000);//wait for a second
    }
    /*************************************************/
    void loop()
    {
      myservo.write(15);//goes to 15 degrees
      delay(1000);//wait for a second
      myservo.write(30);//goes to 30 degrees
      delay(1000);//wait for a second.33
      myservo.write(45);//goes to 45 degrees
      delay(1000);//wait for a second.33
      myservo.write(60);//goes to 60 degrees
      delay(1000);//wait for a second.33
      myservo.write(75);//goes to 75 degrees
      delay(1000);//wait for a second.33
      myservo.write(90);//goes to 90 degrees
      delay(1000);//wait for a second
      myservo.write(75);//back to 75 degrees
      delay(1000);//wait for a second.33
      myservo.write(60);//back to 60 degrees
      delay(1000);//wait for a second.33
      myservo.write(45);//back to 45 degrees
      delay(1000);//wait for a second.33
      myservo.write(30);//back to 30 degrees
      delay(1000);//wait for a second.33
      myservo.write(15);//back to 15 degrees
      delay(1000);//wait for a second
      myservo.write(0);//back to 0 degrees
      delay(1000);//wait for a second
    }
    /**************************************************/

sender: assistant

body:
One of the first things to know about Arduinos is that that there are a lot of them – and a lot of tools for programming them. For your problem this means that the most likely reason for the problem you are having is a mismatch between the board your are using and the board your tools are set to upload to. Since you've said you're new to the Arduino I'm assuming that you're using the "official" IDE.

So, here are some things to try:

 1. From the IDE main menu, choose **Tools > Board** and select your board, then
 1. Choose **Tools > Programmer** and select an appropriate programmer for your board. Without knowing what board you're using and how you're connecting to it I can't offer more specific advice. However, if you Google for something like "beginner tutorial <your board name here>" you're likely to find an answer. Or more likely three answers. You'll need to look at the one that matches the OS you're using on your development machine.
 1. You may also need to select the port that the Arduino is connected to.

If you've gotten this far and haven't solved the problem, here's what I'd do next:

 1. Do a search on the exact error message you're getting – copy it out of the IDE and the paste it into your favorite search engine. Put quotes around the message so that you don't get a bunch of unrelated hits for your search.
 1. Search for tutorials on the board and/or IDE vendor site.
 1. Work through a tutorial from a good beginner's site. I like the [materials the Adafruit folks have developed][1], but there are lots of good resources out there.
 1. Post a question. When you do be sure to:

  * Describe your environment: the board you're using, the IDE you're using, the OS you're working on, how the board is connected to the development machine, and the basic settings of the IDE.
  * Explain what you've tried.
  * Describe, or better, include a screen shot or the actual text of the problem that you're seeing (like you did here).
  * For some problems it will also be useful to include the code. If you include the complete code then it is possible that somebody could try to actually reproduce your problem.

 [1]: https://learn.adafruit.com/lesson-0-getting-started/overview


message:
Arduino outputs garbage values on serial monitor with ESP8266

I have connected my Arduino with an ESP8266.

When I check the ESP8266, by manually entering commands at serial monitor, I get correct results.

However, when I run this program

    #include<SoftwareSerial.h>

    SoftwareSerial esp8266(2,3);

    void setup() {
      Serial.setTimeout(5000);
      Serial.begin(115200);
      esp8266.begin(115200);
      delay(1000);
    }

    void loop() {
      delay(2000);
      String command="AT";

      esp8266.println(command);
      if(esp8266.available())
      {
        while(esp8266.available())
        {
          char c=esp8266.read();
          Serial.write(c);
        }
      }
    }

I get garbage values where sometimes it has an `OK` in between the output:

> " Received: "ÁT OK " Received: "AÔ ÏË " Received: "AÔ OK " Received: "ÁT ÏË " Received: "ÁT OË " Received: "ÁÔ OK " Received: "Á¬ OK " Received: "ÁT OË "

Could someone help me?

body:
As noted by Matt, the baud rate for the ESP8266 can vary depending on the firmware version/manufacturer.  9600 and 115200 are the most common.  If you can connect using a serial terminal program (like CoolTerm) you can then test the baudrate.

It sounds like the ESP8266 is set to 115200, but in my experience (and others') SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting). Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  But you can reset this and see what the max reliable value is for you in your configuration.

How to change the baud rate on the ESP8266 will depend on the firmware version. I've had success with `AT+IPR=9600`. You only need to run this command once (it's a persistent setting). I'd suggest, based on your description, that this is the most likely culprit that's causing the intermittent "garbage" output you describe.


body:
Using 115200 has too many instructions for the Arduino Uno to reliably decode characters and that's where the garbage is coming from.

The ESP8266 default baud is 115200, so you need to connect at the default rate and issue an AT command to reduce the baud rate to 9600.

Each time you reset, the ESP8266 goes back to the default baud rate.

Here's an example script that connects at the default baud rate and then reduces it to 9600. You'll connect the Serial Monitor at 9600. At the lower baud rate, I'm not getting any garbage characters.

    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup()
    {
      Serial.begin(9600);
      ESPserial.begin(115200);
      ESPserial.println("AT+IPR=9600");
      delay(1000);
      ESPserial.end();
      // Start the software serial for communication with the ESP8266
      ESPserial.begin(9600);

      Serial.println("Ready");
      ESPserial.println("AT+GMR");
    }

    void loop()
    {
        // listen for communication from the ESP8266 and then write it to the serial monitor
        if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

        // listen for user input and send it to the ESP8266
        if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
    }

An odd thing that happened to me is that I tried to use a baud rate of 4800 and I bricked one ESP8266 module. I don't know if that was a glitch or just a coincidence.


body:
Using AT+IPR is a very dangerous command. Many ESP8266 will get bricked after the command. The only way to do it is by flashing your ESP to a 9600 baudrate.

I just had to do this myself with a friend today after using the AT+IPR command and loads of websites tell you to never use the command.


body:
Finally, solved garbage symbols in serial monitor by lowering the ESP's baud rate from 115200 to 9600 with the following command:
`AT+UART_DEF=9600,8,1,0,0`
The root cause of the problem is speed limitations of the SoftwareSerial. On hardware Serial connection, it should work ok with speeds up to 115200.

There is my ESP AT+GMR info:
```
AT version:1.3.0.0(Jul 14 2016 18:54:01)
SDK version:2.0.0(5a875ba)
v1.0.0.3
Mar 13 2018 09:37:06
```


message:
Is it possible to simulate PWM using delay() function?

I was thinking about if it is possible to **simulate** PWM (AKA pulse width modulation).
Is it possible to reach the speed of the PWM using the delay() function ?.
Note : I am talking about the pins which does not support PWM, Arduino uno Pin 13 for example.

body:
It is possible to create a PWM signal from a non-PWM digital pin although you would not want to use delay, but timer interrupts for accuracy and finite timing. PWM intervals are typically measured in (μs[microseconds] vs ms[milliseconds]).

The standard Arduino servo library  does this: [Servo](https://github.com/arduino/Arduino).


body:
It would be possible to do it. Would it be a smart thing to do ?

I do not think so. Micro-controllers (not just Atmel's) have dedicated hardware modules to manage the signals for PWM. What happens when you use AnalogWrite is the compiler/interpreter/whatever uses these informations to modify the appropriate registers so the toggling is not managed by the code.

If you use the delay() functions, you are simply letting clock cycles pass by until the time you set is passed which is a lot less efficient. Plus, you would probably not get the same PWM frequency.


body:
What you are talking about is more appropriately called Bit-Banging. Check out this [link](https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM). It even has an example of what you are trying to do. @Jason is correct that it causes a number of issues. The link above will also run you through the draw backs of this method which I will summarize.

 - Jittery due to interrupts (Interrupts can be disabled)
 - The Processor cannot do anything else and keep the output working
 - Frequency and Duty Cycle are difficult to determine


body:
I think it depends on what you want to use it for. I compared using PWM and bit banging to run a small DC motor.  PWM produced an audible whine that I found very irritating.  Using the delay function removed that (a delay on/off cycle of 10 milliseconds).  I also found that it was relatively easy to control not only the ratio of on/off (PWM) but also the length of the cycle.  This was useful for starting the motor with a slightly higher "push" to get it moving. (I'm sure that this could be done using PWM too) With respect to performance of the engine, I didn't find much actual difference.

The key issue with a DC motor is that while the digitalWrite() is LOW, the inertia of the motor carries the rotation on and so the effect of the delay is smoothed.  In addition the RPM of the motor wasn't critical for my application.

However, if one was running a LED then using delay() might be visibly discernable and cause discomfort (and possibly seizures?).  For this, I'd definitely use PWM.

regards
Mark


message:
How to confirm a pin is fried

How do you confirm a pin has been damaged and is unable to work as a digital input?

I tried detecting a pushbutton (connecting ground to pin 11 with a pullup resistor enabled) on a fresh Arduino Uno and digitalRead() always registers 0, regardless of the pushbutton state.

To confirm it wasn't my pushbutton's wiring, I tested it on some other pins, and they register the button press perfectly. I then tested pin 11 as an output, and it was able to blink and LED just fine.

The Arduino's pretty new, and I don't remember doing anything with it that would have damaged anything, much less pin 11, but is it fair to say that pin has somehow been damaged? As far as I can tell, everything else on the Arduino works perfectly.

body:
Yes, it sounds like that pin is fried.

You seem to have done all the things I would recommend:

1. Try your circuit on a different pin (works fine)
2. Try your circuit on the same (faulty) pin on a different microcontroller (works fine)

If you get different results between two chips that should be the same with the same code running on them then one of them is most likely faulty in some way, or has some other setting in it (fuse setting) that could be affecting it.  I am not aware of any settings like that on the '328P, certainly none that you would change without knowing you had changed them.


message:
How to check if a pin is set from bank?

How would you go about checking if an input pin has been set using the entire bank? I am thinking that I need to use bit twiddling with a bit mask but I have not used this enough to figure out how to do what I want.

Basically I have the following code:

    void setup() {
       DDRA = 0x00;
       PORTA = 0xff;
    }

    void loop(){
       //Check if any pin from Port A has been pressed
       if (PINA & 0xff){
          //do stuff
       }
    }

But the code above is not working how I expected it to. Has anyone tried to use this approach before? Am I going about this the wrong way? I figured since I was using all 8 pins from one bank, it would be better to check if any of the pins on that bank have been set instead of checking each individual pin. My thinking on this was to prevent any user input from being skipped in case a button press was initiated while the program was running other code. This way I only check if anything in the bank has been set saving time (I think).

body: The simplest way is to use DigitalRead in a loop. It makes your code more portable, and easier to read.


body:
I'm not really an expert in "plain avr code" but I've modified arduino blink and got (almost) a perfect example. Placed a jumper between 5v and pin 8 of arduino and uploaded the following code:

<!-- language: C -->

    void setup() {
      // initialize digital pin 13 as an output.
      DDRB = 0b00100000;

    }

    // the loop function runs over and over again forever
    void loop() {
      if (PINB & 0x1) {
        PORTB =  0b00100000;  // turn the LED on (HIGH is the voltage level)
        delay(500);              // wait for a second
        PORTB = 0;    // turn the LED off by making the voltage LOW
        delay(500);              // wait for a second
      }
    }

according to following picture pin8 on arduino is PB0 and pin13 is PB5. So using DDRB I set PB5 as output and all others as input. Then in loop I check as you do PINB register and use bitmask to check first pin (the PB0). And it works... well not quite well. For some reason the loop goes a few times more before goes really low. I believe is because I just remove the jumper and do not actually ground pin 8 ( is left float) and maybe the extra loops are discharging some capacitance on that pin 8.

[![pinouts][1]][1]
<sub>(source: [arduinoexperts.com](http://jobs.arduinoexperts.com/wp-content/uploads/2013/03/ARDUINO_V2.png))</sub>

So, to your specific question, your bitmask is right. This instruction `PORTA = 0xff;` is useless because, as far as I know, this settings are ignored because you set Pin direction in pins of PORTA to input. However, according to that image, atmega328 doesn't have a PORTA. Is that your error or are you using another microcontroller?

**EDIT** Capacitance thing is confirmed, maked it swing between gnd and vcc   with a switch and all works fine.

 [1]: https://i.stack.imgur.com/ZXMxn.png


body:
The problem is here:

>     //Check if any pin from Port A has been pressed
    if (PINA & 0xff){

Since the pullups are enabled, the default state of the pins is high. To detect a "press", they have to be pulled to ground. This changes the test to:

    //Check if any pin from Port A has been pressed
    if (~PINA) {

And for individual pins:

    //Check if PA3 has been pressed
    if (!(PINA & _BV(PA3))) {


message:
Is there any way to flash sketches using custom firmware?

I am using HIDUINO as my firmware (flashing via dfu-programmer), and to upload sketch I need to re-flash original firmware, upload sketch and then flash HIDUINO again.

Is there a way to flash sketches without reflashing original firmware?

body:
I assume you mean you are reprogramming the USB interface chip, which means you no longer have a UART pathway through to the ATMega328P. If so then yes, you can provide your own USB interface in parallel by connecting an FT232 (or similar) breakout board direct to the ATMega328P chip just like you would on a breadboard Arduino:

[![enter image description here][1]][1]

* FTDI TX -> Arduino RX (Yellow)
* FTDI RX -> Arduino TX (Blue)
* FTDI DTR -> 100nF Capacitor -> Arduino RESET (Green)
* FTDI GND -> Arduino GND (Black)

The capacitor is required with later versions of `avrdude` and newer versions of the Arduino IDE since the DTR signal is now held LOW rather than being pulsed as it used to be.  This is to combat a change in the FTDI drivers that meant that the DTR stopped being driven at all and broke the auto-reset facility.  So now we need a capacitor to convert a constant LOW into a short low-going pulse to initiate a reset without locking it all up.

  [1]: https://i.stack.imgur.com/zaoYI.png


message:
Is there something I can use to control Arduinos easily over Ethernet with .NET?

I'm wondering if there's anything out there that maybe works pretty similarly to Firmata, runs on Unos or Megas, and can be controlled over Ethernet. I am writing a home automation system with .NET, and I see some options for supporting Firmata with .NET, but I want to be able to connect my devices over Ethernet.

body:
I don't use .net but I have done this using php website to control a door lock over ethernet.

My solution was to use the ethernet to recieve commands and be able to use them on the arduino through http calls. And when it was done send a http call back to the server with some data. I was doing a door lock program for example. Please ignore anything talking about doors, locking, unlocking, or other requirements to certain calls, I am just providing examples about how it COULD be used, not that you need to include my door lock code in your project to get it to work.

As far as how that works out with .net that's up to you, however I can give you a hand getting your messages back and forth.

first you want to create the ethernet connection to your router. put this in your header section.

    #include <UIPEthernet.h>
    // assign a MAC address for the ethernet controller.
    // fill in your address here:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };

    // fill in an available IP address on your network here,
    // for manual configuration:
    IPAddress ip(127, 0, 0, 1);

    // initialize the library instance:
    EthernetClient client;

    char server[] = "www.example.com";
    //IPAddress server(127,0,0,1);  // numeric IP for www.example.com (no DNS)

    int waitTime = 3L;

    unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = waitTime * 1000L; // delay between updates, in milliseconds
    // the "L" is needed to use long type numbers

throw this in your main loop so it doesn't constantly make http requests spamming a server.

    // if ten seconds have passed since your last connection,
    // then connect again and send data:
    if (millis() - lastConnectionTime > postingInterval || buttonState == 0) {
      httpRequest();
    }

Create a method to handle httpRequest because shoving everything under the main is kinda sloppy.

Alright so there will be quite a bit here because http headers are kinda lengthy.

    // this method makes a HTTP connection to the server:
    void httpRequest() {
      // close any connection before send a new request.
      // This will free the socket on the WiFi shield
      client.stop();
      // if there's a successful connection:
      if (client.connect(server, 80)) {
        Serial.println("connecting...");
        // send the HTTP PUT request:
      Serial.println("String is " + readString);
      if(readString == "Ready" || readString == ""){
        client.println("GET /command.txt HTTP/1.1");
        where = "web";
        waitTime = 5L;
      }
      else{
        // here is the basic format of sending a get command
        //this specific request is so that I can tell where the command came from. I had a web client / mobile app that could control the door AND you could also control it from a physical buttom. The door would have to reply either way to the web server (READ: .net application) in order to have the correct status always show up on the web end.

        client.print("GET /update.php?where=Arduino&command=Ready&status=");
        if(readString == "Reset"){
          client.print("Reset");
        }
        else if(isLocked){
          client.print("Locked");
        }
        else{
          client.print("Unlocked");
        }
        client.println(" HTTP/1.1");
        waitTime = 1L;
      }
      client.println("Host: www.example.com");
      client.println("User-Agent: arduino-ethernet");
      client.println("Connection: close");
      client.println();

        // note the time that the connection was made:
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection:
        Serial.println("connection failed");
      }
    }

TL;DR if you wanna use ethernet you need to use all of ethernet.
Start by creating your connection to the router statically (watch for conflicts).

Then create a method of watching for incoming data or waiting for a command if there isn't one. (server call).

Then create A FULL HTTP REQUEST in order to pass your request through. Shorting any parts of this last part and you will either end up with bad request errors or will simply fail.

Let me know if you need anything else or if this was useful to you!


message:
Interface pressure Sensor

Hello folks,
              I am using G1/4 Pressure Transmitter Sensor 0-1.2 MPa sensor can you guide for programming part.The conversion from bar to pascal  or bar to Mpa or pascal to psi.Though I am new to it. Plz guide me .

body:
I'm assuming you mean that you want to pull a voltage number off of an input pin and convert it to a meaningful number.

To do this find the range of the incoming voltage.

Find the range of the sensor.

After that you need to split the voltage up to show what parts of the range convert to how much psi.

Here is an example of a temperature gauge that has the same principle.

[Temp sensor][1]

  [1]: https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor


body:
One thing that I would add to this is that if you need good accuracy you may want to apply a voltage equal to your full scale output to the AREF pin. The value on AREF does not have to be equal to the full range of the sensor – just to the maximum value you will get – if you will never see readings at the extremes of the sensor's range you can set your AREF below the maximum value and get higher resolution.

Tronixstuff has a good [tutorial on the AREF pin][1] that goes into considerable detail about how to configure the pin and use the `analogReference()` function.

[1]: http://tronixstuff.com/2013/07/02/tutorial-arduino-and-the-ti-ads1110-16-bit-adc/


message:
Array of strings - how to determine the number of elements present

I would like to use an array of strings which I define as follows:

    char* CommandQueue[]={"FirstCommend", "SecondCommend", "ThirdCommand", "Cmd4", "Cmd5"};

The purpose of this array is to hold commands ("strings of various lengths") that the Arduino will receive through a serial port. Those commands will be interpreted by calling appropriate callback functions to act on them. The CommandQueue is supposed to line up the commands in a sort of "buffer".

Initially the "CommandQueue" array does not contain any elements and gets populated during the runtime of the project. The  array will continuously be interrogated and once a command is interpreted (and the corresponding function executed) the command will be eliminated from the queue.

How can I determine how many elements (i.e. strings) or commands are present in the array? The sizeof() function will not be helpful because the individual elements can be of different lengths.

Thanks in advance for your help or comments.

body:
Do you need to know how long the command queue is, or just if there are still elements in it? This seems like a case where you might be better off using a different data structure – a linked list seems like an obvious possibility. If you're not familiar with linked lists, [this article][1] may be helpful. Otherwise, I think you'll need to keep track of the number of elements in the queue for yourself.

If you do use an array, it will need to be declared with a fixed length, something like:

     char * CommandQueue[MAX_QUEUE_LENGTH];

The `sizeof` operator would tell you the length of the array, but not the number of items in it (the length of the array is the number of character pointers defined by MAX_QUEUE_LENGTH). The code to manage the command queue as an array could get pretty messy, especially if you need to execute the commands in order.

If instead you use a linked list then each command is added to the list at the end as it comes in, and when you execute commands they are pulled from the head of the list. If you need to know the length of the queue you could either update it as you add and remove commands, or you could iterate over the list and count the number of items in the list.

[1]: http://www.thegeekstuff.com/2012/08/c-linked-list-example/


body:
You can't know how many items are in an array simply because an array has a fixed size, and there is no such thing as "not an entry".

The closest you can have is a fixed size array and only some entries in it are valid - those that aren't valid have a special value to say "this is not a valid entry". For `char` pointers it's normal to use `NULL` as the "not a valid entry" value.

The drawback of this approach though is that you can never store more items than there are slots for, and finding out how many valid or invalid entries there are and shuffling them around when you remove the first entry is both a tedious and time consuming task.

Better in this situation to use a *circular buffer* which is a fixed size array but you remove the concept of a "first" entry. Instead you have a "head" and a "tail" value which is the locations in the array where you read from (remove the oldest) and write to (add after the newest).  It's how the serial port on the Arduino deals with incoming and outgoing data - as data arrives it is added to a circular buffer and you then read from that buffer.

To help work with circular buffers I wrote a small template class:

* https://github.com/MajenkoLibraries/CircularBuffer


body:
A very useful macro is [membersof][1]().

    #define membersof(x) (sizeof(x) / sizeof(x[0]))

You will find in defined in large libraries and frameworks for C/C++. For your example above the number of elements is:

    const int COMMAND_QUEUE_MAX = membersof(CommandQueue);
    ...
    for (int i = 0; i < COMMAND_QUEUE_MAX; i++) ...

A dynamic set would require a max length and null terminated or simply a counter.

    const int COMMAND_QUEUE_MAX = ...;
    char* CommandQueue[COMMAND_QUEUE_MAX] = { ....., NULL };

    for (char** cpp = CommandQueue; *cpp != NULL; cpp++) {
      char* name = *cp;
      ...
    }

Or even better use a [Queue][2] data type:

    Queue<char*, COMMAND_QUEUE_MAX> CommandQueue;
    ...
    char* cp;
    while (CommandQueue.dequeue(&cp)) ...

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Types.h#L165
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh


message:
Sending data over TCP connection in one piece

I'm trying to send short strings via Java client to Arduino server and vice versa. Sending data to client goes fine, but when I try to send data to arduino it cuts the string into bytes and then sends the first letter.  Will the following work?

<!-- language: c -->

    for(int i = 0; i < data.length(); i++)

Even if it can be sent as characters I want to send it in one piece, because strings are very short so there should be no problems with length.

EDIT: Alright, I read `client.read()` documentation, so the problem is at arduino.

This is my java code:

<!-- language: lang-java -->

    public class TCP {
 static Socket clientSocket;

 public static void main(String args[]) throws Exception {
        clientSocket = new Socket("10.10.10.57", 5000);
  sendToServer("HAI THERE\n");
  String msg = getFromServer();
  System.out.println(msg);
  close();
 }

 static void sendToServer(String msg) throws Exception {
  //create output stream attached to socket
        PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        //send msg to server
        outToServer.print(msg + '\n');
        outToServer.flush();
 }

    static String getFromServer() throws Exception{
        //create input stream attached to socket
     InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader inFromServer = new BufferedReader(isr);
        //read line from server
        String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
        return res;
    }

    static void close() throws IOException{
        clientSocket.close();
    }
    }

This code sends only one byte at the same time.It might be problem in my arduino code, since I read it with

<!-- language: c -->

    char c = client.read()

One more thing. If there is any java master, I would like to know what to do with exceptions. How should I handle disconnected socket, failed connection to server, and so forth?

body:
The problem is, that "char" is just one character. So you have to build your return out of the chars... if you want to use the "client.read()" function.

    String res = ""; //this will be the resived msg after the loop
    do {
       char c = client.read(); //c will be -1 if no byte is left
       if(c!=-1)
           strcat(res, String(c)); //Append the char to the result string
    } while(c!=-1);

//Code is not tested!!!

To your java problem... just put your code parts into try catchs not whole functions (remove it for the function and add it on the points eclipse tell you to). So you can react to each error individually. Then put client stuff in a own thread so it not blocks any other stuff. Every disconnect or faild connection will throw an exception if you dont catch it with an if. So you have to handel it their (try to reconnect or something)

EDIT:

    static void close() {
        try {
            client.close();
        } catch (IOException e) {
            system.out.println(e.toString()); //Print the error or do something else

        }
    }


message:
Updated Arduino IDE and Arduino not working

I've had the 1.0.5 IDE on my PC, which worked great. Now I've just decided to update to 1.6.6. After some stupid Java errors and trial and error, I got it to work.

I recompiled my project. Massive errors. Fixed the errors and compiled again.

It stated "Uploading..." That took much longer than before, but I saw the "This takes xxx memory and xxx bytes on the device" yadi yadi ya.

I decided to unplug the Arduino, swap some jumpers and reconnect it (as I've always done). Only this time - I hear 3 beeps from my PC (the sound you hear with broken USB devices). The COM port is no longer recognized.

How do  I fix this? Did that IDE upgrade just brick my Arduino?

body:
Allright, seems to be fixed. After a 3rd reinstall it seems like its fixed. I reinstalled the whole package, including the drivers, and now it seems to recognize the device again.

Also the compiling now stops properly when done and shows "upload complete".


message:
Documentation for creating a Board Manager profile for the Arduino IDE

I'd like to write a Board Manager profile for some Arduino boards that I have. So far I've struck out on finding the documentation on the format and contents of the files. Does anybody know where I can find it?

body:
Documentation is kind of scarce.

Basically there are two aspects to what you want - the *board definition* and the *board manager JSON file*.

The first describes the board to both the IDE (entry in `boards.txt`) and to the API software (definition of what pins are what and what peripherals are where, etc).  The latter is in the file `pins_arduino.h`.

Then there is the `JSON` file that describes the whole package to the board manager and is what allows people to download the `boards.txt` and `pins_arduino.h` files (and anything else you may require) from your website.

As there is not much documentation you are best off taking an existing set of files that are close to what you want and modifying them.  Most of the time it will be a slight tweak such as re-ordering a few pins in some arrays, or changing the name of the board and maybe an upload command or baud rate setting.


body:
Arduino has provided comprehensive official documentation. You may not have found it because, since this is developer documentation rather than something the average Arduino user needs, it is published in the wiki of the Arduino IDE GitHub repository rather than with the standard documentation on [arduino.cc](https://www.arduino.cc/).

### Hardware Package
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification

### Boards Manager Support Files
- JSON Index File: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification

- Boards Manager installation archive: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#installation-archive-structure


message:
Best practise when dynamically updating sketch

I am currently working on a project that uses an Arduino Mega 2560 board along with the Arduino GSM shield to connect to the internet and send/receive SMS messages.

As part of my project, I want to be able to update the software that I am running dynamically. At a high level, I want to connect to my server, check if there is an update, if there is, download it and then overwrite the current sketch to run the new downloaded binary if the checksum of the downloaded binary is as expected (to avoid corruption).

Now, I am new to Arduino programming, so I figured I would ask a community of people with experience to determine the best method.

My current ideas are as follows:

 - **Writing a custom bootloader** - The sketch will have an update routine that downloads the new binary to a known location, and then performs a system reset. The bootloader will then overwrite the current sketch with the downloaded binary and then run the sketch.
 - **Overwriting the sketch whilst running** - I'm not sure of the viability of this method, but the overall method would be to write an update routine to the end of flash memory, and in this code simply overwrite all of the non-bootloader code with the new sketch.

Are these methods both viable, if so, is there one that would be preferable to another? If not, are there any known solutions to this problem?

body:
You won't be able to download the whole binary and test its checksum before flashing because RAM is so much smaller than flash. To do that, you'd need an external storage device to hold the new binary, and a custom bootloader to install it from the device.

Otherwise you'll have to load-and-flash, testing the checksum on the fly, and retry if you need to until you get a good reload. Can your device and its environment tolerate stopping for however long a couple of retry cycles might take? You can't recover if the process is interrupted once you start flashing; you can only move forward. Can it tolerate a conceivably long outage if communication goes down once the reload process has started?


message:
Windows 10 problem installing driver

So the arduino shows up as "Unknown device" when connected to my computer. Followed somr guides on google but still failed, this error came up, what should I do? I've tried "Disable Driver Signature Enforcement" and the regedit thing..

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/TUxUJ.jpg

body: Install the latest Arduino IDE with windows administrator rights.


message:
I don't have "Process" header

I'd like to run an application on my system after pushing a button on an Arduino shield. I've read that I need to use the `runShellCommand()` function, which can be accessed from a Process header. However when I add the `#include <Process.h>` line to my program I'm getting this error:

    .build/uno/src/sketch.cpp:2:21: fatal error: Process.h: No such file or directory
     #include <Process.h>

I'm using Ubuntu 14.04 and I've installed Arduino software from repositories.

body: That only works on an Arduino Yún ([as described in this tutorial](https://www.arduino.cc/en/Tutorial/ShellCommands)).


message:
Problems with Draw Loop using u8glib

I am using an Arduino Mega and a 12864ZW LCD with the u8glib library and the following code to draw to the LCD:

    U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);

    void loop(){
       Draw();
    }

    void Draw(){
       Display.firstPage();

       do{
          Display.setPrintPos(10, 10);
       Display.print("This is a test");
       }while(Display.nextPage());
    }

The problem is that the display is constantly redrawing itself. When I used LCD displays in the past, they usually only required to write to the LCD once unless you wipe the display. When I adjusted the code to:

    U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
    bool needsUpdate = true;

    void loop(){
       Draw();
    }

    void Draw(){
       if (needsUpdate){
           Display.firstPage();
        do{
        Display.setPrintPos(10, 10);
        Display.print("This is a test");
        }while(Display.nextPage());
        needsUpdate = false;
       }
    }

I do not get anything drawn on the LCD. Is there a parameter that needs to be set so I only have to redraw the LCD if something changes? Am I using an outdated library? Is there a better library I should be using?

**EDIT**

I think the main problem I have with using this library is does the Draw loop need to be executed continuously to display on the LCD or is there a way to only draw the screen once until it is needed to be drawn again?

body:
You haven't shown us all the code – in particular, the call to `Draw()` from `loop()` is missing – so this answer is speculative, based on the assumption your `loop()` is as follows.

    void loop(void) {
        Draw();
    }

If so, your first bit of code will constantly redraw because `loop()` runs repeatedly without delay.  Try adding a `delay(1000);` after `Draw()` in that case.

Your second bit of code will begin by drawing your image once, and in that `Draw()` call it will set `needsUpdate` to false.  Then `loop()` runs again, and the `firstPage()` call erases the screen.  Since `needsUpdate` now is false and remains false, subsequent calls don't draw an image.

Rather than putting your picture loop into `Draw()`, perhaps use `Draw()` just to draw primitives, and keep your controls in `loop()`:

    void loop(void) {
      Display.firstPage();
      do {     // picture loop
        Draw();
      } while( Display.nextPage() );
      delay(1000); // delay before next picture
    }

If you still get repeated fast redraws, for troubleshooting comment out the `do` and `} while` lines.


body:
Much thanks to jwpat7 for getting me on the right track with this. So I found out how this LCD should really be setup. I am not sure why the examples I was able to find online and even on the u8glib wiki showed the usage like my question but I was able to get this library functioning right.

First thing is the .firstPage() and .nextPage() functions. The .firstPage() function actually clears the screen and the .nextPage() function displays what is waiting in the queue (thanks jwpat7). When the .nextPage() finishes there is no need to write to the LCD again until you need a refresh. I put together a very simple code example that uses a input to change the text without having to continuously update the LCD.

    U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
    bool redraw = true;
    String strOut = "This is a test...";

    void loop() {

     if (redraw){
      Display.firstPage();  //Clear the LCD

            //Main Difference while the LCD needs drawing will return 1
      while(Display.nextPage()){
       Display.setFont(u8g_font_04b_03b);
       Display.setPrintPos(20, 20);
       Display.print(strOut);
      }

      redraw = false;  //Clear flag to redraw
     }

        //check if any of the pins in PINA have been pressed
     if (~PINA & 0xff){
      strOut = "Of the emergency broadcast ...";

            redraw = true; //Set flag to redraw the screen
     }
    }


message:
Multiple RGB LEDs

I'm quite new to these things and I need some help. I'm building a computer shelf with plexiglass and RGB LEDs (one per length) and I need some help to sketch up a data sheet of some sort for this.

I'm thinking of using an Arduino Uno, but will it be able to run 12+ LEDs?

body:
If your RGB LEDs are [WS2812-style, 5050-size](http://www.ebay.com/sch/i.html?_odkw=WS2812+7++5050++Round&_osacat=0&_from=R40&_trksid=p2045573.m570.l1313.TR2.TRC0.A0.H0.XWS2812+++5050++.TRS0&_nkw=WS2812+++5050++&_sacat=0) units, it is no problem to control dozens of them using an Arduino Uno or several other models of Arduinos.  [For ATtiny systems, other libraries than [Adafruit's NeoPixel](http://www.adafruit.com/category/168) may be needed; the NeoPixel library keeps several bytes of state data per pixel, which some other libs don't.]

WS2812-style LEDs typically are arranged in serial strings, driven by a single IO pin from an Arduino.

If you have more than half a dozen WS2812s in the string, power for them should come from an external power supply, rather than via an Arduino's built-in 5V regulator.

For more information, see related questions like *[Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns](https://arduino.stackexchange.com/q/10357)*, and *[Arduino and WS2812 RGB LED Strip "freezing"](https://arduino.stackexchange.com/q/17940)*, and  *[fading colors on a ws2812 strip](https://arduino.stackexchange.com/q/13136)*; also see [Google search Arduino Stackexchange for WS2812](https://www.google.com/search?num=50&hl=en&q=site:arduino.stackexchange.com/questions+WS2812+-newest+-recently).


message:
Error opening serial port 'COM1'. (Port busy)

Im using the arduino Micro pro to read the data out of a temperature sensor (lm35). The program is compiling and NOT uploading, but when I try and open the serial monitor is says: Error opening serial port 'COM1'. (Port busy)

body:
I've got an idea. Your board isn't being recognized. Try unplugging the arduino and see if Com 1 is still there. Sometimes it can recognize mice and other devices as Com 1 or 2 instead of your arduino.

On some of my development machines after everything settled out my devices will show up on Com 4 and 5 when I am working on two at a time.

If this is not the case go into the device manager and see if you can see the board listed.

I would also wonder if you have your sensor hooked to digital pins 0 and 1. These pins are used for your serial line on usb. So if you have anything such as a sensor hooked to them it may be generating data keeping the line busy instead of it being able to negotiate.

I had this happen when setting up hc-05 for the first time. I realized I had to keep the chip off while flashing or I would end up with errors or Com busy.

Please provide your pinout and basic information about the Com ports available on the ide. Also consider that you will need to specify the correct board as it will default to an uno.

Programmer not in sync issues generally occur because the board is recognized but cannot be written to for one reason or another.

- the board has something plugged into digital 1 and 0 which are serial i/o pins
- the board programmer is busy running your last batch of code
- usb error

So

- try a different cord
- try unplugging potential wiring issues and see if it can be written to without anything on it
- try holding down reset on the board until the board when you try to write to it until just after it finishes compiling to clear any potential programing issues

In my experience mega have a tendency to suffer from the last one.


body:
Simple solution:

Close the arduino application and start again.

if still the issue persist restart your system. :)


body:
I had a similar issue (port busy, RN42+Win 8.1) and find a solution by changing the usb bluetooth dongle of the computer.

The one which finally works for me was the Adafruit [Bluetooth 4.0 USB Module (v2.1 Back-Compatible)].

[Bluetooth 4.0 USB Module (v2.1 Back-Compatible)]:https://www.adafruit.com/product/1327


message:
How does this eBay relay board connect to the Arduino

I bought a [single channel relay][1] on eBay and besides the NC/COM/NO, it has six pins and a jumper.

[![relay][2]][2]

It is not possible to see the labels on the image, but the labels are:

    X  X--X  X  X  X
    VCC   -IN+   GND

The default jumper position is shown above with a `-` mark.

Which pins should I use for VCC, GND and ARDUINO? Is the jumper on the correct position?

  [1]: http://www.ebay.com/itm/5V-10A-one-1-Channel-Relay-Module-With-optocoupler-For-PIC-AVR-DSP-ARM-Arduino-/310636242802
  [2]: https://i.stack.imgur.com/PicO1.jpg

body:
Your module consists of both an optocoupler (large black rectangular device) and a P-channel MOSFET driver circuit for the relay.

VCC and GND are used to power the MOSFET and relay, and so should be connected to a power source suitable for driving the relay (if it's a 5V relay then the +5V and GND pins of the Arduino - if it's a 12V relay then a 12V power supply).

The interface to the Arduino is through the optocoupler. The Arduino sees that as just an LED, so you can wire it up just like any other LED.  The circuit contains a current limiting resistor already, so you don't need to worry about that at all.  So you connect the - of the input to GND and the + to an IO pin, or connect the + to +5V and the - to the IO pin, depending on which polarity of drive you want to have.

The jumper is optional to allow you to create one of those two links on the board - say connecting - to GND or connecting + to VCC so you don't need the extra wire.


body:
You should do a bit of testing. The Vcc and GND pins will go to power and ground respectively. They are powering the circuitry on the board that protects the Arduino from the relay coil. Then it looks like the IN pins allow you to operate the relay either from an active high or an active low signal.

If you have a DMM check the connections of the pins (see if any of them are common). The thing that is puzzling to me is the jumper, but it may be set up so that you can use only two wires to control the relay by using the IN terminal to also supply either Vcc or ground.

So start out by hooking up to power and ground, and then test by jumping the IN pins to ground and power in turn. I would expect the relay to operate when the IN+ goes to Vcc or when the IN- goes to GND.


message:
Using ATtiny85, NRF24L01+, DHT2: can't get data from DHT22

I am trying to make a sensor that gets temperature and humidity values from a DHT22 and send it through NRF24L01+ to a Raspberry Pi 2 Model B.

To connect NRF24L01+ to ATtiny85 and to free two pins for the DHT22, I used [this link][1].

There is a scheme of my sensor:
[![enter image description here][2]][2]

There is a photo of the test board with the sensor (sorry, it is very untidy, because I remade it many times before to fix the problem):
[![enter image description here][3]][3]

I program the ATtiny85 with Arduino IDE (with 8 MHz clock).

I used [this library][4] and radio communication is working perfectly (it can't be an error during the radio transmission).

Here is the code of my ATtiny85:

<!-- language: c -->

    #include <DHT.h>
    #include <RF24.h>

    byte currentNodeAddr[6] = "1Node";  // Address of this node

    // Struct for sending measured data
    struct Data {
      uint16_t temp;  // Temperature value
      uint16_t hum;   // Humidity value
      int status;     // DHT22 module status
    } data;

    RF24 radio(2,2);  // Create instance of RF24 radio object
    DHT dht;          // Create instance of DHT22 module object

    void setup() {
      // Set up the radio
      radio.begin();
      radio.openWritingPipe(currentNodeAddr);
      radio.stopListening();
      dht.setup(3); // Set up the sensor on PB3 pin
    }

    void loop() {
      // This DHT library can calculate the delay but it may be 2+ sec
      delay(dht.getMinimumSamplingPeriod());
      // Get values from DHT22
      data.temp = dht.getTemperature();
      data.hum = dht.getHumidity();
      radio.write(&data, sizeof(Data));  // Send data to the Raspberry
    }

But I can't the get temperature and humidity values from the DHT22. I used a lot of different libraries for DHT22 (for example, *github.com/ringerc/Arduino-DHT22, github.com/nethoncho/Arduino-DHT22, github.com/jscrane/DHT22*, etc.) and none of them works (they return zeros, NAN, or, generally, timeout error). And it seems that the connection with the DHT22 is correct (there were connection errors and I fixed them). I tried to use a lot of DHT22 modules, so the problem can't be a defective module.

Yes, I put a 2 second (and more) delay in between read requests. Yes, I added a 10k resistor between pin 1 and 2 of the DHT22.

Now I am thinking that the libraries work fine, but may be free pins (PB3 or PB4) of ATtiny85 can't receive data for some reason.

Tell me please where may be an error or a bug? Thank you in advance! And also many thanks to authors of all links and repositories that I have mentioned here!

**EDIT (in accordance with frarugi87's answer):**

At first I have grounded 3 and 4 pins of the DHT22.

When I program ATtiny at the **1 MHz**, values are sent every 2 seconds (as it should be), but when I program ATtiny at **8 MHz**, values are sent every 16 seconds (is it correct?).

I used the suggested code to check the radio library and it seems it works pretty well (values are being incremented and sent):
[![Test radio library][5]][5]

After that I used the suggested library ([RobTillaart/Arduino][6] v. 0.1.21) and at first time it returned some strange values (humidity and the status were 0 and temperature was MAX_INT value), but when I have tried to get only status value as string, the library also has returned -2 (DHTLIB_ERROR_TIMEOUT). This time I program ATTiny at 8 MHz:
[![enter image description here][7]][7]

Also I tried to get values without NRF24L01+ through I2C connection between the ATtiny85 and the Raspberry Pi. Result was the same (DHTLIB_ERROR_TIMEOUT):
[![enter image description here][8]][8]

Maybe the problem is in timings of ATtiny85 or in the program process?
I used these links ([1][9], [2][10], [3][11]) to set up Arduino IDE on Raspbian.

**Here is list of useful links for this project which I found to implement it (I hope the authors will not mind that I posted their links here)**:

Arduino/AVR DHT projects and libraries:

 - [Arduino Wireless Weather Station](http://www.instructables.com/id/Arduino-Wireless-Weather-Station/)
 - [Mini weather station with Attiny85](http://www.instructables.com/id/Mini-weather-station-with-Attiny85/)
 - [Easy IoT weather station with multiple sensors](http://www.instructables.com/id/Esay-IoT-Weather-Station-With-Multiple-Sensors/)
 - [ATtiny84 & RFM12B wireless sensor node](https://github.com/nathanchantrell/TinyTX)
 - [DHT11 HUMIDITY & TEMPERATURE SENSOR MODULE](http://www.uugear.com/portfolio/dht11-humidity-temperature-sensor-module/)
 - [DHT22 running @ 8MHZ](http://forum.arduino.cc/index.php?topic=269216.0)
 - [DHT22 not working with 8mhz clockspeed?](http://forum.arduino.cc/index.php?topic=97915.0)
 - [Adafruit DHT Library and ATtiny85](http://forum.arduino.cc/index.php?topic=124457)
 - [Class for DHTxx sensors](http://playground.arduino.cc/Main/DHTLib)
 - [An Arduino library for reading the DHT family of temperature and humidity sensors](https://github.com/markruys/arduino-DHT)
 - [Using a RHT03 (aliases: RHT-22, DHT22, AM2302) temperature/humidity sensor from Arduino](http://blog.ringerc.id.au/2012/01/using-rht03-aliases-rht-22.html)
 - [Arduino-library for DHT11/DHT22 sensors reading](https://github.com/amperka/dht)
 - [Efficient DHT library for Arduino](https://github.com/markruys/arduino-DHT)
 - [Feuchtesensor AM2302/DHT22](http://www.pgollor.de/cms/?page_id=1013)
 - [7 Segment Digital Thermometer using ATtiny 85](http://www.instructables.com/id/7-Segment-Digital-Thermometer-using-ATtiny-85/?ALLSTEPS)
 - [Wiring up DHT humidity sensors](https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/wiring)
 - [Attiny85 RF Transmitter to Arduino Uno Receiver](http://www.instructables.com/id/Attiny85-RF-Transmitter-to-Arduino-Uno-Receiver-Ma/)
 - [Arduino library for the DHT22 humidity and temperature sensor](https://github.com/nethoncho/Arduino-DHT22)
 - [Arduino library for DHT11DHT22, etc Temp & Humidity Sensors](https://github.com/adafruit/DHT-sensor-library)
 - [A simplified DHT11/DHT22/AM2302 library for use with the Trinket/Gemma](https://github.com/adafruit/TinyDHT)
 - [Arduino library for the DHT22 humidity and temperature sensor ](https://github.com/nathanchantrell/Arduino-DHT22)
 - [Arduino sketch code for reading RHT03 (also known as DHT22, RHT22, and AM2302) temperature/humidity sensor](https://github.com/ringerc/scrapcode/blob/master/arduino_avr/RHT03_DHT22_humidity_temp_sensor.c)

Arduino/AVR nRF24L01 projects and libraries:

 - [Optimized fork of nRF24L01 for Arduino and Raspberry](https://github.com/TMRh20/RF24)
 - [Optimized Network Layer for nRF24L01(+) Radios on Arduino and Raspberry Pi](https://github.com/TMRh20/RF24Network)
 - [nrf24l01+ control with 3 ATtiny85 pins](http://nerdralph.blogspot.ru/2014/01/nrf24l01-control-with-3-attiny85-pins.html)
 - [NRF24L01 real life range test](https://hallard.me/nrf24l01-real-life-range-test/)
 - [Optimized fork of nRF24L01 for Arduino and Raspberry Pi](https://github.com/edoardoo/RF24)
 - [NRF24L01 SIX CHANNELS TO ONE RECEIVER](https://www.itead.cc/blog/nrf24l01-six-channels-to-one-receiver)
 - [Arduino attiny support files for nRF24L01 RF modules](https://github.com/stanleyseow/attiny-nRF24L01)
 - [ARDUINO + RASPBERRY PI Switching light with NRF24l01+](http://hack.lenotta.com/arduino-raspberry-pi-switching-light-with-nrf24l01/)

Programming the ATtiny85 from Raspberry-Pi:

 - [Programming the ATtiny85 from Raspberry Pi](http://www.instructables.com/id/Programming-the-ATtiny85-from-Raspberry-Pi/?ALLSTEPS)
 - [Arduino IDE Installation](https://projects.drogon.net/raspberry-pi/gertboard/arduino-ide-installation-isp/)
 - [Arduino for other Chips](http://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips)
 - [Tiny AVR Programmer Hookup Guide](https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/attiny85-use-hints)
 - [ATtiny85 with Arduino IDE and Gertboard](https://www.raspberrypi.org/forums/viewtopic.php?f=42&t=76639)
 - [Setting up the Arduino IDE on Raspbian](http://spellfoundry.com/sleepy-pi/setting-arduino-ide-raspbian/)

Arduino/AVR FR433 libraries:

 - [433Kit is a collection of code and documentation designed to assist you in the connection and usage of RF 433MHz transmit and receive modules to/with your Arduino and Rapberry Pi](https://github.com/ninjablocks/433Utils)
 - [Tiny AVR Programmer Hookup Guide](https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/attiny85-use-hints)

Troubleshooting:

 - [Wrong reading value for DH22 & get stuck after running for a while](https://community.particle.io/t/wrong-reading-value-for-dh22-get-stuck-after-running-for-a-while/11271)
 - [DHT22 Sensor - sync timeout](http://forum.arduino.cc/index.php?topic=91569.0)

  [1]: http://hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2
  [2]: https://i.stack.imgur.com/Ip0Y4.png
  [3]: https://i.stack.imgur.com/52X6K.jpg
  [4]: http://github.com/TMRh20/RF24
  [5]: https://i.stack.imgur.com/m8oH8.png
  [6]: https://github.com/RobTillaart/Arduino
  [7]: https://i.stack.imgur.com/XnmDS.png
  [8]: https://i.stack.imgur.com/RcpKr.png
  [9]: http://spellfoundry.com/sleepy-pi/setting-arduino-ide-raspbian/
  [10]: https://www.raspberrypi.org/forums/viewtopic.php?f=42&t=76639
  [11]: https://projects.drogon.net/raspberry-pi/gertboard/arduino-ide-installation-isp/

body:
Ok, let's troubleshoot it.

Try with the following sketch:

    #include <RF24.h>

    byte currentNodeAddr[6] = "1Node";  // Address of this node

    // Struct for sending measured data
    struct Data {
      uint16_t temp;  // Temperature value
      uint16_t hum;   // Humidity value
      int status;     // DHT22 module status
    } data;

    RF24 radio(2,2);  // Create instance of RF24 radio object

    void setup() {
     // Set up the radio
     radio.begin();
     radio.openWritingPipe(currentNodeAddr);
     radio.stopListening();
     data.temp = 0;
     data.hum = 1;
     data.status = 2;
    }

    void loop() {
     data.temp++;
     data.hum++;
     data.status++;
     radio.write(&data, sizeof(Data));
     delay(2000);
    }

You should see a bunch of data being sent to the raspberry every second (you should see `temp = 1, hum = 2, status = 3` then, after two seconds, `temp = 2, hum = 3, status = 4` and so on. Of course you need something to display the data.

If there is some problems then it's the radio library fault, otherwise let's integrate the DHT22.

So, AFTER having tried the previous sketch and confirming that everything is working, download the library from [here][1], install it and then use this sketch:

    #include <RF24.h>
    #include <dht.h>

    dht DHT;

    const byte DHT22_Pin = 3;

    byte currentNodeAddr[6] = "1Node";  // Address of this node

    // Struct for sending measured data
    struct Data {
      uint16_t temp;  // Temperature value
      uint16_t hum;   // Humidity value
      int status;     // DHT22 module status
    } data;

    RF24 radio(2,2);  // Create instance of RF24 radio object

    void setup() {
     // Set up the radio
     radio.begin();
     radio.openWritingPipe(currentNodeAddr);
     radio.stopListening();
    }

    void loop() {
     data.status = DHT.read22(DHT22_Pin);
     data.temp = (int)DHT.humidity;
     data.hum = (int)DHT.temperature;

     radio.write(&data, sizeof(Data));

     delay(2000);
    }

Now, instead of displaying increasing numbers, it should say the temperature, the humidity and, most important, the status:

     0 -> OK
    -1 -> ERROR_CHECKSUM
    -2 -> ERROR_TIMEOUT
    -3 -> ERROR_CONNECT
    -4 -> ERROR_ACK_L
    -5 -> ERROR_ACK_H

Check if this works.

**IMPORTANT NOTE**: I read somewhere that sometimes the ground pin on the DHT is 3 instead of 4. Try grounding both pins if something does not work.

  [1]: https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib


body:
Thanks to Rob Tillaart, the autor of the Arduino DHT [library][1] suggested by @frarugi87 (also thank him), the problem has been solved (see **[this issue][2]** for more information).

In my case **to fix the problem** there is only needed to to set a specific value of `DHTLIB_TIMEOUT` by leaving the definition `#define DHTLIB_TIMEOUT 1000` in the `dht.h` file of this library and commenting other definitions written next to it:

    // #ifndef F_CPU
    #define DHTLIB_TIMEOUT 1000 // should be approx. clock/40000
    // #else
    // #define DHTLIB_TIMEOUT (F_CPU/40000)
    // #endif

The ATtiny is programmed on 8 MHz. The DHT22 is working at a voltage of 3.3V with a **3K3** resistor.

The cause of the problem may be the way I program the ATtiny85 with old version of Arduino IDE installed in the Raspberry Pi (see comments to the @frarugi87's answer).

Libraries used:

 - [RobTillaart/Arduino DHT11, 21, 22, 33 library](https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib)
 - [Arduino driver for nRF24L01 http://maniacbug.github.com/RF24](https://github.com/maniacbug/RF24)

Here is the final code of the ATtiny85 transmitter and the Raspberry Pi reseiver respectively (**I took the most part of the code from different examples of RF24 libraries and DHT libraries! Excuse me, if the code is not tidy.**).

**NRF24Transmitter.ino:**

 #include <dht.h>
 #include <RF24.h>

 #define DHT22_PIN 3
 #define LONG_DELAY_MS 900000

 byte currentNodeAddr[6] = "1Node";  // Address of this node

 // Struct for sending measured data
 struct Data {
   float temp;  // Temperature value
   float hum;   // Humidity value
   int status;     // DHT22 module status
 } data;

 RF24 radio(2,2);  // Create instance of RF24 radio object
 dht DHT;          // Create instance of DHT22 module object

 void setup() {
   // Set up the radio
   radio.begin();
   radio.openWritingPipe(currentNodeAddr);
   radio.stopListening();
 }

 void loop() {

   unsigned long startMillis = millis();
   while (millis() - startMillis < LONG_DELAY_MS);

   do {
  data.status = DHT.read22(DHT22_PIN);
  data.temp = DHT.temperature;
  data.hum = DHT.humidity;

  if (data.status != DHTLIB_OK) {
    delay(1000);
  }

   } while(data.status != DHTLIB_OK);

   radio.write(&data, sizeof(Data));  // Send data to the Raspberry
 }

**Receiver.cpp:**

 #include <cstdlib>
 #include <iostream>
 #include <sstream>
 #include <string>
 #include <unistd.h>
 #include <RF24/RF24.h>

 using namespace std;

 uint8_t addresses[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node"};

 // Struct for sending measured data
 struct Data
 {
  float temp;  // Temperature value
  float hum;   // Humidity value
  int status;     // DHT22 module status
 } data;

 RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

 int main(int argc, char** argv)
 {
  uint8_t currentPipe = 1;
  data.temp = -888;
  data.hum = -888;

  printf("BEGIN: %d\n", (int)radio.begin());

  radio.setAutoAck(1);
  radio.setRetries(15,15);
 // radio.setDataRate(RF24_1MBPS);
 // radio.setPALevel(RF24_PA_MAX);
 // radio.setCRCLength(RF24_CRC_16);

  radio.openReadingPipe(1, addresses[0]);
  radio.openReadingPipe(2, addresses[1]);
  radio.openReadingPipe(3, addresses[2]);
  radio.openReadingPipe(4, addresses[3]);
  radio.openReadingPipe(5, addresses[4]);

  radio.startListening();

  radio.printDetails();

  sleep(1);

  cout << "Start!" << endl;

  while(true)
  {
   cout << "Waiting for data..." << endl;

   while (radio.available(&currentPipe))
   {
    cout << "Reading: " << addresses[currentPipe - 1] << "..." << endl;

    radio.read(&data, sizeof(Data));

    cout << "Temp: " << data.temp << endl;
    cout << "Hum: " << data.hum << endl;
    cout << "Status: " << data.status << endl;
   }

   sleep(1);
  }

  return 0;
 }

**Here is Makefile to compile the receiver.cpp:**

 #############################################################################
 #
 # Makefile for librf24 examples on Raspberry Pi
 #
 # License: GPL (General Public License)
 # Author:  gnulnulf <arco@appeltaart.mine.nu>
 # Date:    2013/02/07 (version 1.0)
 #
 # Description:
 # ------------
 # use make all and make install to install the examples
 # You can change the install directory by editing the prefix line
 #
 prefix := /usr/local

 # Detect the Raspberry Pi by the existence of the bcm_host.h file
 BCMLOC=/opt/vc/include/bcm_host.h

 ifneq ("$(wildcard $(BCMLOC))","")
 # The recommended compiler flags for the Raspberry Pi
 CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s
 endif

 # define all programs
 #PROGRAMS = scanner pingtest gettingstarted
 PROGRAMS = receiver #gettingstarted gettingstarted_call_response transfer pingpair_dyn test
 SOURCES = ${PROGRAMS:=.cpp}

 all: ${PROGRAMS}

 ${PROGRAMS}: ${SOURCES}
  g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@

 clean:
  rm -rf $(PROGRAMS)

 install: all
  receiver -d $(prefix) || mkdir $(prefix)
  receiver -d $(prefix)/bin || mkdir $(prefix)/bin
  for prog in $(PROGRAMS); do \
    install -m 0755 $$prog $(prefix)/bin; \
  done

 .PHONY: install

  [1]: https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib
  [2]: https://github.com/RobTillaart/Arduino/issues/30


message:
Does ATmega328 on Uno need to be burned?

I'm new to the Arduino world so please bear with me. I'm not sure whether the ATmega328 bootloader needs to be burned. What I'm reading is all that needs to be done is plug the board into the computer by USB cable. Then burning the 328 is also mentioned. I appreciate any help.

body:
If you bought an Arduino Uno the bootloader comes pre-programmed.

"The ATmega328 on the Uno comes preprogrammed with a bootloader that allows you to upload new code to it without the use of an external hardware programmer. It communicates using the original STK500 protocol (reference, C header files)." - from the [oficial page][1].

Might want to take a look at [this][2] discussion if you're confused.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: http://forum.arduino.cc/index.php?topic=153154.0


body:
You only ever need to burn a bootloader if:

1. You are building your own "breadboard" Arduino
2. You have somehow erased the bootloader that is on your Arduino
3. You have replaced the original chip on the Arduino

The chip that came already inserted into the Arduino board already has the bootloader installed into it.


body: It depends. If you bought the arduino from most places, it will be already be burned. However, some less reputable sources might not burn it. If the LED on pin 13 blinks when you power on the arduino, that means the bootloader is installed.


message:
Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino

[Intel Edison Kit for Arduino Hardware Guide][1] instructs:

    echo 28 > /sys/class/gpio/export
    echo 27 > /sys/class/gpio/export
    echo 204 > /sys/class/gpio/export
    echo 205 > /sys/class/gpio/export
    echo 236 > /sys/class/gpio/export
    echo 237 > /sys/class/gpio/export
    echo 14 > /sys/class/gpio/export
    echo 165 > /sys/class/gpio/export
    echo 212 > /sys/class/gpio/export
    echo 213 > /sys/class/gpio/export
    echo 214 > /sys/class/gpio/export
    echo low > /sys/class/gpio/gpio214/direction
    echo high > /sys/class/gpio/gpio204/direction
    echo high > /sys/class/gpio/gpio205/direction
    echo in > /sys/class/gpio/gpio14/direction
    echo in > /sys/class/gpio/gpio165/direction
    echo low > /sys/class/gpio/gpio236/direction
    echo low > /sys/class/gpio/gpio237/direction
    echo in > /sys/class/gpio/gpio212/direction
    echo in > /sys/class/gpio/gpio213/direction
    echo mode1 > /sys/kernel/debug/gpio_debug/gpio28/current_pinmux
    echo mode1 > /sys/kernel/debug/gpio_debug/gpio27/current_pinmux
    echo high > /sys/class/gpio/gpio214/direction

However line 3 already gives an error:

    echo: write error: No such device

Any suggestions on how to enable I2C?

  [1]: http://download.intel.com/support/edison/sb/edisonarduino_hg_331191008.pdf

body:
It was a strange problem which we were not able to resolve in an acceptable manner after all.

The problem disappeared after we re-flashed the device.


message:
avrdude: stk500_rcv :programmer is not responding

I'm a newbee to Arduino programming and hoping someone can help me with this. These are the error messages.

avrdude: stk500_rcv() : programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10:not in sync:

Problem uploading to board.

I'm using a Arduino UNO clone on com port 3,the blink sketch is functioning. I get the mentioned error message on all sketches I have ran. Not sure what to do.

body: try this site: https://github.com/Makeblock-official/Makeblock-USB-Driver/ , it works for me. This is a driver for arduino, and command for bash


body:
You mentioned arduino uno clone, do you know what USB chip it's using and what chip you are uploading the sketches to?

The clone I have is very fussy and hangs up continuously. I have had luck once or twice with uploading the sketches. Depending on the chips on the board downloading the proper driver will help and selecting the proper chip under the board setting i.e. Atmega328 or atmega8 depending on the chip. Hope this helps as it worked for me.


body:
I had a same problem with UNO R3 (CH340G) MEGA328P for Arduino UNO R3

On Ubuntu 14.04 I checked the whether the USB chip not recognized, but it looks ok:

    ~$ dmesg | tail -n 6

    [ 3350.417900] usb 2-2: new full-speed USB device number 5 using xhci_hcd
    [ 3350.546759] usb 2-2: New USB device found, idVendor=1a86, idProduct=7523
    [ 3350.546763] usb 2-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    [ 3350.546764] usb 2-2: Product: USB2.0-Serial
    [ 3350.547255] ch341 2-2:1.0: ch341-uart converter detected
    [ 3350.547996] usb 2-2: ch341-uart converter now attached to ttyUSB0

But the upload went wrong like this:

    ~$ avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -Uflash:w:/home/oliver/Arduino_Build/Blink/Blink.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/oliver/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : stk500v1
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    ....

After reading bunch of articles [1], [2], [3], [4], [5], [6] it turned out my bad Chinese Arduino clones does not have bootloader installed on the Atmel microcontroller ship. To solve this problem you need a working Arduino and the clone Arduino we want to fix.

Walk trough who to burn the bootloader: http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/

Shortly: Burn the bootloader
----------------------------

[![Arduino as ISP][7]][7]

 1. You need a working Arduino
 2. Connect the working Arduino with a usb to the computer
 3. Upload `Examples->ArduinoISP` on working Arduino
 4. Connect the wires from the working Arduino to the clone as follows:
  - Pin 10 goes to reset pin
  - Pin 11 -> 11, 12 -> 12, 13 -> 13
  - 5v to 5v and ground to ground
 5. Go to `Tools->Board` and select the chinese board that is not working. in my case it's an Arduino Uno.
 6. Go to `Tools->Programmer` and select `Arduino as ISP`.
 7. Go to Tools again and select "Burn Bootloader".
 8. Your clone should work just fine now, but don't forget to restore Programmer (set back to ArduinoISP or AVRISP).

My clone board does not had integrated LED on 13 pin :) you need to connect it for Blinking test.

  [1]: https://www.quora.com/What-is-the-difference-between-Arduino-Uno-R3-compatible-board-ATmega328P-ATmega16U2-and-Arduino-Uno-R3-ATmega328P-USB-board-CH340G-Which-should-I-buy-and-why
  [2]: https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi
  [3]: http://forum.arduino.cc/index.php?topic=186413.0
  [4]: http://forum.arduino.cc/index.php?topic=289518.0
  [5]: http://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
  [6]: https://arduino.stackexchange.com/questions/25135/how-can-i-fix-the-error-stk500v2-getsync-timeout-communicating-with-program/25136
  [7]: https://i.stack.imgur.com/TBWOB.png


body:
I assume that you're trying to upload the code with the Rx and Tx pins connected..
Try removing the Rx and Tx and then click the upload button in the IDE..

This happens because your computer communicates with the Arduino via Serial communication. The Rx and Tx pins also do communicate via Serial communication. An Arduino does not have the capability to handle two such communications simultaneously. So, it goes out of sync.. And that's how you get this error...


body:
I'm not familiar with Arduino Uno, but in case of a Nano switching to another **Processor** in the **Tools** menu of the Arduino IDE solved the problem for me. For my Nano the `ATmega328P (Old Bootloader)` is the one that works, maybe there is a similar option for Uno.

Steps and screenshot: https://gyorgybalassy.wordpress.com/2020/10/16/arduino-programmer-is-not-responding-not-in-sync-error/


message:
Simple Speed question - Mapping PWM values

I am working on an Arduino project for school to power a 12V DC cooling fan.

I want to adjust the speed of the fan. The instructions say to set the motor pin at an equation of `(0 to 9) * 10 + 150` to get a range of 150 to 240.

I need to write a mathematical equation but can not figure out what 150 to 240 means.  Is this voltage, resistance...?  Thanks for the help.

body:
They're the value to pass to `analogWrite()` in order to generate a PWM waveform with an appropriate duty cycle.

But don't bother writing your own algorithm, just use <a href="https://www.arduino.cc/en/Reference/Map">`map()`</a>.


body:
The `analogWrite()` function takes a value that is between 0 (fully off) and 255 (fully on).

Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

* (150 / 255) * 100 = 58.8% on time
* (240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive.  Let's call this value "*i*".  You want an output value, let's call it "*o*".

The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula.  0-9 is *i*, remember:

* *o = i × 10 + 150*

If *i* is 0 then *o* = *0 × 10 + 150* = *0 + 150* = *150*.

If *i* is 9 then *o* = *9 × 10 + 150* = *90 + 150* = *240*.

As Ignacio mentions, the Arduino API has a `map` function which is meant to be used for this kind of thing;

    o = map(i, 0, 9, 150, 240);

*However:* the `map()` function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.


body:
The [map()][1] function is the answer. It "rescales" the range of the data, using this formula:

    (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

You input these five values:

    map(value, fromLow, fromHigh, toLow, toHigh)

 - `value` is the X value you want to resize
 - `fromLow` and `fromHigh` is the range that X is currently in
 - `toLow` and `toHigh` is the range that you want to scale X to

  [1]: http://labs.arduino.org/map


message:
Peer to peer communication

Hello guys ,
             I want to perform a mesh network between 3-4 modules using ESP8266 . Any one have idea how to do it?

body:
You can't, that's not how the esp8266 works.

The esp8266 is WiFi, so you will either need an access point or nominate one esp8266 module to act as an access point running in softap mode.


body:
Peer to Peer Example
Written by Stewart Meyer (engineer retired from the FAA).
This is first time that I have given an answer, hope you can read this:

Not only can the ESP8266 connect to a WiFi network and interact with the Internet, but it can also set up a network of its own, allowing other devices to connect directly to it. This example demonstrates how to turn the ESP8266 into an access point (AP) also called a server, and serve up data to any connected client also called a station.

Server (Access Point)
First we will look at the server:

    /* Server
    *  We write the server first because we need its IP address
    */

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    const char* ssid = "Meyer";       // ssid of server (Access Point (AP))
    const char* password = "";        // password of server (Access Point (AP))
    WiFiServer server(80);            //Service Port

    int ledPin = 2; // GPIO2 of Server ESP8266

    void setup()
    {
        delay(1000);
        Serial.begin(115200);    // to use tools->serial monitor

        pinMode(ledPin, OUTPUT);   // set GPIO 2 as an output

        WiFi.mode(WIFI_AP_STA);  // Set WiFi to AP and station mode

        // Connect to the WiFi network
        Serial.println();
        Serial.print("Connecting to: "); Serial.println(ssid);
        WiFi.softAP(ssid, password);

        // Display the server address
        Serial.print("Connected, My address: ");
        Serial.print("http://");
        Serial.print(WiFi.softAPIP());
        Serial.println("/");

        // Tell the server to begin listening for incoming connections
        server.begin();
        Serial.println("Server listening for incoming connections");
    }

    void loop()
    {
        // Check if a client has connected
        WiFiClient client = server.available();
        if (!client) // if not available, return
        {
            return;
        }

        // Wait until the client sends some data
        Serial.println();
        Serial.println("Client connected");
        while(!client.available())
        {
            delay(1);
        }

        // Read the request
        String request = client.readStringUntil('\r');
        Serial.print("Request = "); Serial.println(request);

        if (request.indexOf("/ON/") != -1)
        {
            digitalWrite(ledPin, LOW); // turn LED on
        }
        if (request.indexOf("/OFF/") != -1)
        {
            digitalWrite(ledPin, HIGH); // turn LED off
        }

        client.flush();
        Serial.println("Client disconnected");
    }

Client (Station)
Next we will look at the client:

    /*  Client
    *   This client will turn the LED on or off every 5 seconds
    */
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>

    const char* ssid = "Meyer";   // ssid of access point (Server)
    const char* password = "";    // password of access point (Server)
    int port = 80;                // port number

    byte ip[]= {192,168,4,1};

    int LEDstatus = 0;

    WiFiClient client;  // Declare client

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

        WiFi.mode(WIFI_STA);  // set mode to station (client)

        // Connect to wiFi
        Serial.println(); Serial.println();
        Serial.println("CONNECTING TO WiFi");
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED)
        {
            delay(500);
            Serial.print(".");  // print dots until connection
        }
        Serial.println();
        Serial.println("WiFi CONNECTED");
    }

    void loop()
    {
        // Connect client to server
        Serial.println("CONNECTING CLIENT TO SERVER");

        if (client.connect(ip, port))
        {
            Serial.println("CONNECTED");
        }
        else
        {
            Serial.println("CONNECTION FAILED");
        }

        // Send message to control the LED
        if (LEDstatus == 0)
        {
            client.println("/OFF/");
            Serial.println("LED OFF");
            LEDstatus = 1;
        }
        else
        {
            client.println("/ON/");
            Serial.println("LED ON");
            LEDstatus = 0;
        }

        client.println();

        client.flush();

        delay(1);
        Serial.println("CLIENT DISCONNECTED");
        Serial.println();
        delay(5000); // delay 5 seconds
    }


message:
Generating a 38 KHz signal without timers

I am currently trying to generate a 38 KHz signal for my TSOP4838 (http://www.vishay.com/docs/82459/tsop48.pdf) with an ATtiny84A.

I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.

I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).

So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (`micros()`, `millis()` etc.) stopped working and prevented me from using my serial communication. I tried to change the code in `wiring.c` to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.

I am now stuck with two options I guess:

A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.

B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.

I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?

If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()

body:
A 38kHz square wave at 50% duty cycle would be a transition running at 38x2=76kHz.  That is 1/76,000 = 0.000013158s, or 13.158µs.  That's quite a high accuracy to try and achieve with delays on a small chip like the 84A.

I assume you are running it at 8Mhz (internal calibrated RC oscillator) - that means each clock tick is 1/8000000=125ns long. so 13156ns would equate to 105.248 clock cycles. That can't happen, so the closest you would get is 105 clock cycles, which would be 13125ns, or 76.190kHz, or an end frequency of 38.095kHz.  So fairly close.

So now you need to create a tight loop that is *exactly* 105 clock cycles long *including* the toggling of the IO pin *and* the comparisons and branches for the loop.  For that you need to do some careful instruction cycle counting and work in assembly language.  Page 268 of [the data sheet](http://www.atmel.com/images/doc8183.pdf) details the clock cycles used for each instruction.

The simplest (though most long winded) loop would be an OUT or SBR (depending on port) instruction (1 clock) to set the IO pin HIGH, then 104 NOPs (1 clock each), then an OUT or CBR to set it LOW (1 clock), then 102 NOPs (1 clock each), then an RJMP to go back to the start (2 clocks).  That is then a grand total of 210 clock cycles, or 1/(210*0.000000125) = 38.095kHz.

You could compress all the NOP instructions down into a tight loop themselves by setting a register to a pre-defined loop count value, decrement it each pass - repeat if it's not 0. That means even more careful instruction counting to get that loop to equal the 104 or 102 clock cycles needed for the precise timing.

**However** all that is pretty much academic, because the loop will keep being interrupted by your timer 0 interrupt and cause *jitter* in your output as the interrupt routine is being run instead of your IO pin driving loop.

If you don't need absolutely reliable timing anyway it might be easier (though far less accurate) to use the `micros()` function to find when 13µs have elapsed and do it all in C instead of assembly.  You will still need high speed direct port access rather than using `digitalWrite()` since `digitalWrite()` adds way too much overhead to be able to do that kind of timing reliably.  Something like:

    uint32_t start = micros();
    while(1) {
        if (micros() - start >= 13) {
            start = micros();
            PORTB ^= 1<<4; // toggle B4
        }
    }

Note the use of `while (1)` there rather than relying on the `loop()` function repeating itself.  There is quite a large overhead in using the auto-repeating of `loop()` that can be avoided by looping within it with a `while (1)` like that.  Of course, anything else you want to happen repeatedly would have to be inside that `while` loop, and most likely would impact your output timing somewhat.

So a much better solution would be to use a timer, since that is what they are there for.  But fidding with timers breaks things like `millis()` and `delay()`.  So the answer to that is *don't use `millis()` and `delay()`*.  Instead create your own timing functions that are controlled by your own interrupt that does the pin IO - instead of relying on a system provided tick you create your own.  If your interrupt is firing every 13µs then add 13 to a global counter - that counter is then the number of microseconds that have passed.  When that count exceeds 1000 you subtract 1000 (*don't* zero it) and add 1 to a millisecond counter.  Now you have the equivalent to `millis()` in a global (*remember to make it volatile*) variable that you can use instead of `millis()`.


body:
It would be much easier to use a dedicated IC such as a 555 or a 556. I built such a system based on these circuits [IR Bream Break Detector][1]

  [1]: http://www.pcbheaven.com/circuitpages/Long_Range_IR_Beam_Break_Detector/


body:
Several approaches are possible, some of which, but far from all, have been listed in previous answers.  In following, I assume that by “use it as a light barrier” you mean that the TSOP4838 will be part of an object-intrusion detection system, rather than for transmitting data.  As a consequence, some jitter and/or inaccuracy is acceptable.  Note, all of the following methods assume that Arduino core code has set up timer 0 to support ordinary micros() and millis() calls.

Approach 1:  Compute or calibrate a simple loop:  In `setup()`, run a series of tests that find a value `k` to minimize error, via C code equivalent to the following Python:

    for k in plausibleRange():
      err = genBurst19(k)
      if err < bestErr:
        bestErr = err
        bestK = k

where `genBurst19()` is like the following:

    def genBurst19(k):
      t1=micros()
      for i in range(38):
        setPortBit(i&1)
        for j in range(k):
          nop
      t2=micros()
      return abs(t2-t1-500)

In other words, `genBurst19()` sends a burst of 19 cycles, which at 38 KHz should take 500 microseconds.  It returns a measure of error to the caller.

After finding `bestK`, you can subsequently use it as a limit for other delay loops, or could just use repeated calls to `genBurst19(bestK)` whenever you want to generate some "38KHz".

Note, you might wish to try some minor variations, such as adding a second or third `nop` in the inner delay loop, or generating some higher multiple of 19 cycles.  While a delay loop containing a single `nop` (or no `nop` at all, just an empty loop) has finer resolution than a loop with multiple `nop`s, it may happen (depending on loop code) that a smaller error occurs with more.  [But also see Approach 3 regarding fine tuning.]

Summary:  This method is easy to use, has low jitter, but is limited in the accuracy it can attain.

Approach 2:  Use a method analogous to [Bresenham's](https://en.wikipedia.org/wiki/Bresenham's_line_algorithm) to produce a signal with high-accuracy period, on the average, but with more jitter than Approach 1.  Bresenham's algorithm tries to draw a straight line, on an x-y grid of pixels; you are trying to draw a straight line, on a time-vs-cycles grid.

In this method, you keep track of how many microseconds total should have elapsed, and when you fall too far behind, issue a delay with `k-1` instead of `k`, to catch up; or if too far ahead, with `k+1`, to drop back.  See my answer to [stackoverflow 8113883](https://stackoverflow.com/a/8113883) for a little more re Bresenham's method, in the line drawing context.

Summary:  By applying Bresenham's method, you can get the average frequency as close as you like (when averaged over a few milliseconds).

Approach 3:  This is more of a fillip than a whole approach.  It modifies Approach 1 by adding the following C code before the `for j in range(k): nop` loop.  It also needs a second parameter, `l`.

    switch (l) {
      case 9: nop;
      case 8: nop;
      case 7: nop;
      case 6: nop;
      case 5: nop;
      case 4: nop;
      case 3: nop;
      case 2: nop;
      case 1: nop;
      case 0: ;
    }

To use this approach, first find the best `k` using a series of calls like `err = genBurst19(k,5)`.  Then find the best `l` via `err = genBurst19(bestK,l)` for `l` from 0 to 9.  [Note, a number smaller than 9 can be used in the above, if the `for j in range(k): nop` loop uses fewer cycles.]

Summary: This fillip can tune `genBurst19()` closer to single-nop accuracy.


body:
I just built an NE555 based circuit for 38 kHz. Sender is a 950 nm IR diode, receiver is said TSOP4838. According to the [NE555 Data Sheet][1], the frequency in astable mode is *approximately*

f ≈ 1.44 / (C (RA + 2 RB) )

[![NE555 astable circuit][2]][2]

Using values of RA = 1.8 kΩ, RB = 18 kΩ, C = 1 nF, the NE555 should generate a frequency of 38.095 kHz. Using these values, my circuit generated 34 kHz with some small changes of a few 100 Hz when using different resistors/capacitors (due to tolerance), but it came nowhere close to 38 kHz. This is probably because the frequency formula [is an approximation](https://electronics.stackexchange.com/a/228235/135063). The easiest fix is probably to put a variable capacitor in parallel to C and use it for fine tuning, or a variable resistor to RB.

This may not be necessary in every case as the TSOP48xx uses a band pass filter, and 34 kHz are still recognized, only at lower responsivity. Note that this IR receiver (as well as others) have some limitations on pulse length, so you cannot constantly send 38 kHz but only for up to 70/f, which is around 1.8 ms. After that, the TSOP output switches off again, probably because the internal threshold is raised.

[![TSOP48 frequency dependency graph][3]][3]

## Measurements

Some measurements from a logic analyzer (PulseView). This is from the above NE555 circuit which should yield 38 kHz.

[![Logic analyzer screenshot][4]][4]

I used an AND IC ([74HCT08][5]) to modulate a signal, generated by an Arduino, on top of the 38 kHz carrier. Sampling rate is 12 MHz. The probes measure:

* D0: TSOP4838 output signal
* D1: IR signal (`carrier AND signal`)
* D2: Arduino `signal`
* D3: 38 kHz `carrier` from NE555

[![38 kHz modulated IR signal][6]][6]

  [1]: http://www.ti.com/lit/ds/symlink/ne555.pdf
  [2]: https://i.stack.imgur.com/NQDRr.png
  [3]: https://i.stack.imgur.com/6uZdM.png
  [4]: https://i.stack.imgur.com/07Rj3.png
  [5]: http://www.ti.com/lit/ds/symlink/sn74hct08.pdf
  [6]: https://i.stack.imgur.com/OnwGN.png


message:
Read RC receiver channels using Interrupt instead of PulseIn

I am designing my own quadcopter control algorithm, whereby I currently read 4 RC receiver channels using PulseIn on each loop in the following manner:

    ch1_raw = pulseIn(rcPin1, HIGH, 25000);

In other words, ch1_raw contains the length of a HIGH pulse in microseconds.

I now want to avoid PulseIn in the interest of speed and instead achieve the same using interrupt.

I have looked at http://playground.arduino.cc/Main/PinChangeIntExample and I am aware that other similar questions have been asked (e.g. https://arduino.stackexchange.com/questions/16740/how-to-read-rc-receiver-channels-without-using-pulsein-command-with-arduino and https://arduino.stackexchange.com/questions/9465/is-pulsein-fast-enough-for-quadcopter?newreg=1d1811fae8244f409488e6c4dba0d915), but I don't understand how to implement interrupt to give me the correct ch1_raw value on each loop.

Can somebody help me? (I'm new to Arduino, so go easy on me please!) Thanks!

------------------------------

Edit:
So far I have tried to implement the following:

    #include <PinChangeInt.h>

    unsigned long pulsestart, pulsewidth;

    int rcPin1 = A0;

    void setup(){

      pinMode(rcPin1, INPUT);

      Serial.begin(9600);

      PCintPort::attachInterrupt(rcPin1, counttime,RISING);
      PCintPort::attachInterrupt(rcPin1, subtracttime,FALLING);

    }

    void loop(){

      Serial.print("  pulsewidth: ");
      Serial.println(pulsewidth);

    }

    void counttime()
    {
      pulsestart = micros();
    }

    void subtracttime()
    {
      pulsewidth = micros()- pulsestart;
    }

Edit 2:
(Somewhat) successful implementation so far, using EnableInterrupt.h instead. It seems that FALLING is being detected, but not RISING.

    #include <EnableInterrupt.h>

    #define rcPin1 10

    volatile uint16_t pulsestart=0;
    volatile uint16_t pulsewidth=0;
    //volatile unsigned long pulsestart=0;
    //volatile unsigned long pulsewidth=0;
    volatile uint16_t risingcount=0;
    volatile uint16_t fallingcount=0;

    void counttime()
    {
      pulsestart = micros();
      risingcount++;
    }
    void subtracttime()
    {
      pulsewidth = micros()- pulsestart;
      fallingcount++;
    }

    void setup() {
      Serial.begin(9600);
      pinMode(rcPin1, INPUT_PULLUP);
      enableInterrupt(rcPin1, counttime, RISING);
      enableInterrupt(rcPin1, subtracttime, FALLING);
    }

    void loop() {
      //delay(1000);
      Serial.print("risingcount: ");
      Serial.print(risingcount);
      Serial.print(" fallingcount: ");
      Serial.println(fallingcount);
      //Serial.print("pulsewidth: ");
      //Serial.println(pulsewidth);
    }

body:
Interrupts don't obey, or even understand the concept of, the "loop" paradigm.

An interrupt fires when it needs to fire, and if you're reading a PWM signal then that means it's firing hundreds of times a second.

As long as your interrupt is updating a variable that can be read from within the loop, and you ensure that the variable doesn't get updated during your reading of it (Google: *Critical Sections*) then you will always have the most up to date value at your fingertips whenever you need it.

As for the interrupt itself, that's very straight forward - you just need to recognise if it's a rising or falling edge:

* If rising edge: record the timestamp (micros()).
* If falling edge: Subtract the recorded timestamp from the current micros() and store in the global variable.