body:
First, you need a SoftwareSerial interface, since the hardware serial is already used for debugging. To setup a SoftwareSerial this is an example:

    #include <SoftwareSerial.h>

    const byte rxPin = 6; // Wire this to Tx Pin of ESP8266
    const byte txPin = 7; // Wire this to Rx Pin of ESP8266

    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
      delay(1000); // Let the module self-initialize
    }

    void loop() {
      while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got Data from ESP8266: " + inData);
         // The rest of your code...
      }
    }

To send data from ESP8266 back to Arduino try something like this:

    uart.setup(0, 115200, 8, 0, 1, 1 ) -- Change the baudrate to 115200
    -- A simple http server
    srv=net.createServer(net.TCP)
    srv:listen(80,function(conn)
     conn:on("receive",function(conn,payload)
      payload = payload + "\n"
      uart.write(0, payload) -- send it back to Arduino via Serial interface
     end)
          conn:on("sent",function(conn) conn:close() end)
        end)

    uart.on("data", function(data)
     -- When ESP8266 receives data from Arduino, it will trigger this event
    end, 0)


sender: user

message:
Communication via IP adress with Arduino IDE and ESP8266

I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen.

I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks

sender: assistant

body:
After reviewing your codes, I've rewritten them this way, I didn't get a chance to test them though, so try them and let me know.

**Server code: a. Arduino**

    #include <SoftwareSerial.h>

    int ledPin = 13;
    int txPin = 2;
    int rxPin = 3;

    SoftwareSerial wifi(rxPin, txPin);

    void setup() {
        pinMode(ledPin, OUTPUT);
        Serial.begin(115200); // This baudrate is better than 9600
        wifi.begin(9600);
        wifi.println("dofile('wifiserv.lua')"); // This where it goes
        digitalWrite(ledPin, LOW);
        delay(2000); // delay is necessary
    }

    void loop() {
      while(wifi.available())
      {
         digitalWrite(ledPin, HIGH);
         String inData = wifi.readStringUntil('\n');
         if (inData.startsWith("Server IP: "))
            Serial.println(inData); // This is just the Server IP address
         else
            Serial.println("Got new sensor value: " + inData)
      }
      digitalWrite(ledPin, LOW); // This means no data is available
    }

**Server code: b. ESP8266**

    uart.setup(0, 9600, 8, 0, 1, 1 )
    wifi.setmode(wifi.STATION)
    wifi.sta.config("mynet","pass")
    print("Server IP: " .. wifi.sta.getip() .. "\n")

    srv = net.createServer(net.TCP)
    srv:listen(80,function(conn)
     conn:on("receive",function(conn, s)
      data = s:match("sensor=(%w+)")
      data = data + "\n"
      uart.write(0, data)
        end)
    end)

    uart.on("data", function(cmd)
        -- When ESP8266 receives data from Arduino, it will trigger this event
    end, 0)

**Client code: a. Arduino**

    #include <SoftwareSerial.h>

    int ledPin = 13;
    int EP = 9;
    int txPin = 2;
    int rxPin = 3;

    int dato = 10;

    String ip; // Assign this to your server IP

    SoftwareSerial wifi(rxPin, txPin);

    void setup()
    {
      pinMode(ledPin, OUTPUT);
      pinMode(EP, INPUT);
      Serial.begin(115200);
      wifi.begin(9600);
      wifi.println("dofile('wificlie.lua')"); // This where it goes
      delay(2000); // delay is necessary

    }

    void loop()
    {
      long medida = TP_init();
      delay(50);

      if(medida > 1000)
      {
        Serial.println(medida);
        digitalWrite(ledPin, HIGH);

        String cmd = "ip=" + ip + " " + "data=" + String(dato);
        Serial.println("Sending: " + cmd);
        wifi.println(cmd);
      }
      else
      {
        digitalWrite(ledPin, LOW);
      }
    }

    long TP_init()
    {
      delay(10);
      long medida = pulseIn(EP, HIGH);
      return medida;
    }

**Client code: b. ESP8266**

    wifi.setmode(wifi.STATION)
    wifi.sta.config("mynet","pass")

    uart.setup(0, 9600, 8, 0, 1, 1 )
    uart.on("data", function(s)
     uart.write(0, "GoSending!")
     ip = s:match("ip=(%d+.%d+.%d+.%d+)")
     data = s:match("data=(%w+)")
     conn = net.createConnection(net.TCP, 0)
     conn:on("connection", function(c)
      print("connected");
      conn:connect(80,ip)
      conn:send("sensor=" .. data)
      uart.write(0, "Data has been sent successfully")
     end)
    end, 0)


message:
How do I connect this string of LEDs to my Arduino Uno?

I'm an electronics noob. I have this string of LEDs but don't know how to connect them to my Arduino Uno. As they are wired in parallel, there are two wires / four ends. What do I plug where?

[![string of LEDS][1]][1]

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

body:
Connect the negative ( or cathode ) to ground ( 0V )
and the postive ( anode ) to the output pin of the controller.

Firstly connecting that many LEDS directly to a single micro pin is not a good idea. Usually you would need to go through a buffer/driver first which can deliver the correct power to the LEDS.

I'm not that familiar with the UNO but unless that board has a driver circuit on it you might need a few extra components.

[![Basic LED driver][1]][1]

What are the specs of the LEDS?

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


message:
Arduino IDE, Underlying Code and Libraries

I'm trying to better understand what is going on behind the Arduino IDE. First off I am no expert in C or writing firmware to boards but do have experience in real development.

I see currently the Arduino IDE is one big vast library we first select our board.
What I don't understand is where are our header files? The source files for the board you select?

Not only that we use a number of functions already detected within the IDE where are these located also is any of this code editable?

I had a look through the Arduino directory and most of this stuff looks like its Java I was hoping for C files. Thanks for any links, help or info anyone can give.

body:
Just check the [source code](https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino). Specifically look at `Arduino.h`, `main.cpp` and `wiring*`.

These files should also be present in the Arduino application folder somewhere, but you'll have to go through quite a few subfolders to find them.

The different boards have different .h file that will specify the pin-numbers and other chip specific data.

The "auto detect" functionality is done by `keywords.txt` files. At least for libraries. That way if you install a new library with keywords.txt file, the library functions-names are recognized.

The processes of taking all these files, and the users code, and compile it all whole story on it's own.


message:
Flexibility of SoftPot Membrane Potentiometer during the use?

Does anybody have some information or experiences with the flexibility of Spectra Symbol's [SoftPot Membrane Potentiometer] during the use? Is it possible to partly wind it up on a reel (or something similar) and use the remaining part dynamically without loosing precision and control? Are there "ghost touches" caused by the force/pressure of bending/winding the sensor strip? Or should the sensor always be used in a flattened position?

Thanks for any helpful comments.

[SoftPot Membrane Potentiometer]:https://www.sparkfun.com/products/8681

body:
As you can see from this data sheet it will show you examples on how it is used. https://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf

I'd buy a curved one just to make sure, because as it bends, the 2 conductive materials will touch.


message:
Is it possible to package a sketch with dependent libraries for cross-platform compatibility?

I have a complex sketch that I spent many weeks working on, which I am backing up frequently because I'm afraid of losing any of my progress.

I'm wondering if it's common practice to make a self-contained package of the sketch and all its dependencies, so that it can be moved easily to another OS if necessary. My concern is that if my OS crashes and I have to reinstall everything or move to another OS, I might run into library and dependency errors, especially with the libraries that I altered/customized. I need my sketch to be able to compile as quickly as possible on whatever OS I end up using, since it's a home-automation sketch that controls dozens of things around me.

Is this a valid concern? And if so, what are some preferred ways to make a sketch become "self-contained", so that everything necessary is included? Is there some kind of a better version-control system for Arduino sketches that an amateur programmer might not be aware of?

body:
A way to do so is to include all the library files (*.cpp, *.h) in your sketch folder and then include them in your code.

There are many solutions that you might find handy in this link: https://arduino.stackexchange.com/questions/348/how-to-organize-my-arduino-projects-structure-for-easy-source-control


body:
I would suggest switching to [UECIDE](http://uecide.org) instead of the Arduino IDE. (Yes, shameless plug, it's my IDE).

UECIDE has a facility that I dubbed "localizing" a library whereby it copies it into a libraries folder within the sketch folder itself, and that copy of the library is used in preference to any other library named the same in the system.

That means that a sketch and its libraries then become completely self contained in one folder, and it's perfectly possible to have different versions of the same library in different sketches.


message:
How do I create a 9 bit number based on values from 9 digital inputs?

I have 9 pins that are inputs from 9 IR LEDs. I want to combine all their results into one 9 bit number.

example:
pin1 = high,
pin2 = high,
pin3 = high,
pin4 = low,
pin5 = high,
pin6 = low,
pin7 = low,
pin8 = high,
pin9 = low

9 bit number = 111010010

body:
As @KiraSan said, You need something larger than a byte for 9 bits. However:

    int tally;
    tally=0;
    for (char pin=1; pin<=9; pin++) {
        if (digitalRead(pin)==HIGH) {
            tally|=1<<(9-pin);
        }
    }

This is done from memory and is untested, if anyone spots any errors, let me know.

Explanation: tally is the sum (you should do something with this at the end, obviously, or it has no effect). It is defined and set to 0. Then, for each pin (1-9), read the pin; if the pin is high: take the number '1', and double it (9-pin) times; so if pin=9, it is doubled 0 times; for pin=2, it is doubled once (for a total of 2), and so forth. Set this bit on the tally.

Note that this reads digital pin 1 (which happens to be the second pin, the first being pin 0) - this should be marked as "tx" to set in the first bit, not the one referred to as "pin1" (which might be a constant or a variable, and therefore could point to any given pin). This method also assumes the pins are in order - you could easily change it to start from 0, or 7, but they have to be in order.

If you want arbitrary pins, or variable pins, you might try this:

    const PIN_COUNT=9;
    char pins[PIN_COUNT]={13,2,5,4,3,6,7,8,9};
    int tally;

    tally=0;

    for (char pin=0; pin<PIN_COUNT; pin++) {
        if (digitalRead(pins[pin])==HIGH) {
            tally|=1<<pin;
        }
    }

Changes: add PIN_COUNT as a constant at the start, set the order of the pins (which can include any digital pins, including repeating a given pin if you feel so inclined, even after the start of the code.). You can also change them by doing: `pins[0]=1;` - note that they are numbered from 0-8 for 9 pins. Since they now start at 0, the line with << is now adjusted accordingly, as is the line that starts with `for...`.


body:
In your code you would use a 16 bit unsigned integer as your variable. As there is no such thing as a 9 bit type.

If the pins correspond to different ports on your micro, you basically do this:

Read the pin value from the port register, and bit shift to the right bit position then OR with the variable.

Say you had 8 of the LEDS on PORTB (pin 0 - 7 )and the 9th on PORTC (pin 2)

    unsigned int ir_inputs = 0

    ir_inputs = PORTB; //just reads the register directly
    ir_inputs = ir_inputs|((PORTC & 0x04)<<6); //reads the bit on pin 2 then shifts it 6 places to bit 8 (or the 9th bit remember bits always start at 0) and does not affect the other bits

something like that

actually you could put it into a function

    unsigned int getIRinputs(void){
        return (unsigned int)PORTB|((PORTC & 0x04)<<6);
    }
Easy done

Even if you had the inputs on 9 separate ports the principle is the same.
Read, Shift, OR


body:
Something like this:

    typedef union NUM_9_BITS_t {
        unsigned int U;
        struct NUM_9_BITS_FIELD {
            unsigned int BIT0 : 1;
            unsigned int BIT1 : 1;
            unsigned int BIT2 : 1;
            unsigned int BIT3 : 1;
            unsigned int BIT4 : 1;
            unsigned int BIT5 : 1;
            unsigned int BIT6 : 1;
            unsigned int BIT7 : 1;
            unsigned int BIT8 : 1;
            unsigned int BITO : 23;
        } BITS;
    } NUM_9_BITS;

    NUM_9_BITS num;

    num.BITS.BIT0 = digitalRead(PIN0);
    num.BITS.BIT1 = digitalRead(PIN1);
    num.BITS.BIT2 = digitalRead(PIN2);
    num.BITS.BIT3 = digitalRead(PIN3);
    num.BITS.BIT4 = digitalRead(PIN4);
    num.BITS.BIT5 = digitalRead(PIN5);
    num.BITS.BIT6 = digitalRead(PIN6);
    num.BITS.BIT7 = digitalRead(PIN7);
    num.BITS.BIT8 = digitalRead(PIN8);

    Serial.print(num.U);


message:
ESP8266 & websockets

At the moment, I'm using various operating systems and devices like the Raspberry pi to control lights and other stuff over websockets. I use websockets since they added the support on Chrome. I write a lot of Javascript stuff for fun. Websockets allow you to communicate with another server without the need of reloading a page. It's a lot better than Ajax. Once the connection is open with a web server data can travel both ways. No unnecessary headers to send. No unnecessary requests. You just send only the data you want, this in both directions. AND FAST, DAMN FAST.

For example I use Javascript's `requestAnimationframe` to send RGB values (based on music frequency) to lamps connected to the network. `requestAnimationframe` executes approximately at 60 Hz. But that's not the highest speed, I also created some "web controllers" to [control servos][1] and other stuff with touch and mouse events. In that case it probably touches transmission frequencies of 200-300 data packets (normally I use JSON- encoded strings) or more per second.

Websocket servers have also broadcast which allows you for example to control multiple RGB lamps based on the music you play from basically every modern device that has a browser. I don't use "normal" sockets because of the simple fact that there is no support for sockets in a standard web browser. So I would need to create a custom iOS app, custom Windows app, custom Android app. I said that we know that websockets are made for a fast multi-user / multi-device / bidirectional communication. And it should be really fast or it's useless.

Lately I have a lot of fun with electronics and MCUs, so I made even more lamps and stuff controlled from Arduinos, ATtinys and other microcontrollers. I'm new to C++ but since I write Javascript code since the previous century I just have to slightly modify old Javascript functions to run in the Arduino IDE.

But for sure I'm not ready to write a perfect library for an MCU, so I need to use what I find online.

Apparently there are not many people into websockets. I tested 2-3 Arduino websockets libraries and couldn't get them to work properly.

The last one I tested([Links2004][2]) works but I can't send a 4 decimal string faster than 2 times per second or it crashes.

All I did was to add this code for testing:

    void onWebsocketMessage(uint8_t * payload) {
     analogWrite(13,atoi((const char *)payload));
    }

Where `payload` is the data received.

Problems that could slow down/crash everything:

1. My code. Does `atoi` take too much to execute?
2. My code. Is the `(const char *)` cast filling memory?
3. The lib itself?

I know that the CPU memory or whatever else is not the problem because of this video:

https://www.youtube.com/watch?v=8ISbmQTbjDI

He gets realtime stats from the controller at 200-600 Hz.

While it's supercool and I could just install that "custom firmware" I prefer to stay in the Arduino IDE for now.

How to fix websockets on the ESP8266 device using Arduino IDE?

Or maybe can I extract only the websocket part from that firmware (CNLohr's Video)?

Suggest another lib?

I posted here because I use the Arduino IDE. And the ESP8266 has also been part of the Arduino world for a while. And maybe some not so popular Arduino-based websockets work also on the ESP8266.

Wouldn't it be nice to control your ws2812b strip with a web interface showing the preview like this?

http://jsfiddle.net/dgws3usa/5/

----------

**EDIT**

links2004 @ github

1. The network should be fine. It's a relatively expensive Cisco/Linksys N router at 20cm/8inch away from the ESP8266 module.
2. Luckily the module I'm using is one of the modules listed in the Arduino IDE, the [MOD-WIFI-ESP8266-DEV][3], but I have another one with fewer GPIOs.
3. I just noticed now that I programmed it at 80 Mhz instead of 160 Mhz.
4. The program I uploaded consists only of the basic websockets server example with in addition just the code posted above.
5. If `atoi` is the problem/is slow, what are other ways to convert the received array to a string?
6. I use both the latest versions of the Arduino ESP8266 port and the arduinoWebSockets. At least I guess so. I followed the install instructions one day before I asked this question.
7. By crash I mean, while moving the range slider, if updating in realtime with `addEventListener('input',function,false)` at some point (after 1 sec/ 3-4 messages send/received) it stops sending or receiving data. By the way, the video you posted seems to work properly with a lot more code. Also that guy updates in realtime with `oninput` vs 'onchange', which would only update when the user releases the slider.
8. I think for now I can't use `Serial.setDebugOutput(true);` as I didn't get the serial communication working. I'm using a cheap CH340G to program the chip.

Japanese post.

9. I'm doing exatly the same thing but in a much simpler way. No web server, no ping pongs, no serial stuff, I don't use complex functions to elaborate the web server's data. Altough his example works.

10. He is doing, code-wise, a lot more than I do.

    for(i=0; i<4; i++) {
      mask[i] = client.read();
    }
    byte m_data[data_len];
    char data_c[data_len];
    Serial.print("Receive Data = ");
    for(i = 0; i<data_len; i++) {
      m_data[i] = client.read();
      data_c[i] = mask[i%4]^m_data[i];
      Serial.print(data_c[i]);
    }
    switch (data_len) {
      case 1:
        data_b = data_c[0]-0x30;
        break;
      case 2:
        data_b = ((data_c[0]-0x30)*10) + (data_c[1]-0x30);
        break;
      case 3:
        data_b = ((data_c[0]-0x30)*100) + ((data_c[1]-0x30)*10) + (data_c[2]-0x30);
        break;
      }
      LED_PWM(data_b);

My full "test" code:

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>
    #include <WebSocketsServer.h>
    #include <Hash.h>
    ESP8266WiFiMulti WiFiMulti;
    WebSocketsServer webSocket=WebSocketsServer(81);
    void webSocketEvent(uint8_t num,WStype_t type,uint8_t * payload,size_t lenght) {
      switch(type) {
        case WStype_DISCONNECTED:
          break;
        case WStype_CONNECTED:
          {
          IPAddress ip=webSocket.remoteIP(num);
          }
          break;
        case WStype_TEXT:
          analogWrite(13,atoi((const char *)payload)); // MY CODE
          webSocket.broadcastTXT(payload,lenght);
          break;
        case WStype_BIN:
          hexdump(payload,lenght);
          webSocket.sendBIN(num,payload,lenght);
          break;
      }
    }
    void setup() {
      pinMode(13,OUTPUT); // MY CODE
      for(uint8_t t=4;t>0;t--) {
        delay(1000);
      }
      WiFiMulti.addAP("ssid","pass");
      while(WiFiMulti.run()!=WL_CONNECTED) {
        delay(100);
      }
      webSocket.begin();
      webSocket.onEvent(webSocketEvent);
    }
    void loop() {
      webSocket.loop();
    }

11. I normally write Javascript code. Converting a string to a number or vice-versa is much simpler. `num=1; str=1+''; num=str*1;` So all this binary array is relatively new for me.

12. Note that while I convert the binary array to an int now. In the future I need to convert that to a string which then will be parsed. Something like JSON. And so update more channels per message.

13. On the client side, like I said, I'm sending the data really fast. So if there is no buffer on the server side that could be a problem. Solving that is simple: `requestanimationframe`. Continuously check if the input changed. That allows you to send the data every 16-17ms. So 60 Hz. Not slower, Not faster. But again that should be the maximum pause between messages.

I said that I will reprogram it at 160 Mhz now and hope there are other ways to convert the received data faster and hope for updates relative to my code.

----------

**EDIT2**

Right. The serial works. Reprogrammed the ESP8266 At 160 Mhz.

The error I get when when I set `Serial.setDebugOutput(true);` is:

    LmacRxBlk:1

If you need some other information just ask.

**EDIT3**

Sorry for the late response.

    webSocket.broadcastTXT(payload,lenght);

Broadcasting seems to be the problem. I just have a few minutes so for now I can't do the describe debug stuff... But I will do as soon as I have a little more time.

**EDIT4** for Aditya Tannu

Added

    #include <NeoPixelBus.h>
    #define pixelCount 16
    NeoPixelBus strip = NeoPixelBus(pixelCount,13);

Inside the webSocketEvent function

    case WStype_TEXT:
    for(uint8_t i=0;i<pixelCount;i++){
     strip.SetPixelColor(
      i,
      RgbColor(i==(atoi((const char *)payload)%pixelCount)?255:0,0,0)
      // i need to put the above outside of the loop.
      // it does not work if i do so
     );
    }
    strip.Show();
    break;

HTML JS

    var ws,form;
    function msg(a){
      console.log(a);
    }
    window.onload=function() {
      form=document.getElementById('form');// change
      ws=new WebSocket('ws://IPNUMBER:PORT');// change
      ws.onopen=function() {
        ws.send('0');
      };
      ws.onmessage=msg;
      form.addEventListener('input',function() {
        ws.send(this.firstChild.value) // firstchild is the range
      }, false);
    }

[vid][4], I use a logic level converter from 3.3v to 5v: pca9306.

**EDIT 5** for Links2004

> I think I should rework the examples. It looks like most users don't
> understand it well.

Nono. At some point you need to broadcast back the actual position anyway.

Sorry. I forgot to test the debug stuff again. But we know it's the broadcast. We just need to send back data only when there is not too much traffic.

  [1]: https://www.youtube.com/watch?v=ThLoN494XBc
  [2]: https://github.com/Links2004/arduinoWebSockets
  [3]: https://www.olimex.com/Products/IoT/MOD-WIFI-ESP8266-DEV/#
  [4]: https://youtu.be/IbKtPX20kbY

body:
I tried to port Charles Lohr's implementation to esp8266/Arduino. An initial working version is up here: https://github.com/AdySan/ESPSocket

I'm able to get ~150Hz without any disconnections or crashes. I'll keep working on it to add more functionality and hopefully improve speed.


message:
Power maximum output power for each pin

A have Arduino Mega 2560. I found in the spec that the maximum output current for each I/O pin is 40 mA.

Can i use 40 IO in parallel? That's mean 40*40ma*5 volt = 8000 mw = 8 watt.

What about the heat?!

body: No, you can't.  Read the rest of the specifications and you'll see why.  Also the 40mA is wrong. That is the *absolute* maximum. 20mA is the guaranteed limit for steady-state IO.


body:
There are also limits on the total power of groups of pins,

>  1. The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed
>     200mA.
>  2. The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
>  3. The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
>  4. The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
>  5. The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.

So you are already limited to 800mA.

Secondly, you have to be careful to change all the pins at exactly the same time. Otherwise some pins will be low, and others high creating effectively a dead short. Or if you make sure the pins are inputs before changing, some pins will be on sooner, and those pins will then for a short period, handle all the current, and thus exceeding their limit for a brief moment. Which isn't that bad, but still not ideal.

So definitely don't use `digitalWrite` to change all the pins, one after the other.


message:
I2C between Arduinos without Master

I am working on a library for some Arduinos that should talk between each other.
The aim is that I can load the same binaries onto each Arduino. The I2C ID will be set by DipSwitches.
So far everything works pretty nice but once a while everything gets stuck.

I am not asking you to resolve and debug my code, but I am not sure if i have done something completely wrong:

To make all Arduinos interchangeable I have no Master (`Wire.begin()`) in my I2C Bus.

I read, that the Master would be responsible for the pulse on the Clock line. As I have no Master in my setup maybe that is the reason for the instability.

Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

body:
You have to have a master for an I2C bus to work.  Can't you allocate one of the dip switches to define the master?

Edit to be able to remove the downvote
Nick his answer seems to imply that you do not need masters but that is wrong.
What Nick is saying is that you can swap masters over time.
But each time there is communication there is a master.
So the statement "You have to have a master for an I2C bus to work" is 100% right.
As I misunderstood this myself I downvoted this answer. I hope this edit will enable me to remove my downvote and add a upvote.


body:
> Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

There is no master except during transmissions. Thus it is possible to rotate the job of master if you want. You would need some way of deciding when it was a particular board's turn to be master.

I have code [here on my RS485 page](http://www.gammon.com.au/forum/?id=11428&reply=2#reply2) about how you can set up a rolling master using Serial communications. The same basic idea could be used to make a rolling I2C master.


message:
How does the speed work in VirtualWire Library

I'm analyzing the VirtualWire library and in it, the send messages are being sent with digitalWrite in the "send" method. However, there is a setup speed function. I'm reading that function and I see a lot of prescalers and TCCR variables. However, I'm not quite sure what these things do. Because, if it uses digitalWrite anyway to send the bits, then really is no intrabit delay, etc. Can someone please clarify this?

Sorry if question is convoluted. Happy to do any clarification. Thank you for all guidance!

EDIT: Also, how do I transmit a block of message. Something greater than a byte? I'm trying to calculate BLER of messages and software serial only transmits 1 byte at a time. While virtualWire uses low-level error detection (and i want to avoid the use of any error detection/correction).

body:
I think that is used for receiving. By setting the speed, it knows how often it needs to read the input pin. It does this using timer interrupts, so it will run "in the background" without interfering with the main (loop) code.

The TCCR stuff is the set the interval for the timer interrupt.


message:
How to choose SPI type used by RF24 library from application?

I am developing a device with Ethernet shield (with Wiznet W5100) and NRF24L01+. I need to use Soft SPI due to a bug in the Wiznet chip. Next I am developing a different device with NRF24L01+ only. I want to use hardware SPI (besides other things it already contains a socket for NRF24L01+ connected to the default Arduino SPI pins).

It is very inconvenient to enable/disable `#define SOFTSPI` in `RF24_config.h` every time I want to work on the other device.

Is there a way how to choose the SPI type used by RF24 library in the application?

My current solution is to make a copy of RF24 to RF24_SoftSpi and RF24Network to RF24Network_SoftSpi. I enabled SOFTSPI in “_SoftSpi” versions (+ renamed all files, fixed includes and #ifndef statements in headers to avoid ambiguous errors).

Then in an application I just include RF24_SoftSpi instead of RF24 and RF24Network_SoftSpi instead of RF24Network to use software SPI.

With this workaround it is difficult to make updates to “_SoftSpi” libraries when a new feature is released.

Do you know of any better solution?

body:
Using this [RF24 library][1] set, I am able to use or not softspi by doing #define SOFTSPI on my sketch, there's no need to define it on the RF24_config.h, you should be able to define it on your own sketch.

  [1]: https://github.com/TMRh20/

***EDIT:***

Arduino 1.6.5

    #include <SPI.h>
    #include "RF24.h"
    #include "printf.h"
    #define SOFTSPI //Define pins RF24_config.h

    /****************** User Config ***************************/
    /***      Set this radio as radio number 0 or 1         ***/
    bool radioNumber = 0;

    /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8     */
    RF24 radio(8,9);

    ....
    ....
    void setup() { ... }
    void loop() { ... }


message:
How do I resolve "avrdude: stk500_recv(): programmer is not responding"?

Whenever I try to program my Arduino UNO Rev.3, I'm seeing the following error

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00

When I plug this in, I do see a power light. There are no cables whatsoever connected other than the USB. I have another Arduino UNO which works fine when I upload the sketch (I'm using the basic blink sketch). How do I resolve this? What kind of problem can it be?

body:
Have you already tried this?
https://stackoverflow.com/a/20735393/5507619

> I had this problem with a Crowduino, running the Arduino IDE on OSX.
> The solution for me was to switch on verbose output during upload (in
> the arduino IDE preferences pane).
>
> Then, when uploading, you can see avrdude sending three packets
> avrdude: Send: 0 [30]   [20] (with corresponding RX flashes on the
> board) right before the avrdude: ser_recv(): programmer is not
> responding error.
>
> The trick is to hit the reset button on the board immediately before
> these three packets are sent. Then the program will be uploaded
> successfully.


body: I had periodically encountered this as well and was stumped after I had tried all the recommended solutions I could find. In my particular case it turned out to be the cable I was using.


body:
I was having the same problem, however I was able to solve as follows,

* rebooting my computer
* or, changing the cable, basically switching between 2 USB cables (may be it just needed to unplug the USB and plug it in again).

* or, resetting the COM port
  1. closing the Arduino IDE
  2. disabling the COM port
  3. enabling the COM port
  4. opening the Arduino IDE


body: After trying numerous suggestions, 2 different boards, 3 different cables on a WinXP and a Win7 machine, I finally got things working by going to "Tools -> Processors -> ATmega 328P Old Bootloader"


body:
I had this problem when working with Arduino IDE and XOD running on top of it.
What I found; looked like **baud rates were being set differently at different stages in the setup**. I compared Windows 'device settings', arduino IDE settings and XOD settings...and they are not the same and seem to change ? ...hence the 'avrdude:stk500_**** errors!

**To demonstrate**

 Connect an Arduino board to a PC USB socket.

1. On Windows 7; Control Panel\ System and Security\System\ Device Manager... then double-click on 'Ports (COM & LPT)

 You should see FTDI

 or

 USB-SERIAL CH340(COM7) ... for a chinese serial com chip on the arduino board.
Right-click on this and check 'Properties\ Port Settings' and note  the 'Bits per second' value : e.g. 57600 ... (write it down !)

2. Open the arduino IDE and click on File\Preferences and tick the option ;'**Show verbose output during: 'upload**'.Then close the 'Preferences' screen.

3. Load a small program that works. e.g. File\Examples\01.Blink

4. In the for your arduino board setup in the Arduino IDE;

 Tools\Board ... such as *Arduino Nano*

 Tools\Processor ... such as *ATmega328P*

 Tools\Port:COM7 for example ... make sure a tick is selected.

 Tools\Get Board Info ... will show info from the arduino serial chip (**a good sign your usb cable works!**)

5. On the IDE toolbar select;

 - 'Verify' and shortly it should show 'Done Compiling'

 - Click 'Upload' and the *Blink* program should load into the arduino chip.

6. Now here is the interesting observation; The 'verbose message at the bottom of the IDE screen will indicate what '**Overriding Baud Rate : XXXXX'** is being used! Write this number down next to the value you found on the Windows devices setting.

7. Now, if you are a XOD man, leave the arduino IDE running and run XOD.

8. Open the XOD IDE and open (Deploy) say the *01-hello* program and load it into your arduino board.

9. Select'welcome-xod' and select 01-hello program on left-side menu.

10. Select 'Deploy\Upload to Arduino ...'

11. select 'Board model:'  and 'Serial port:' ... eg COM7

12. Scroll up in the 'Deployment ' window and there will be another value labeled **'Overriding Baud Rate : e.g.115200'**

I HAVE FOUND THESE BAUD RATE SETTINGS CHANGE INEXPLICABLY !

I hope my observations will throw some light on your problem of erratic uploads.


body:
For me it was a matter of `-B 10` instead of `-b xxxx`. So:

    sudo ~/arduino-1.8.12/hardware/tools/avr/bin/avrdude -P /dev/ttyACM0 -B 10 -c arduino -p m328p -C ~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -U eeprom:r:eeprom.hex:r


message:
How to use a microSD card reader with SCK instead of CLK?

I've bought this microSD reader/writer: http://www.ebay.com/itm/131132034753

I've found only one tutorial, where the pins are similar to my pins, but in the example there is a CLK instead of SCK: https://learn.sparkfun.com/tutorials/microsd-shield-and-sd-breakout-hookup-guide

The pins on my MicroSD reader are:

 - CS
 - SCK
 - MOSI
 - MISO
 - VCC
 - GND

body:
SCK stands for **S**PI **C**loc**K**

CLK stands for SPI **CL**oc**K**

Two different acronyms for the same thing.


body:
It's common practice for speakers/writers to use the generic term: "clock" (CLK) for various different situations. This clearly being a *serial* interface we don't need to specifically say **S**erial clo**CK** each time the signal mentioned, as it's more of a mouthful than saying "clock".

In this case consider "CLK" and "SCK" as fully interchangeable.


message:
Popen command restarts arduino

So I am trying to make a Mac OSX program with Cocoa that will be able to control my Arduino via serial. I currently have the C command

    popen("echo 7 > /dev/cu.usbmodem1411", "r");

to try to send the number 7 over serial to the Arduino. I know that the path     /dev/cu.usbmodem1411 is correct because the Arduino is responding, however it seems to "crash" or simply restart whenever this command is received from the Mac. Sorry this may be a question for StackOverflow, but I thought I would start here.

body:
I think the problem is more going to be that you don't have a serial connection to the arduino. ie, if you look in the Arduino IDE, you assign a serial port to the application. When you upload your sketch, a connection is made, the arduino resets (by design) and your sketch is uploaded.

What it appears you are doing here is opening a new connection and sending the character (which is `ASCII`) which in turn sends the arduino into reboot to look out for a sketch being uploaded.

I'm not familiar with `popen` and maybe you can use it and keep the connection open and even monitor the data stream, but I would say instead of writing directly to the device as you've done, use an application that will initialise the port properly (ie open it and leave it open) so that you can continue to use/monitor it.

A quick google search has brought up [Mike's PBX Cookbook][1] which has some good info about it. I've personally used `minicom` ([a guide for installing minicom][2]) and [`CoolTerm`][3], I have used `Screen` but it was so long ago I don't remember why I moved on.

*edit: I just followed the link submitted by the first commenter (sorry name not available in the edit screen), and although you've responded with "that's not it", it actually is, you just haven't realised it since your `popen` command is actually opening the port and triggering the RTS mentioned in that post*

  [1]: http://pbxbook.com/other/mac-tty.html
  [2]: http://hints.macworld.com/article.php?story=20041026113304907
  [3]: http://freeware.the-meiers.org/


message:
How can i connect the Mics-5132 to Arduino Uno (Carbon Monoxide Sensor)

[![datasheet][1]][1]

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

hi. i don't know how can i connect Mics-5132 CO Sensor to my arduino.

plz help

body:
That is a very skimpy data sheet for the MiCS-5132 .  (Shame on manufacturer for not including isolation information between heater and resistor output).

Connect 3.2 volts (3.3 volts is ok) to pins 1 and 3 (heater). Keep in mind the heater will draw about 32 mA.

Pins 2 and 4 are the output.  The output is a resistor, whose value changes with the degree of detected gases. And the resistance is about 160 k ohms.

Wire a resistor (call it R1) from VCC (positive power) to your input. Start out with R1 = 150k  (anything from 120K to 180K). .

Wire the sensor (pin2) to your input (use an input that can do A/D conversion).  Wire the other side of the sensor (pin 4) to your board ground.

This makes a resistor voltage divider to your input pin. Your input pin should be an A/D converter.  The A/D converter input should return a value dependent upon the sensor resistance.

Experiment with different values for R1, to get the input range that you desire.


message:
Drawing amperage with Arduino code

I'd like to preface this by saying I'm a complete beginner, but I have learned a ton already on this project, and I feel like I'm almost there.

I'm using an Arduino Uno and an Adafruit motor shield. I am working on a project for mechanical engineering and I need lots of amps for lots of torque for my mechanism. I'm including my code although I know it doesn't work, I haven't had the chance to debug it yet, and I'm really not sure if I'm on the right track.

So I know that it's possible to draw more amperage than is strictly allowed from the Arduino. What I don't know for sure is how to code it. Attached is my preliminary attempt.. I kind of assumed that the maximum speed would be the maximum allowable speed of the motor, regardless of the Arduino's capabilities, and scaled the output `MAXampDrawSpeed` as a function of that. To be specific, my motor can draw up to 20 amps, which would be too much for the Arduino to handle, so I scaled it down accordingly, with 255 being that maximum 20 amp output. I'm not sure if I'm on the right track there.

So the other problem is - the TA for my class made a simplified code reference file, sort of predefining a lot of the things that I manually defined in my code (or tried to at least). I didn't realize this, and when I asked him a question, he sort of shot me down and said "you should use my reference code" -- but his code doesn't compile for me. I had some problems with libraries (I fixed them!), but this isn't a library. It's a reference file, like the tabs up at the top. But it won't even compile for me. My feeling is that I may have annoyed him with my many many stupid questions up until this point and he's just kind of like "girl, get it together"... So the question there is -- am I almost there with my track or should I figure out what's wrong with his code and try to fix it his way so that I can ask him questions without being such a bother to him? And also is that likely to be a hindrance on drawing the extra amperage that I really really want? I am prepared to use heat dissipation methods as are necessary, and any advice you could give me there would also be appreciated.

If you need any more information, about my mechanism or anything I'd be glad to share that as well. I'm parallel mounting one motor to the four dc motor mounts on my Arduino in order to draw maximum current in that way as well. I have two switches controlling the output, one of the switches will engage the program for the maximum distance competition and the other for the accuracy competition.

So again, this code isn't right. I haven't even started on debugging it, because I didn't want to waste my time. Maybe you'll be able to follow my logic. I know there aren't many notes. If you need me to add notes for clarity I would also be glad to take the time to do that.

Thanks!

    #include <Stepper.h>
    #include <AccelStepper.h>
    #include <Servo.h>
    #include <Adafruit_MotorShield.h>
    #include <Wire.h>
    #include "Arduino.h"

    #define STEP_TYPE_1   SINGLE
    #define STEP_TYPE_2    SINGLE
    #define STEPS_1    200
    #define STEPS_2    200

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
    Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
    Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
    Adafruit_DCMotor *DC4 = AFMS.getMotor(4);
    Servo Servo1;

    void setup() {
      digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
      int i = analogRead(A0); //Reads the value on the analog pin and saves     this as variable "i"
      AFMS.begin(); //Initializes the motorshield board
      int motorPin1 = 1;
      int motorPin2 = 2;
      int motorPin3 = 3;

      pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
      digitalWrite(A0,HIGH);
      pinMode(A1, INPUT);
      digitalWrite(A1,HIGH);
      pinMode(A1, INPUT);
      pinMode(1, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      Servo1.attach(9);
    }

    void loop()  {
      int distancepin = 0; //Just integer quantities, i like to have too     many of them
      int accuracypin = 0;
      int inPin1 = 0; //switch pin values
      int inPin2 = 0;
      int MAXampDrawTime = 75;
      int MAXampDrawSpeed = 178;
      int NORMampDrawTime = 225;
      int NORMampDrawSpeed = 61.2;
      int DrawTime = MAXampDrawTime+NORMampDrawTime;
      int ServoTime = 450;
      long previousMillis =0;
      long intervalMAXamps = 100;
      long intervalNORMamps = 400;
      DC1->setSpeed(MAXampDrawSpeed);
      DC2->setSpeed(MAXampDrawSpeed);
      DC3->setSpeed(MAXampDrawSpeed);
      DC4->setSpeed(MAXampDrawSpeed);
      inPin1 = digitalRead(A0);
      inPin2 = digitalRead(A1);
      if (inPin1 == HIGH){
        unsigned long time_zero = millis();
        unsigned long current_time = millis();
        digitalWrite(1,HIGH); //turn motor on to maximum draw amperage
        digitalWrite(2,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(4,HIGH);
        while((millis()-time_zero)<(400000)){
          if( millis() >= (time_zero+NORMampDrawTime)){
          DC1->setSpeed(NORMampDrawSpeed); //set motor on to normal draw     amperage
          DC2->setSpeed(NORMampDrawSpeed);
          DC3->setSpeed(NORMampDrawSpeed);
          DC4->setSpeed(NORMampDrawSpeed);
          digitalWrite(1,HIGH); //turn motor on to normal draw amperage
          digitalWrite(2,HIGH);
          digitalWrite(3,HIGH);
          digitalWrite(4,HIGH);
        }
        if ( millis() >= (time_zero+DrawTime)); {
          digitalWrite(1,0); //turn off motors
          digitalWrite(2,0);
          digitalWrite(3,0);
          digitalWrite(4,0);
        }
        if (millis() >= (time_zero+ServoTime));{
          Servo1.write(0);
          delay(400);
          Servo1.write(90);
        }
      }
    }
    if (inPin2 = HIGH);{
      int MAXampDrawTime = 75;
      int MAXampDrawSpeed = 59;
      int NORMampDrawTime = 225;
      int NORMampDrawSpeed = 20;
      int DrawTime = MAXampDrawTime+NORMampDrawTime;
      int ServoTime = 250;
      unsigned long previousMillis =0;
      unsigned long intervalHIamps = 100;
      unsigned long intervalNORMALamps = 400;
      DC1->setSpeed(MAXampDrawSpeed);
      DC2->setSpeed(MAXampDrawSpeed);
      DC3->setSpeed(MAXampDrawSpeed);
      DC4->setSpeed(MAXampDrawSpeed);

      unsigned long time_zero = millis();
      unsigned long current_time = millis();
      digitalWrite(1,HIGH);
      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
      digitalWrite(4,HIGH);
      while((millis()-time_zero)<(500)){
      if( millis() >= (time_zero+MAXampDrawTime)){
        DC1->setSpeed(NORMampDrawSpeed);
        DC2->setSpeed(NORMampDrawSpeed);
        DC3->setSpeed(NORMampDrawSpeed);
        DC4->setSpeed(NORMampDrawSpeed);
        digitalWrite(1,HIGH);
        digitalWrite(2,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(4,HIGH);
      } else( millis() >= (time_zero+DrawTime)); {
        digitalWrite(1,0);
        digitalWrite(2,0);
        digitalWrite(3,0);
        digitalWrite(4,0);
      }
      if (millis() >= (time_zero+ServoTime));{
        int  time_check = millis();
        while (millis() - time_check < 400000) {
          inPin1 = digitalRead(A0);
          if (inPin1 == HIGH ) {
            Servo1.write(0);
            delay(400);
            Servo1.write(90);
          }
        }
      }
    }
    }}

body:
Firstly your formatting is horrible, but that's probably just the this editor, if it isn't please fix it.

In loop() you are wasting time if you are re declaring constants, move them outside the loop.

Why have you got 4 on switches?  Could you not gang them altogether? Join the wires and use just one pin?

you are repeating blocks of code, break these out into functions, this means less code to debug. I.e. SetMotorSpeed.

    If (inPin2 = HIGH)

This will always be true, because an assignment is C\C++ always returns true, you meant ==

You TA is being paid to help you, don't be afraid to p##s them off, it's there job to get p'd off at students, and their choice.  At least you are doing it by asking questions not d##king around.  That said the most likely cause of you problems with his example is missing libraries or IDE version differences.  Or even library versions, if you add the first 5 errors as a comment I might be able to point you in the right direction.


body:
I'm going to echo what Matt said but you have way too many constants declared like variables.

A constant in C should be done like this

    #define MYCONSTANT 666

right at the top of your code and outside of any setup loop or main function

Also think about the integer types you are using remember that Arduinos are 8 bit processors only use longs (32bit) where you really really have too and especially do not declare a constant as a long or int the way you have inside your loop.

This

    int NORMampDrawSpeed = 61.2;

is just wrong you are saying that an int is a float, which it cannot be.

I personally avoid using floats altogether in Arduinos but if you must then declare it as a float or a constant (if it is a constant)

    float NORMampDrawSpeed = 61.2;
or

    #define NORMampDrawSpeed 61.2

be very careful when doing arithmetic with floats and ints because it will always return a float unless specifically typecast

better still since your new to programming just don't use them

And yes as Matt said write your own functions for stuff you need to do a lot such as

    void setMotors( byte on_off ){
        for( uint8_t i=1; i <= 4; i++){
            digitalWrite(i,on_off);
        }
    }

declare this function above the setup function an use it to turn all your motors on or off (1 or 0) like

    setMotors(1);


body: You reeeally don't want to draw current through your controller board.  It's best to use a transistor power circuit, or 741 op-amp, or relay.  Keep your power delivery separate from your control system.


message:
is it possible to convert a 328 design to use a 32U4?

I have several projects that use simple 328 based arduinos that I built myself, similar to the familiar "arduino on a breadboard" projects that I'm sure everybody has seen. They have just the bare minimum, no ftdi, etc.

Is it possible to drop in the 32U4 without modifying the circuits, or would I have to do a bunch of work to the circuits to get them to work with the 32U4 chips, and if so what are the general steps?

body:
Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin.
Also the 32U4 seems to have a lot more peripherals.

So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though.

eg SPI on portB, uart on portD

But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly.

Datasheets are easy to find. Good Luck!


message:
Why are Arduino clones cheap?

You can buy Arduino Nano v3 clones from Alibaba at the cost of roughly $2-$3.

I have calculated the cost for fabricating and all the parts in the BOM for Arduino Nano V3, and it ended up costing around $10 to $12 (depending on where you fabricate the board, buy the components and purchasing volume - assuming less than 100 units).

However, how are Chinese clone manufacturers able to slash the price so much it's only ~1/10 of the BOM cost.

Could it purely be due to economy of scale, lower fixed costs (cheap labor), low quality parts *(How do you define **low quality parts**)*? Or are there other factors at play as well?

body:
All the factors mentioned in the question apply to make the cost so low.  However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that.

Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch.  The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made.  Those badly made will function but may have shorter lives and higher failure rates.  For example, the USB cable fit may be loose, or the switch may fall apart.  Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.

However, [SMT (surface mount technology)](https://en.wikipedia.org/wiki/Surface-mount_technology) or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts.  SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention.  See, eg, [ceramic capacitor manufacturing](https://en.wikipedia.org/wiki/Ceramic_capacitor#Multi-layer_ceramic_capacitors_.28MLCC.29) at wikipedia.  Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs.  In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts.  The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.

Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines.  As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used.  In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. ([For example,](https://www.sparkfun.com/news/395) NCP5318 buck regulators relabeled as ATmega328s.)  In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail.

The CH340g USB-to-serial chip  vs. ATmega32U4 USB issue is more complicated.  Ie, some may think of the CH340 as a lower quality part than a 32U4.  The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. [1](http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html), [2](http://www.arduinodroid.info/2015/07/ch340g-support.html).  The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities.  I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.

The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor.  Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.

Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality.  Corners may get cut on assembly quality and on quality assurance inspections.


message:
Is it possible to make a mathematical function generator using Arduino?

I want to build a function generator but not the ones which outputs square wave or sawtooth ect. I will input a discrete function lets say f(n) = e^n for n=0 to n=100 and the output array will be outputs as voltage samples creating a e^x like signal on a scope?

Is this possible?

body:
You can generate arbitrary waveforms using either the built-in PWM and a low-pass filter or an external DAC.

You won't get more than 16-bits in PWM ( or AFAIK non-audio DAC with arduino libraries ), so your e^N function will be below your resolution for most of the cycle.

Alternatively, generate a saw-tooth and use an [op-amp exponential function][1]

  [1]: https://en.wikipedia.org/wiki/Operational_amplifier_applications#Exponential_output


body:
Arduino DUE has a built-in DAC (has two in fact) and so you can do arbitrary function generation fairly easily by just going over some arbitrary table (that sampled the function) and output that with [`analogWrite`](https://www.arduino.cc/en/Reference/AnalogWrite) to the DAC channel[s]; details in [this arduino.cc tutorial](https://www.arduino.cc/en/Tutorial/DueSimpleWaveformGenerator). They only show sine/triangle/square waves there, but if you look at Waveforms.h at the end of that tutorial you can put arbitrary shapes in there.

By the way this technique of waveform generation of using a lookup table and a DAC is abbreviated DDS for [Direct Digital Synthesizer](https://en.wikipedia.org/wiki/Direct_digital_synthesizer).
Here's a more conceptual tutorial on DDS (not involving arduino):
http://www.ni.com/white-paper/5516/en/

The DACs built-in Arduino DUE have 12-bit resolution by the way, i.e. 4096 discrete output levels. IF you need better than that, an external DAC is required, which you could connect by TWI/SPI etc.

You can get a poor man's DAC on the Arduino UNO or Leonardo by PWMing with `analogWrite` on the GPIO pins (as suggested in the other answer), but you need [understand low pass filter fundamentals](http://provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/) to get that done.


message:
Unstable reading from Raspberry Pi

I'm trying to send a signal from Raspberry Pi GPIO to Arduino. I made a sketch that basically reads the state of the digital read, but the reading are very unstable. I understand that there is a floated voltage and the obvious solution is to configure the pullup resistor and connect the input to ground, but my goal is to read the incoming signal.
I'm using Arduino Mega 2560 and Raspberry Pi 2B.

I hope this info is enough!

body:
As Majenko commented, you need to not only connect the data wires together but also the ground wire (from the Arduino to the Pi).

> ... the reading are very unstable ...

Without a consistent "ground reference" the readings would indeed be unstable.


message:
Serial Communication Problem Using Eclipse

**Please help**

I have created an Arduino program that will switch the pins when I send a char. It works fine with serial monitor, but the problems come when I send chars with Eclipse using RXTX serial communication. When I click the button to send the char, at first click it does not switch the Arduino pins; it just senses the Rx and Tx LED but the second time it switches on. But when I tried to switch the second LED it first turns off the first LED although that was not my aim, and then it switches the intended LED. Here is my Arduino code.

    const int lamp=2;
    const int fan=3;
    const int pump=4;
    const int fridge=5;
    char val;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(lamp,OUTPUT);
      pinMode(fan,OUTPUT);
      pinMode(pump,OUTPUT);
      pinMode(fridge,OUTPUT);
    }
    void loop() {
      // put your main code here, to run repeatedly:
      if(Serial.available()) {
        val=Serial.read();
        if(val=='a') {
          digitalWrite(lamp,HIGH);
          Serial.print(val);
          delay(100);
        } else if(val=='b') {
          digitalWrite(lamp,LOW);
          Serial.print(val);
          delay(100);
        } else if(val=='c') {
          digitalWrite(fan,HIGH);
          Serial.print(val);
          delay(100);
        } else if(val=='d') {
          digitalWrite(fan,LOW);
          Serial.print(val);
          delay(100);
        } else if(val=='e') {
          digitalWrite(pump,HIGH);
          Serial.print(val);
          delay(100);
        } else if(val=='f') {
          digitalWrite(pump,LOW);
          Serial.print(val);
          delay(100);
        } else if(val=='g') {
          digitalWrite(fridge,HIGH);
          Serial.print(val);
          delay(100);
        } else if(val=='h') {
          digitalWrite(fridge,LOW);
          Serial.print(val);
          delay(100);
        }
      } else {
        int sensorValue = analogRead(A0);
        Serial.println(sensorValue/10);
        delay(100);
      }
    }

*Here is a part of my Java code*

    public boolean identifyport() throws PortInUseException, IOException, TooManyListenersException {
      this.setVisible(true);
      try {
        Enum=CommPortIdentifier.getPortIdentifiers();
        while(Enum.hasMoreElements())
          portname=(CommPortIdentifier)Enum.nextElement();
          if(portname.getPortType()==CommPortIdentifier.PORT_SERIAL)
            port=portname.open(this.getClass().getName(), 2000);
          serialport=(SerialPort)port;
          serialport.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);
          input=((CommPort) serialport).getInputStream();
          output=((CommPort)serialport).getOutputStream();
          serialreader=new BufferedReader(new InputStreamReader(input));
          serialport.addEventListener(this);
          serialport.notifyOnDataAvailable(true);
          progressBar.setBackground(Color.GREEN);
          portlist.addItem(portname.getName());
          progressBar.setValue(i);
          slider_3.setValue(value);
          Thread.sleep(1000);
          prg();
        } catch (UnsupportedCommOperationException e1) {
          // TODO Auto-generated catch block
          JOptionPane.showMessageDialog(contentPane, "Check USB cable connection", "No port available ", 0);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          JOptionPane.showMessageDialog(null, "Port status", "Please connect the device....!!!!", day, null);
        }
        return rootPaneCheckingEnabled;
      }
      @Override public void serialEvent(SerialPortEvent e) {
        // TODO Auto-generated method stub
        if(e.getEventType()==SerialPortEvent.DATA_AVAILABLE){
          try {
            serial=  serialreader.read();
          } catch(Exception e1) {
            e1.printStackTrace();
          }
        }
      }
      public void writedata(int v1) {
        try {
          output.write(v1);
          output.hashCode();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

    *And this is part of the switch button;*
    Button button_1 = new Button("switch");
    button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
    button_1.setBounds(10, 10, 117, 42);
    panel_3.add(button_1);
    button_1.addActionListener(new ActionListener() {
      int count=0;
      public void actionPerformed(ActionEvent e) {
        writedata(v1);
        if(count==0) {
          canvas.setBackground(Color.RED);
          canvas.setForeground(Color.GREEN);
          v1='b';
          count++;
        } else {
          canvas.setBackground(Color.YELLOW);
          canvas.setForeground(Color.GREEN);
          v1='a';
          count--;
        }
      }
    });

Sorry I can not write everything because there is so much code.

body:
The java code you wrote should send just 'a' and 'b' so you should see just lamp turning on and off.

Move writedata invocation just before count++ and count-- statements to solve your "first time". The problem could be the initialization of v1.

Into writedata method why do you call hashcode on the output stream? Maybe flush?


body:
Thanks my friends, I had already solved the problem, the problem was this....
I made the method that ran after pressing each button, which sent the data at particular button, it seems the data interfered each other but I do not know why, but I had deleted that method and I used to send data using the object I created at each button.

 Button button_1 = new Button("switch");
  button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
  button_1.setBounds(10, 10, 117, 42);
  panel_3.add(button_1);
  button_1.addActionListener(new ActionListener() {
    int count=0;
   public void actionPerformed(ActionEvent e) {
    if(count==0){
     canvas.setBackground(Color.RED);
     canvas.setForeground(Color.GREEN);

     char v2 = 'a';
     try {
      output.write(v2);
     } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
     }
    count++;
    }
    else{
     canvas.setBackground(Color.YELLOW);
     canvas.setForeground(Color.GREEN);
     char v1 = 'b';
     try {
      output.write(v1);
     } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
     }
     count--;
   }

   }

Now it worked fine....!!!!.


message:
Ideal settings for regulated power using Arduino Uno VIN?

Is there a downside to providing a lot of amps to Arduino UNO's VIN? Is there any advantage to only supplying a limited amount of amps? I have a regulated power supply and I'm curious what I should set it to when going through the 5v port?

Also, should I stick with 5 volts? I've seen some tutorials say if powering the board through VIN it should ideally be much more than that?

Is there a spec sheet of sort that tells you this?

body:
Honestly, it doesn't matter how much power (amps) you make available, it will only draw what it needs.

However, there is definitely something to be said for limiting how much power you provide.  If something in your circuit is miswired or otherwise shorts out, limiting the circuit to something reasonable (wisely including a fuse in your design as well) means that you won't have some enormous current suddenly passing through burning stuff out and possibly injuring someone. :)

As far as what to provide in terms of volts and amps, the data sheet for your particular arduino is the place to go.  As long as you are providing *that* you are in good shape.


body:
From https://www.arduino.cc/en/Reference/Board :
> The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin. Note that different boards accept different input voltages ranges, please see the documentation for your board.

For specific values, visit https://www.arduino.cc/en/Main/Products?from=Main.Hardware and select your board, and look down to where it says "Input voltage" - there's a "recommended" and "limit", each being a range. Note that some power sources will fluctuate (e.g. 4 AA batteries are 6 volts, possible slightly higher when brand new, but will drop down if there is a high drain, or as they get used up. 4 AA batteries will not provide 6v for long).

As for current (measured in amps or milliamps), if the power supply cannot supply what is used by the board, it will overheat; if it provides more than is required, then it will work 100% perfectly well (so long as you don't have a short circuit). The current an Arduino on it's own will draw will vary depending on the board, Nick Gammon measured an Arduino Uno Rev 3 board at 50 milliamps, but LEDs will typically draw around 20mA each; motors will draw a lot more. 1000mA = 1 amp, so Nick's Uno would draw 0.050 amps. Power supplies typically say on them how many amps (or in some cases, milliamps) they can (safely) provide.


message:
LED Control through bluetooth

I have an Android app that sends data to the arduino HC-06. It is however giving me colors i did not send to it. Eg. Red in place of green, white in place of red etc.
Here is a snippet of my android code that sends the data via bluetooth

     public void onColorChanged(int color) {
        BluetoothV2 bluetooth = new BluetoothV2();
        int r,g,b;
        r = Color.red(color);
        g = Color.green(color);
        b = Color.blue(color);
        bluetooth.Message(r+","+g+","+b);
     }
 Here is a snippet of my arduino code

    void loop() {

    if(Serial.available()>0){

    while(Serial.available()>0){
       char inChar = (char)Serial.read();
       inputString += inChar;
    }
       int red = Serial.parseInt();
       int green = Serial.parseInt();
       int blue = Serial.parseInt();
       color(red,green,blue);
       inputString = "";
       Serial.println("R:"&& red &&"G:"&& green &&"B:"&& blue);
      }
    }

    void color (unsigned char red, unsigned char green, unsigned char blue){
       analogWrite(redPin, 255-red);
       analogWrite(greenPin, 255-green);
       analogWrite(bluePin, 255-blue);
    }

Terminal data

                   2,,,,,,,,,,,,,2,,5,,,,,,,,,,,,,,,,,,,,,,,,,02725,1,502725,,,,,,,,,02514,5,602515     ,5,3,,,,,025

Is the problem how i get the data though Serial.read()? Or what am i missing

body:
Maybe you can try again with something like this to check if the android part is not correct. From your terminal output it seems that you receive values higher than 255.

    void onColorChanged(int red, int green, int blue) //values from 0 - 255
    int r,g,b;
    r= red;
    g= green;
    b= blue;
    bluetooth.Message(r+","+g+","+b);

The receive part in your arduino code is like my code for a similar project.
Try setting your color in the arduino code like this to check if the example code from above works:

    void color (int red, int green, int blue)
    {
    analogWrite(redPin, red);  //the higher your send value the brighter the color
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
    }


body:
    int firstcomma = inputString.indexOf(',');
    int secondcomma = inputString.indexOf(',',firstcomma+1);
    String r = inputString.substring(0,firstcomma);
    String g = inputString.substring(firstcomma+1,secondcomma);
    String b =  inputString.substring(secondcomma+1);
    red = r.toInt();
    green = g.toInt();
    blue = b.toInt();
    Serial.print("R");
    Serial.print(red);
    Serial.print("G");
    Serial.print(green);
    Serial.print("B");
    Serial.println(blue);

This solved my problems.


message:
How to transmit more than 1 byte continually?

In software serial, the write function only sends 1 byte at a time. Is there someway, some library, that i can send multiple bits/bytes, without stopping (and not using digitalWrite)? i want to be able to transmit at least 16 bits as opposed to just 8.

I know i can send 2 bytes, or even 100 bytes. But the thing i'm trying to do is, implement my own LDPC(error correction) codes on the Arduino. Therefore, i'm taking a lot of channel measurements. One of them is figuring out how the error happens during the delay between the stop bit and the next startbit. Often times, this is were synchronization problems occur. So I'm trying to track this down. Hence why, I need to send more than 8 continuous bits. In software serial, it transmits 8 bits, then transmits the stop bit. then write() restarts on the next call. Instead of this, i just want to send more bits, like 64 bits for instance, and look at the BLER on the received data. (the reason why I'm staying away from hardware serial is because i'm doing this with wireless RF modules) Do you guys have any further info regarding this? I'm very grateful! Thank you so much!

Also, it was suggested that I write my own softwareserial, but that's a pretty daunting task. I would like to avoid it, if i can.

**EDIT: Let me show you my data.**
So, I'm constantly transmitting the values; 123,124,125,126.

    1111011
    1111100
    1111101
    1111110

The above 4 lines repeat about 2 times. Then, suddenly, it synchronizes incorrectly, and the following 4 lines are being constantly repeated.

    11110101
    11111001
    11101101
    11110001

It never syncs back to the original 4 transmissions. Now, inside the unsynced block of 4 transmitted bytes, there are fragments of the correct transmission inside. For instance, start from the 2nd bit of the 3rd byte of the correct transmitted byte. Now, if you account for the '0' start bit, and try to matchup the bits, the correct bits are being picked up in the correct order. It's just a problem of what the receiver takes as the startbit.

As i'm typing this edit, i realized something else. What i said in the above paragraph is true, then for the unsynced block, there should be a '0' start bit in front. Now, if the messages match up exactly, and if the 0 start bit that is being transmitted is being treated as a payload, then which 0 is being treated as the startbit, because all the bits between the synced and unsynced data are matched up. However, there should be one missing 0 each time because it's being read as a startbit, not databit.

Sorry if this is convoluted. Happy to clarify any part of it. Thank you so much!!

body:
I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.

With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be *some* difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.

Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.

You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.

So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.

---

>  However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.

How will it get unsynced?  I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.

Really, to **ensure** syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.

Imagine you have an incoming stream of bits on the receiver:

    011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
    1101001010100101101001010100111011111001000010111100100011011001001001001011001001010

And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: `111111111`) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.

In other words, with 8-bit bytes, **data** will always be `0xxxxxxxx1` and thus a gap of `1111111111` must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).


message:
Unable to upload sketch on Mac OSX El Capitan

I recently dusted off an _old_ Arduino Duemilanove to play with. I can connect it to my Mac laptop with the same USB cable I used previously and I'm able to monitor the serial port and see the output from the last sketch I uploaded (five years ago). Everything is unplugged from the board.

When I try to upload a new sketch, the Arduino IDE gets stuck on `Uploading...` indefinitely:

    Using Port                    : /dev/cu.usbserial-A800eGZI
    Using Programmer              : arduino
    Overriding Baud Rate          : 19200

The board itself has the green `PWR` LED and amber `TX` LED on solid once the currently loaded sketch starts running. Initiating an upload causes the amber `L` LED to blink three times, then the `RX` LED blinks twice, and finally the `TX` LED on solid.

Here is the exact board: https://www.sparkfun.com/products/retired/666

---

My research into this issue produced many suggestions that have not resolved the problem...

I disabled the built-in FTDI driver:

    sudo kextunload -b com.apple.driver.AppleUSBFTDI

And made sure the FTDI driver from ftdichip.com was loaded:

    sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext

I tried `csrutil enable --without kext` against my better judgement and saw no change.

I also tried a completely separate machine -- my PC running Windows 10 -- and the upload hung there too.

I have tried timing the upload to coincide with a board reset, hoping to sneak my upload in before the current sketch starts running. I did this _a lot_ and got no satisfaction.

I haven't given up yet; there are too many signs of life to think that it's unrecoverable. I'm looking for more suggestions on how to troubleshoot.

I have already ordered another Arduino -- hopefully I can use it to burn the bootloader on the Duemilanove.

body: Possibly the boot-loader baud rate in the IDE's `boards.txt` file is wrong. I have older (less than 6 years) '328p chips whose boot-loaders expect 57600 baud, but the boards.txt file in more recent Arduino IDE's try to talk to them at 115200 baud. I've had to duplicate the Arduino Uno entry in boards.txt and make one that specifies 57600 baud, to use these chips.


body:
The problem was that I selected `ATMega168` when I should have selected `ATMega328`

[![facepalm][1]][1]

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


message:
Problem with analog pins' name when trying to connect Arduino board and Processing

I am trying to use Processing with Arduino Uno board to read the change of voltage done by a potentiometer. The code is simple:

    import processing.serial.*;
    import cc.arduino.*;

    Serial myport;
    Arduino arduino;

    color off = color(4, 79, 111);
    color on = color(84, 145, 158);
    int val=0;
    float value=0;
    void setup() {
      size(600, 600);
      println(Arduino.list());
      arduino = new Arduino(this, Arduino.list()[0], 57600);
      arduino.pinMode(0, Arduino.INPUT);
    }

    void draw() {
      stroke(on);
      value = arduino.analogRead(0);
      println(value);
      ellipse(300,300,value,value);
      delay(100);
    }

My question is: For analog pins in Arduino IDE one should type A0, A1, ... but here in Processing IDE it is an error to type so. Is it possible that Processing reads the wrong pin? Because in Serial output I always get zero, however, for the same circuit in Arduino IDE the values change as I turn the potentiometer knob.
Thanks

body:
(as suggested in comments to bump it down)

your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing

[![screenshot][1]][1]

If it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0

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


message:
How to know if arduino activated its short breaker?

today i was trying to use arduino power headers as a power source for my basic laser.
I used pin "5V" to connect it to the laser anode and the "GND" pin to the laser groung pin.
after doing this arduino turned restarted, so I removed all the connections to the laser, now the arduino is normal.
booth "5V" and "GND" pins is working normal.
does this mean that I made a short circut and arduino protected it self ?
should I do anything now ?

body:
It sounds like connecting your Laser to the 5 volts power supply did draw too much current, thereby the 5 volts dropped to very low voltage.

The Arduino didn't "protect" itself.  The Arduino simply shut down because of voltage being too low. Then, upon reapplication of 5 volts the Arduino re-started as normal.

You don't mention any details about the Laser.  But if your Laser is simply a Diode, the Laser diode would draw a lot of current, resulting in the 5 volts power source giving reduced voltage.

If your Laser is a "laser module" with a built in driver, perhaps you connected the Laser backwards to the 5 volts.

EDIT 11/20/2015 :  IF you are using the Arduino UNO ,  : The  PolyFuse only protects from 500 mA overload on the USB connector.  Schematic for the UNO shows that 5 volts for USB is called "XUSB". The  PolyFuse connects from "USB VCC" to the XUSB.  When you connected your Laser to the +5 and ground, the  PolyFuse was not involved. (Unless of course you did connect to the USB 5 volts (XUSB), and didn't tell us that.

HOWEVER,  if you powered your UNO from the USB port, then the  PolyFuse WAS involved and did shut you down as others have commented.


body: You uses more the 500mA limit, and the PolyFuse tripped. After unplugging the polyfuse cooled down and "reset" itself.


message:
Here is my code and i keep getting this error expected primary-expression before'}' token

#include <QTRSensors.h>
    #define NUM_SENSORS 8
    #define TIMEOUT 2500
    #define EMITTER_PIN QTR_NO_EMITTER_PIN
    QTRSensorsRC qtrrc((unsigned char[]) {10,7,6, 5, 4, 2,16,14},
    NUM_SENSORS, TIMEOUT, EMITTER_PIN);

    unsigned int sensorValues[NUM_SENSORS];
    int dirB = 12;
    int speedB = 3;
    int brakeB = 8;
    int dirA = 13;
    int speedA = 11;
    int brakeA = 9;
    int e=4;
    int MzSensor=17;
    int xp=4;

    void setup() {
    delay(500);
    int i;
    pinMode(13,OUTPUT);
    digitalWrite(13,HIGH);
    for (i = 0; i < 200; i++)
    {
      qtrrc.calibrate();
    }
    digitalWrite(13,LOW);
    Serial.begin(9600);
    delay(100);
    Serial.println("Robot");
    for (i = 0; i < NUM_SENSORS; i++)
    {
      Serial.print(qtrrc.calibratedMinimumOn[i]);
      Serial.print(' ');
    }
    Serial.println();
    {
      Serial.print(qtrrc.calibratedMaximumOn[i]);
      Serial.print(' ');
    }
    Serial.println();
    Serial.println();
    delay(100);
    }
    void loop() {
    Serial.print('ogeday');
    unsigned int position = qtrrc.readLine(sensorValues);
    unsigned char i;
    for (i = 0; i <NUM_SENSORS; i++)
    {
      Serial.print(sensorValues[i] * 10 / 1001);
      Serial.print(' ');
    }
    Serial.print("   ");
    Serial.println(position);
    delay(200);
    if (digitalRead(MzSensor)==0) {
      while(digitalRead(MzSensor)==0) {
        digitalWrite (dirA, HIGH);
        analogWrite(speedA, 76);
        digitalWrite(dirB, HIGH);
        analogWrite(speedB, 76);
        xp == 5;
        Serial.println("durdu");
        delay(100);
      }
      delay(800);
      Serial.println("CIKTI");
    }
    else
    if (position >= 3250 &&position <= 3750)
    {
      if(sensorValues [1] < 500 )
      {
        e=7;
        xp=3;
      }
      if(sensorValues [8] < 500 )
      {
        e=1;
        xp=3;
      }
      if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
      Serial.println("ILERI"),
      digitalWrite(dirA, HIGH),
      digitalWrite(brakeA, LOW),
      analogWrite(speedA, 72),
      digitalWrite(dirB, HIGH),
      digitalWrite(brakeB, LOW),
      analogWrite(speedB, 72),
      e=4,
      xp=3,

      delay (1),

    }

     else if (position > 4050 || sensorValues [8] <500)
      {
        Serial.println("EN SAG");
        digitalWrite(dirA, LOW);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 19);
        digitalWrite(dirB, HIGH);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 45);
        e=1;
        xp=3;
      }
      else if (position <- 4050 &&position >- 3900)
      {
        Serial.println("SAG");
        digitalWrite(dirA, HIGH);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 51);
        digitalWrite(dirB, HIGH);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 60);
        e=1;
        xp=3;
      }
      else if (position >= 2950 &&position <= 3100)
      {
        Serial.println("SOL");
        digitalWrite(dirA, HIGH);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 60);
        digitalWrite(dirB, HIGH);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 51);
        e=7;
        xp=3;
      }
      else if (position < 2950 || sensorValues [1] < 300 )
      {
        Serial.println("EN SOL");
        digitalWrite(dirA, HIGH);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 45);
        digitalWrite(dirB, 45);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 19);
        e=7;
        xp=3;
      }
      else if (e==7) {
        Serial.println("Cizgi SOLLL");
        if (xp!=1){
          digitalWrite(dirA, LOW);
          digitalWrite(brakeA, LOW);
          analogWrite(speedA, 30);
          digitalWrite(dirB, LOW);
          digitalWrite(brakeB, LOW);
          analogWrite(sppedB, 30);
          xp=1;
          delay(1);
        }
        digitalWrite(dirA, HIGH);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 66);
        digitalWrite(dirB, LOW);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 48);
        e=7;
      }
      else if (e==1) {
        Serial.pirntln("{Cizgi SAGGG");
        if(xp!=1) {
          digitalWrite(dirA, LOW);
          digitalWrite(brakeA, LOW);
          analogWrite(speedA, 30);
          digitalWrite(dirB, LOW);
          digitalWrite(brakeB, LOW);
          xp=1;
          delay(1);
        }
        digitalWrite(dirA, LOW);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 48);
        digitalWrite(dirB, HIGH);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 66);
        e=1;
      }
      else if (e==4) {
        Serial.println("ILERI GIDIYOR");
        digitalWrite(dirA, HIGH);
        digitalWrite(brakeA, LOW);
        analogWrite(speedA, 30);
        digitalWrite(dirB, HIGH);
        digitalWrite(brakeB, LOW);
        analogWrite(speedB, 30);
        e=4;
      }
      //delay(300)
    }

body: Change `delay (1),` to `delay (1);`


body:
In this part:

    if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
    Serial.println("ILERI"),
    digitalWrite(dirA, HIGH),
    digitalWrite(brakeA, LOW),
    analogWrite(speedA, 72),
    digitalWrite(dirB, HIGH),
    digitalWrite(brakeB, LOW),
    analogWrite(speedB, 72),
    e=4,
    xp=3,

    delay (1),

There's a lot of ',' instead of ';'. Change then to ';'.

Also, the 'if' is incomplete. Check the 'if' statement.


body:
    if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
      Serial.println("ILERI"),

1. `if()` condition is not complete
2. `;` not `,`

A little advice. Use functions so that your code is easy to read and easy to debug (looking for errors).

Something like :

    void func(String text, boolean mDirA, boolean mBrakeA, int mSpeedA,
        boolean mDirB, boolean mBrakeB, int mSpeedB){

        Serial.println(text);
        digitalWrite(dirA, mDirA);
        digitalWrite(brakeA, mBrakeA);
        analogWrite(speedA, mSpeedA);
        digitalWrite(dirB, mDirB);
        digitalWrite(brakeB, mBrakeB);
        analogWrite(speedB, mSpeedB);

    }


message:
How to connect Arduino and Beaglebone

I am newbie, I am afraid of doing harm and getting a burned-out Beagle Bone Black. I have soldered this [SparkFun Logic Level Converter - Bi-Directional][1].

I have several questions:

1. How can I check if my converter works correctly without connecting it to any board or at least only to an Arduino?

2. How should I connect all my schematic from bbb to converter and then to an Arduino. I have a bi-directional converter, BTW. Can someone draw a simple picture of how to connect?

I would be grateful for any help.

  [1]: https://www.sparkfun.com/products/12009

body:
Your main concern for frying something would be when sending data from the Arduino(which uses 5V) to the Beagle (Which uses 3.3).

The Arduino *receiving* data on the Arduino RX line wouldn't be anything to worry about since you would be sending data at 3.3V from the Beagle to 5V on the Arduino( Remember that unlike RS-232, TTL serial has no carrier voltage, so current only travels over the lines when data is actually sent )

You could always hook up the Arduino side (HV/5V), program the Arduino to do

    Serial.println("HELLO WORLD");

inside `void loop()`

and look for voltage being send over the RX pin on the LV side. You would still have to connect 3.3V to LV and GND to GND.


body:
The simplest method of connection is just to plug the Arduino into the BBB's USB socket.  That way there's no level conversion or anything needed - you can just open the serial port and communicate through that - what could be simpler?

You can even install avrdude on the BBB itself and upload code (HEX files) direct from the BBB, and the BBB supplies all the power.


body:
In addition to the other methods listed, which will both work, you could also use an Arduino that uses 3.3V logic and connect the serial/UART.

The Trinket: https://www.adafruit.com/products/1500?gclid=COGOxqq-z8kCFcYRHwodpL8P2A
Pro 328: https://www.sparkfun.com/products/10914


message:
Not sure if logic analyzer shows an error or perhaps just a 'relay bounce'

I have an Arduino controlling a relay. I was taking a look at the timings using a logic analyzer and at the onset of the relay switching, it quickly switches again.

This seems to be occurring randomly and I thought it could be highlighting a problem with my code but I wondered if it might just be a 'relay bounce' due to the speed of the switch. I've attached an image below. Any feedback is greatly appreciated. Thanks.

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

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

body:
According to your plot, the pulse length is 50 microseconds. Typical mechanical relay switching time is 10 milliseconds, which is 200 times longer. It's next to impossible that the pulse is due to your software powering the relay back on for a moment, since the relay simply could not react to such a short input pulse.

So yeah, it's just a bounce. You can safely ignore it in most cases, unless you're counting events or doing something similar. In the latter case, there are both hardware and software [debouncing][1] techniques, which share the basic idea of a low-pass filter.

  [1]: https://en.wikipedia.org/wiki/Switch#Contact_bounce


message:
Connect Digital monitor to Arduino?

I need a small display with ~ 5 digits.
The display needs to show number of visits to my site in real-time.

(Every time someone visits it needs to increase by one).

I thought to create an app, that fetches server stats every 10 seconds, and checks new number of visitors.

Do you think it is better to do with Arduino or Raspberry Pi?

Do you know of a digits monitor that can be connected to it?

body:
It all depends on how used to you are with using pi or arduino. What you want can be done in both ways.
The displaying of count is common for both. It can be done using a 16X1 LCD display, 5 different 7 segment LED connected via decoders or a graphic display module. Interfacing all these with Arduino will be relatively simpler than Pi.

For the fetching of data and sending it to your device for displaying it. You can use ESP8266 Wi-Fi module with arduino and pull the data. Which is not as simple as it sounds but it is not impossible too.

For pi, (like @max246 said) you can run a python script and use another api to get the data.


body:
For the complexity of the pulling of the data from a specific API, I would suggest to use i2c screen from adafruit and a python script running on raspberry pi. this will save you time on coding eth interface and just mostly copy and paste some simple code to communicate to the display

This is one module that I used and it is simple to use: https://www.adafruit.com/products/1270


message:
On the Uno, why does VIN require 7-12 volts and the USB only 5 volts?

I'm just wondering why the VIN would require 7-12 volts when the USB port itself only requires 5 volts? What happens if you power an Uno on VIN with 5 volts?

body:
The UNO takes your input power supply (7-12 volts) and then regulates the voltage down to 5 volts. This way, the UNO operates at a constant voltage regardless if your input power supply wanders about from 7 to 12 volts.

The USB port,  BY DEFINITION and International Standards, needs to operate at 5 volts.

If you apply 5 volts power supply, the UNO won't be able to regulate to 5 volts. The voltage regulator itself will have a voltage drop, and the UNO will operate at less than 5 volts.  The UNO may or may not operate properly. The USB will likely suffer from more problems than the UNO if you apply 5 volts.
Good news is that the UNO will not likely suffer permanent damage.


body:
USB's Vcc pin is assumed to be a stable, 5v supply, and is directly connected to the 5v bus on the Arduino board with no further regulation. Vin is assumed to be an unknown and unregulated voltage in the range of 7-12 volts.

The 7v minimum is a requirement of the design of the on-board voltage regulator which needs the 2v "head room" to maintain its output at 5v. A 5v power supply could be designed with a larger input range, even including voltages less than 5v, but the simple design used on the board covers a range of sources at a lower cost than a higher-performance power supply.


message:
Powering an Arduino UNO through 5V

I have a bench supply which I can use to power a breadboard at 5 V. Is it a bad idea to power the the Arduino by going directly to the 5 V pin? It sounds like both this method, and the USB are unregulated, so there would be no difference. Is it safe? Are there any caveats to this?

> 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

They say they "don't advise it", but why?

body:
They wouldn't advise it because they provide on board regulation. By feeding it directly you're circumventing their own protection. If however, you're providing your own regulated supply there is no reason why you can't supply it directly.

In a perfect environment, USB should already be regulated. However given the cheap imported USB hubs and plug packs that are available on the market, I would certainly argue that a good bench power supply is no problems in this regards.


message:
Interrupt on Analog Port - ESP8266 w/ Arduino

I'm trying to implement interrupts in my program. It essentially is constantly reading a photo-resistor and if it exceeds a certain threshold, we should send an update to our database. I'm struggling to understand how to do interrupts on a analog pin. I've tried [reading this][1] but honestly, it doesn't make much sense. Could anyone give me some advice? Here's out code.

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

      // Initally send out false state
      sendState("18:FE:34:F4:D0:AF", false, false);
    }

    void loop() {

      if(analogRead(A0) < 20) {
        sendState("18:FE:34:F4:D0:AF", false, true);
        lastState = true;
        Serial.println("Waiting....");
        delay(15000);
      } else if(lastState == true){
        sendState("18:FE:34:F4:D0:AF", false, false);
        lastState = false;
      }

    }

    void sendState(String address, boolean lights, boolean occupied) {

      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
      }

      String lightsStr = (lights) ? "true" : "false";
      String occupiedStr = (occupied) ? "true" : "false";
      String json = "{\"MACAddress\":\"" + address + "\", \"occupied\":" + occupiedStr + "}";

      String postData;
      postData += "POST /sensor HTTP/1.0 \r\n";
      postData += "X-Parse-REST-API-Key: " + API_KEY + "\r\n";
      postData += "Content-Type: application/json \r\n";
      postData += "Host: " + String(host) + " \r\n";
      postData += "Content-Length: " + String(json.length()) + "\r\n\r\n";
      postData += json;

      // Send the postdata to the server.
      client.print(postData);

      delay(1000);

      // Read all the lines of the reply from server and print them to Serial
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }

      Serial.println();
      Serial.println("Closing connection!");
    }

  [1]: http://forum.arduino.cc/index.php?topic=17450.0

body:
Interrupts are a tricky concept to get, you have to be mindful of so many things (in bigger projects).

Have a quick look on youtube for some tutorials, there are a heap out there.

Having said all that, your code above isn't using interrupts at all. And you have these big delays, does the code work as published?

I would suggest you rework the code into more of a state machine and have a single loop. ditch all the delays (except for your setup, that's fine) and go along the lines of:

#setup#
set a variable for current timer value and have a constant defined for your update interval
#loop#
* read sensor (consider constantly reading, or reading it more often than the information is sent, and average it out)
* anything on the serial port?
 * go read it
* check timer against old timer and interval
* interval exceeded
 * send averaged value

##using interrupts
You could use interrupts but the thing to consider is that they can be run AT ANY TIME. your code must be interrupt-able which whilst isn't too hard, needs special consideration in relation to delays, reading 16bit values, not having delays in the interrupt, status register changes, a whole host of others.

There are two types of interrupt, those that are driven by a change in input and those that are time based. You don't really want the change in state on this one because you would normally want to monitor it constantly anyway, but it is certainly doable.

In both time based and external input, you would have the interrupt set a flag that gets acted upon in your main loop.

*sorry for not providing more info at this time, screaming kids :(*