message:
arduino due-Python interfacing for high speed data rate

Four our project, I want to send data mesured by an Arduino due to a computer via Pyton very vast. So I tried to make a simple benchmark by sending 10240 int datas to determine the time it take. In order to do this, I first try using the programming port and execute this simple script:

    int i=1;
    int maxv=10240;
    int value[10240];
    int deb, fin;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(250000); //serial initialisation
      for (i=0 ; i<maxv ; i++){
        value[i]=i;
      }
      delay(200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println("starti"); //flag
      deb=micros();
      for (i=0 ; i<maxv ; i++) { // sending loop
          Serial.println(value[i]);
      }
      fin=micros();
      Serial.println("stopi");
      Serial.println((fin-deb)/1000000.0);
      delay(2000); //waiting
    }

So with this I can mesure the time it take to send all the datas. And I receive it with this Python's script:

    import numpy as np
    import serial
    ser = serial.Serial('/dev/ttyACM0', 250000)

    value=np.empty(10240)

    temp=ser.readline()

    while temp!='starti\r\n': #search for the flag
        temp=ser.readline()

    for j in range(10240):
        value[j]=int(ser.readline())

    ser.readline()

    time=float(ser.readline())
    print time

with this beaudrate, it take nearly 2.4s which too slow for my purpose. If  try another baudrate, 500000 for example I read data like this : `�Ë`$Pd@s`¥š... I have this for all baudrate higher than 250000.

So I tried the native port which normaly send the data as fast as he can, but we this it took nearly 1.3s, and it's again too slow for my purpose.

I checked that it is not python wich is too slow, by doing the same than in the last example:

    import time
    import numpy as np

    value=np.empty(10240)

    deb1 = time.clock()

    for j in range(10240):
        value[j]=j

    fin1= time.clock()
    print fin1-deb1

and it took only 4ms. So is it clearly the arduino wich send the data to slowly.

So how can I increase the data flux? I have seen the serial.write(buf,len) function which seems does not convert the data into ascii caracters. Does this function will be faster by putting the correct arguments? And, if it's the cas, how can I read this with Python?

body:
There's two things you need to know:

1. The Serial.write(buf, len) function sends the raw data - one byte for every "len" count.
2. On the Due integers are 32-bits, so each one takes 4 bytes.

So first you need to define how big the numbers are you'll be dealing with and use data types that are big enough without being wasteful - you have 3 choices: char, short and int - 8, 16 and 32 bits respectively.

* Values between 0 and 255 use an unsigned char (uint8_t)
* Values between -128 and 127 use a signed char (int8_t)
* Values between 0 and 65535 use an unsigned short (uint16_t)
* Values between -32768 and 32767 use a signed short (int16_t)
* Values between 0 and 4,294,967,295 use an unsigned int (uint32_t)
* Values between −2,147,483,648 and 2,147,483,647 a signed int (int32_t)

One very tricky thing with this kind of *binary* data transfer is knowing where a value starts and ends.  You don't get that kind of issue with ASCII representations as you have a line feed and/or a carriage return after each full value and the range of valid characters that make up a value is very narrow and can never contain the delimiting character.  You don't have that luxury with binary transfers as there is no byte value that can't appear in a data stream.  However, there could be byte sequences that could never appear in the data stream - numbers you know you'll never be using that could form part of a synchronizing header (say, in hexadecimal, 0xFF 0xFF 0xFF 0xFF 0x00 0x00 0x00 0x00 - or in signed shorts that would be a sequence of 65535 65535 0 0) - once you see that sequence of bytes you know you're lined up with your data stream and can receive it byte by byte and build up the right sized values from that.

You can estimate your transfer time by working with the baud rate and knowing the data size.  For instance, to transfer 1000 short (16 bit) values at 250000 baud should take around:

* 1000 * 2 = 2000 bytes
* 250000 baud = 25000 bytes per second (8 bits for the byte, 2 bits for the start and stop bit)
* 2000 / 25000 = 0.08s


sender: user

message:
How to use the eclipse arduino scope?

I am quite new to the Arduino stuff. I have got the Arduino IDE installed side by side with Eclipse. I am using Eclipse with the Arduino plugin, which is working well for me, including the SerialMonitor.

If you're using Eclipse with the Arduino plugin, it'll also add two new views. One is the serial monitor, the other one is called scope. Scope is a 6 channel Oscilloscope. But I don't know how to get values displayed there.

I am just curious how to use the scope there. I can't find any tutorial for this.

Can somebody explain how to show something inside the scope?

sender: assistant

body:
Given that two bytes are short, you send:

1. `SCOPE_START_DATA` `short` flag: `0xCDAB`
2. `short` number of following bytes to read (for example, `0x0002` for only one channel)
3. one `short` per channel

P.S. This is shamelessly stolen from it.baeyens.arduino.monitor.views.ScopeListener


body:
Try the [simplot library][1].

It is from the author of the plugin and works with both 32 and 8 bit processors. There is an example included that should get you going.

The plotter itself automatically connects to the first serial connection so there is no connect needed for the plotter like there is for the serial connection.

  [1]: https://github.com/jantje/libraries/tree/master/simplot


body: The plugin FAQ links to a defunct website. However the internet wayback machine reveals some good info (https://web.archive.org/web/20150321054307/http://www.negtronics.com/simplot). In particular a link to the arduino forums that has some code samples: http://forum.arduino.cc/index.php?topic=58911.0


body:
The simplot library (referenced below) is an excellent example of how to use the scope which works as advertised.
Firstly, readers should note that there are two different Arduino plugins for Eclipse ("Eclipse C++ IDE for Arduino" and "Arduino Eclipse plugin named Sloeber V3"). Only the latter has a scope and a seriel monitor that allows data to be sent.
Getting simplot and the scope to work, however, can be a problem depending on the platform. On a Mac, with the latest version of Eclipse (Neon.2 Release Candidate 2) and the Sloeber V3 plugin, the default path to the Private Library is Users/yourname/Arduino/libraries. Unfortunately, this path doesn't (necessarily) exist.
One could spend hours trying to figure out how and where to import a library when the critical library folder doesn't exist.

The solution (at least on a Mac):

 - Create a folder (arbitraily) named "Users/yourname/Eclipse/libraries".
 - Include this folder in Eclipse - Preferences - Arduino - Private Library Path
 - Download jantje's [entire Github Arduino Library][1], unpack it and move the "simplot" folder into your Private Library Folder. "simplot" should now show up in the libraries.
 - Use: Arduino - Add a Library to the Selected Project
 - Or build a project using the simplot.ino example.

It should work beautifully.

  [1]: https://github.com/jantje/ArduinoLibraries


message:
Advice on setting up a real-time audio equaliser

First time Arduino user here.

We have a microphone set-up which feeds back loudly on particular frequencies and need an equalizer to (preferably automatically) detect spikes in particular frequency bands and attenuate them before sending them on to the speakers. The dB level that has been cut from that frequency channel would then be displayed on an LED matrix such as this one:

[![LED Matrix][1]][1]

Does the Arduino have the processing capabilities to keep up with the audio without noticeable lag? As the LEDs will only be a visual indication of the affect the attenuation is having on the frequencies, it is not particularly important that these be fast. Unfortunately, as the audio stream will be vocals, even a slight delay will render the thing useless. What delay might I expect with a single mono channel going through the arduino?

I expect that I will eventually have to revert to the less-interesting project of an RTA which takes a split of the audio sends to the speakers and simply displays the frequency band intensities rather than altering them.

I'd appreciate any thoughts.

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

body:
Somewhat possible if you accept that the Arduino won't be doing most of the work:

* Yes, the Arduino can sample audio and perform FFT on it, though not fast and not at high frequencies
* Yes, the Arduino can decide what to do depending on the power of different buckets
* Yes, the Arduino can display the results
* No, the Arduino cannot do realtime audio filtering.

If you accept that the filtering will have to be done with a bank of analogue band-cut filters that the Arduino turns on and off as needed then it may be possible.

The Arduino Due might be a more suitable candidate since it will be able to sample and do the FFT much faster so you'll be able to respond to the peaks much quicker, and the displaying won't get in the way so much, but actively filtering inside the chip really requires a DSP.


message:
Serial communication using Arduino and TeraTerm

I wrote a simple serial program using Arduino Mega 2560, it is connected to COMPORT 10. Here is the program I Wrote,

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

    void loop()
    {
      Serial.println("HELLO");
      delay(1000); //Send every one second
    }

Now, I tried to send this message "Hello" to TeraTerm (COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. Doing this I do receive message in my TeraTerm screen but the received message doesn't make sense, its receiving garbage. Its not the case of mismatch of baud rate I am using 9600 on both the side.

However I do receive message "HELLO" in the serial monitor. Is there something I am doing wrong that I am not receiving message on TeraTerm.

body:
> ... I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0.

But neither device knows what voltage they are. You need to connect ground as well so that they have a common reference.


body:
Hello everyone thanks for your reply,

I found the problem :D and was also able to solve it.

I was directly connecting the Tx and Rx pin of Arduino to the Rx and Tx pin of DB9 connector on PC. Since, DB9 on the PC operates on higher voltage than the operating voltage of the Arduino which is 5V. This mis-match of the voltage was causing the problem, So in order to solve this i added a level shifter in between (MAX232) and now it works perfect.

Thanks everyone for replying.


message:
How to interconnect multiple Arduinos with a Rpi to control home-lights/switches

While planning the lightning infrastructure (wall-switches and lights) of my new home (it's still under-construction) I choosed to go through the "automated route" way and due to my background (I'm an "old" system/network administrator with programming skills and plenty of Open-Source "passion" and "advocacy") I'm seriously trying to implement it with three Arduinos and one RPi2.

Due to number/location of wall-push-buttons and lights, I'd like to use three MEGA interfacing both wall-push-buttons and lights of surrouding rooms. Furthermore, a RPi2 (or similar) will be used as a "controller" to properly programs MEGAs, when needed, and interfacing some other equipments (touch-screen; wifi tablet/smartphone; remote-controls; etc.) via the IP-network.

The schema I'm trying to implement is similar to this one:

[![Draft Schema][1]][1]
where you see:

 - 9 lights (L1 to L9) each one controlled by its own dedicated relay (R1 to R9);
 - 7 wall push-buttons (WPB1 to WPB7), to be used to turn on/off one or more lights;
 - 3 MEGAs interfacing wall-push-buttons and lights;
 - 1 RPi2, acting as "supervisor" and "Internet/Ethernet gateway".

My main architectural problem relates to the interconnection between RPI2 and MEGAs. As each device will be located several tens of meters aways from each other, I ended with two only option (please, correct me if I'm wrong):

 1. Ethernet
 2. RS485

(*BTW: I'm explicitely excluding "wireless connections", as I've already placed all the electrical pipes in a "compatible" way. In other words: I'd like to avoid wireless technologies within the "controlling network"*)

As for Ethernet, I'll choose it as a 2nd option, due both to a slightly higher cost and complexity (need a switch to be powered on; additional cabling issues; etc.).

I've extensively researched the "**RS485 bus**" and found that it's relatively easy --from a physical point of view-- to implement it with [two wires in a multidrop configuration][2].

Unfortunately, from an "application point of view", things are more complex as it supports only "half-duplex" communications and, even worse, there is **no** provision to avoid "collisions" when communicating (that's why, probably, the MODBUS protocol --tipically employed on RS485 bus-- provides a "single-master; multiple-slaves" scenario).

Before the questions, I need to add another constraint: I want the infrastructure to be "as much fault-tolerant as possible", expecially towards problems with the BUS and/or with the "controller" (the RPI2). In other words:

  - each MEGA should allow to turn on its own lights when one of its own push-button requires this. For example:
      - if WPB1 controls L2 and L3, it need to be working even if the BUS is broken or the RPI2 is powered off;
      - if WPB3 controls L4 and L9, then should the bus/RPI2 have problems, only L4 will be powered on when WPB3 is pressed;

So, after all of the above, here are my questions:

 1. is a two-wire RS485 multidrop bus, a suitable choice for my scenario?

 2. if not, which (possibly cheap and simple) other solutions may I investigate?

 3. if yes, which is the logic that I need to implement on MEGAs, as:
    - a) they need to act as "slave", with respect to RPI2 when turning on lights commanded by push-button connected to other MEGAs or when the RP2 decide to turn-on some lights (for example, due to remote/Internet access);
    - b) they need to act as "master", when one of their push-buttons is pressed and... this need to be communicated to RPI2 so to send commands to other MEGAs so to turn on "hosted" lights;

 4. as for 3b), insted of having MEGAs acting as master when a WPB is pressed, may I implement a "frequent-polling" logic on the RPI2? If yes, which is a reasonable value for such a polling (1 poll per second? 5 polls per second? too much? too low?)

I understand that this is a too-wide question, but I really did **lots** of researches and despite lots, and lots, and lots of on-line documentation, I've been unable to find an answer to those questions.

-----

Update 1
========

 - in terms of total numbers, I'll have 31 lights to be controlled by 46 wall push-buttons, more or less equally distributed in 4 distinct panel-boards;
 - As for the choise of MEGA (vs. UNO), I've choosed MEGA due to the bigger number of I/O PINs. I simply choosed the board with the maximun number of PINs;
 - As for the RPI2, I choosed to employ a proper "computer" (vs. an additional microcontroller), 'cause I want a sort of "decoupling" between the "physical controlling network" and the "User Management Interface". In other words, I want the management of physical buttons/relais to be handled by PLC-like device (Arduino: very quick power on; sort of real-time performance; very reliable; minor/no external "computing" factors introducing delays/problems); while, at the same time, all the user-interface be handled by a real-computer where I can easily write powerful HTTP web-services and/or really complex "logics", using technologies and languages that doesn't fit well with Arduino (later on --much later on--, I plan to add several 150$ full-HD 10.1" android tablets allaround the house, that will act as wireless "clients" towards what need to be a "powerful" (in terms of computing capacities) web-server; Also I plan to add various sensors [temperature; humidity; contacts; power-meters; etc.] whose data need to be stored for trending/archiving reasons). Hence, I tought about RPi2, than can easily be replaced with something more powerful, should it be needed.

  [1]: https://i.stack.imgur.com/eyX3P.png
  [2]: https://arduino-info.wikispaces.com/RS485-Modules

body:
<!-- language-all: lang-C++ -->

I did a [lengthy post about RS485](http://www.gammon.com.au/forum/?id=11428).

---

First, your use of Megas seems an overkill, unless you already have them to hand. A Uno, or one of the smaller form-factor boards would seem to be perfectly adequate to monitor a few switches and turn on a couple of lights.

Even the Rpi seems unnecessary. Another Uno could easily monitor your RS485 lines and connect via Ethernet (an Ethernet shield) to the rest of your house or whatever you are doing.

---

>  ... there is no provision to avoid "collisions" when communicating ...

Well, you build that in. You give each Mega an address (eg. stored in EEPROM) and then you "address" the one you want, and then wait for a response. For example, in the code from my page above:

**Master**

    #include "RS485_protocol.h"
    #include <SoftwareSerial.h>

    const byte ENABLE_PIN = 4;
    const byte LED_PIN = 13;

    SoftwareSerial rs485 (2, 3);  // receive pin, transmit pin

    // callback routines

    void fWrite (const byte what)
      {
      rs485.write (what);
      }

    int fAvailable ()
      {
      return rs485.available ();
      }

    int fRead ()
      {
      return rs485.read ();
      }

    void setup()
    {
      rs485.begin (28800);
      pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
      pinMode (LED_PIN, OUTPUT);  // built-in LED
    }  // end of setup

    byte old_level = 0;

    void loop()
    {

      // read potentiometer
      byte level = analogRead (0) / 4;

      // no change? forget it
      if (level == old_level)
        return;

      // assemble message
      byte msg [] = {
         1,    // device 1
         2,    // turn light on
         level // to what level
      };

      // send to slave
      digitalWrite (ENABLE_PIN, HIGH);  // enable sending
      sendMsg (fWrite, msg, sizeof msg);
      digitalWrite (ENABLE_PIN, LOW);  // disable sending

      // receive response
      byte buf [10];
      byte received = recvMsg (fAvailable, fRead, buf, sizeof buf);

      digitalWrite (LED_PIN, received == 0);  // turn on LED if error

      // only send once per successful change
      if (received)
        old_level = level;

    }  // end of loop

You configure the RS485 transceiver to either send or receive. Normally it is in receive mode, and you switch to send mode to send a "packet" of data. (See "enable sending" above).

---

Now the addressed device turns its transceiver into "send" mode and replies. The code in the library I wrote has a time-out, so if that particular slave is dead, the receive times out. You might remember that at the master end and try to communicate with it less often. Or you may not care if the time-out is short.

**Slave**

    #include <SoftwareSerial.h>
    #include "RS485_protocol.h"

    SoftwareSerial rs485 (2, 3);  // receive pin, transmit pin
    const byte ENABLE_PIN = 4;

    void fWrite (const byte what)
      {
      rs485.write (what);
      }

    int fAvailable ()
      {
      return rs485.available ();
      }

    int fRead ()
      {
      return rs485.read ();
      }

    void setup()
    {
      rs485.begin (28800);
      pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
    }

    void loop()
    {
      byte buf [10];

      byte received = recvMsg (fAvailable, fRead, buf, sizeof (buf));

      if (received)
        {
        if (buf [0] != 1)
          return;  // not my device

        if (buf [1] != 2)
          return;  // unknown command

        byte msg [] = {
           0,  // device 0 (master)
           3,  // turn light on command received
        };

        delay (1);  // give the master a moment to prepare to receive
        digitalWrite (ENABLE_PIN, HIGH);  // enable sending
        sendMsg (fWrite, msg, sizeof msg);
        digitalWrite (ENABLE_PIN, LOW);  // disable sending

        analogWrite (11, buf [2]);  // set light level
       }  // end if something received

    }  // end of loop

*Note*: The example code from my linked page does not read the address from EEPROM, however that is trivial to implement.

---

I can't see any particular reason why you could not interrogate the slaves quite frequently. What else would the master be doing? You could also set up the master as a HTTP server so you could talk to it from your laptop, or some other part of the house.

---

My wiring:

[![RS485 wiring][1]][1]

---

To demonstrate the idea, I set up two Unos, connected via about 8 m of bell-wire (not even twisted pair, and certainly not shielded).

[![RS485 demo][2]][2]

One Uno was running the standard ASCII table sketch (at 9600 baud), its Tx pin went into the LTC1480, and then the A/B pins went to the bell wire.

The other Uno was connected as a USB interface (Reset connected to ground) and it was just echoing whatever arrived on the Tx pin to the USB.

As far as I could see, it worked perfectly.

---

> I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

My answer above assumed that the slaves were more likely to fail than the master (can't quite think why this would happen, but perhaps based on the fact that there are more slaves than masters, and the master doesn't control things like lights).

I find my Arduinos extremely reliable when doing simple things (like unlocking a door when a RFID card is presented).

You could conceivably build a fall-back position into the slaves. After all, if they get polled every second, and then no poll arrives, they could conceivably attempt to take over as master, perhaps in ascending order of device number, to avoid conflicts. Part of this polling by the "new master" could be to check the "original master" to see if it was ready to resume its duties.

The library I described on my linked page has error checking built into it, the idea being that by checking a CRC on the packet you ensure that you don't come in half-way through a packet and misinterpret the data in it.

You could also build in some randomness of poll times to resolve a deadlock if two slaves attempted to become master at once. If a slave failed it could wait for a random (and increasing) time before trying again to give another slave a chance to do it.

---

> I just wanted to note that the chance of packet collisions is rather low. You only send packets when a switch is pressed, or when a light needs to turn on.

Gerben is right, but I would be worried that a notification about a switch had gone unnoticed. One possible work-around here is rather than the slaves replying with state changes to a query, they reply with the current state. So it might go:

    Master: Slave 3, what is your status?
    Slave 3: Lights 1 and 4 on, lights 2 and 3 off.

---

>  I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

I've been thinking about this a bit, and I think now you could make a system that is basically master-free. It could work like this:

* Each device has its own address, which it gets from EEPROM (or DIP switches). eg. 1, 2, 3, 4, 5 ...

* You choose a range of addresses you are going to use (eg. maximum of 10)

* When the device powers up it first listens for other devices "talking" on the bus. Hopefully it will hear at least one other (if not, see below).

* We decide on a fixed "message packet", say of 50 bytes including address, CRC, etc. At 9600 baud that would take 52 ms to send.

* Each device gets a "slot" of time, and waits its turn to talk to the bus.

* When its timeslot arrives, it goes into output mode, and broadcasts its packet which includes its own address. Therefore all the other devices can now read its status (and act upon it if necessary). Eg. device 1 might report that switch 3 is closed, which means device 2 must turn a light on.

* Ideally, you know your timeslot has arrived because your device address is one greater than the packet you just listened to. Eg. You are device 3. You just heard device 2 announce its status. Now it's your turn. Of course, you wrap around at the maximum number, so after device 10 you go back to device 1.

* If a device is missing and does not respond, you give it (say) half a timeslot to respond, and then assume it is dead, and every device on the bus now assumes the next timeslot has started. (eg. You heard device 2, device 3 should respond, after 25 ms of inactivity, device 4 can now respond). This rule gives a device 25 ms to respond, which should be plenty even if it is servicing an interrupt or something like that.

* If multiple devices in sequence are missing you count a 25 ms gap for each missing device, until it is your turn.

* Once you get at least one response the timing is resynchronized, so any drift in clocks would be cancelled.

The only difficulty here is that upon initial power-up (which might happen simultaneously if the power to the building is lost and then restored) there is no device currently broadcasting its status, and thus nothing to synchronize to.

In that case:

* If after listening long enough for all devices to be heard (eg. 250 ms) and hearing nothing, the device tentatively assumes it is the first one and makes a broadcast. However possibly two devices will do that at the same time, and thus never hear each other.

* If a device has not heard from another device, it staggers the time between broadcasts randomly (perhaps seeding the random-number generator from its device number, to avoid all devices "randomly" staggering the broadcasts by the same amount).

* This random staggering by additional amounts of time won't matter, because there is no-one listening anyway.

* Sooner or later one device will get exclusive use of the bus and the other ones can then synchronize with it in the usual way.

This random gap between attempts to communicate is similar to what Ethernet used to do when multiple devices shared one coaxial cable.

---

## Demo of master-free system

This was an interesting challenge, so I put together a demo of doing this without having any specific master, as described above.

First you need to set up the current device address, and the number of devices, in EEPROM, so run this sketch, changing `myAddress` for each Arduino:

    #include <EEPROM.h>

    const byte myAddress = 3;
    const byte numberOfDevices = 4;

    void setup ()
      {
      if (EEPROM.read (0) != myAddress)
        EEPROM.write (0, myAddress);
      if (EEPROM.read (1) != numberOfDevices)
        EEPROM.write (1, numberOfDevices);

      }  // end of setup

    void loop () { }

Now upload this to each device:

    /*
     Multi-drop RS485 device control demo.

     Devised and written by Nick Gammon.
     Date: 7 September 2015
     Version: 1.0

     Licence: Released for public use.

     For RS485_non_blocking library see: http://www.gammon.com.au/forum/?id=11428
     For JKISS32 see: http://forum.arduino.cc/index.php?topic=263849.0
    */

    #include <RS485_non_blocking.h>
    #include <SoftwareSerial.h>
    #include <EEPROM.h>

    // the data we broadcast to each other device
    struct
      {
      byte address;
      byte switches [10];
      int  status;
      }  message;

    const unsigned long BAUD_RATE = 9600;
    const float TIME_PER_BYTE = 1.0 / (BAUD_RATE / 10.0);  // seconds per sending one byte
    const unsigned long PACKET_LENGTH = ((sizeof (message) * 2) + 6); // 2 bytes per payload byte plus STX/ETC/CRC
    const unsigned long PACKET_TIME =  TIME_PER_BYTE * PACKET_LENGTH * 1000000;  // microseconds

    // software serial pins
    const byte RX_PIN = 2;
    const byte TX_PIN = 3;
    // transmit enable
    const byte XMIT_ENABLE_PIN = 4;

    // debugging pins
    const byte OK_PIN = 6;
    const byte TIMEOUT_PIN = 7;
    const byte SEND_PIN = 8;
    const byte SEARCHING_PIN = 9;
    const byte ERROR_PIN = 10;

    // action pins (demo)
    const byte LED_PIN = 13;
    const byte SWITCH_PIN = A0;

    // times in microseconds
    const unsigned long TIME_BETWEEN_MESSAGES = 3000;
    unsigned long noMessagesTimeout;

    byte nextAddress;
    unsigned long lastMessageTime;
    unsigned long lastCommsTime;
    unsigned long randomTime;

    SoftwareSerial rs485 (RX_PIN, TX_PIN);  // receive pin, transmit pin

    // what state we are in
    enum {
       STATE_NO_DEVICES,
       STATE_RECENT_RESPONSE,
       STATE_TIMED_OUT,
    } state;

    // callbacks for the non-blocking RS485 library
    size_t fWrite (const byte what)
      {
      rs485.write (what);
      }

    int fAvailable ()
      {
      return rs485.available ();
      }

    int fRead ()
      {
      lastCommsTime = micros ();
      return rs485.read ();
      }

    // RS485 library instance
    RS485 myChannel (fRead, fAvailable, fWrite, 20);

    // from EEPROM
    byte myAddress;        // who we are
    byte numberOfDevices;  // maximum devices on the bus

    // Initial seed for JKISS32
    static unsigned long x = 123456789,
                         y = 234567891,
                         z = 345678912,
                         w = 456789123,
                         c = 0;

    // Simple Random Number Generator
    unsigned long JKISS32 ()
      {
      long t;
      y ^= y << 5;
      y ^= y >> 7;
      y ^= y << 22;
      t = z + w + c;
      z = w;
      c = t < 0;
      w = t & 2147483647;
      x += 1411392427;
      return x + y + w;
      }  // end of JKISS32

    void Seed_JKISS32 (const unsigned long newseed)
      {
      if (newseed != 0)
        {
        x = 123456789;
        y = newseed;
        z = 345678912;
        w = 456789123;
        c = 0;
        }
      }  // end of Seed_JKISS32

    void setup ()
      {
      // debugging prints
      Serial.begin (115200);
      // software serial for talking to other devices
      rs485.begin (BAUD_RATE);
      // initialize the RS485 library
      myChannel.begin ();

      // debugging prints
      Serial.println ();
      Serial.println (F("Commencing"));
      myAddress = EEPROM.read (0);
      Serial.print (F("My address is "));
      Serial.println (int (myAddress));
      numberOfDevices = EEPROM.read (1);
      Serial.print (F("Max address is "));
      Serial.println (int (numberOfDevices));

      if (myAddress >= numberOfDevices)
        Serial.print (F("** WARNING ** - device number is out of range, will not be detected."));

      Serial.print (F("Packet length = "));
      Serial.print (PACKET_LENGTH);
      Serial.println (F(" bytes."));

      Serial.print (F("Packet time = "));
      Serial.print (PACKET_TIME);
      Serial.println (F(" microseconds."));

      // calculate how long to assume nothing is responding
      noMessagesTimeout = (PACKET_TIME + TIME_BETWEEN_MESSAGES) * numberOfDevices * 2;

      Serial.print (F("Timeout for no messages = "));
      Serial.print (noMessagesTimeout);
      Serial.println (F(" microseconds."));

      // set up various pins
      pinMode (XMIT_ENABLE_PIN, OUTPUT);

      // demo action pins
      pinMode (SWITCH_PIN, INPUT_PULLUP);
      pinMode (LED_PIN, OUTPUT);

      // debugging pins
      pinMode (OK_PIN, OUTPUT);
      pinMode (TIMEOUT_PIN, OUTPUT);
      pinMode (SEND_PIN, OUTPUT);
      pinMode (SEARCHING_PIN, OUTPUT);
      pinMode (ERROR_PIN, OUTPUT);

      // seed the PRNG
      Seed_JKISS32 (myAddress + 1000);

      state = STATE_NO_DEVICES;
      nextAddress = 0;

      randomTime = JKISS32 () % 500000;  // microseconds
      }  // end of setup

    // set the next expected address, wrap around at the maximum
    void setNextAddress (const byte current)
      {
      nextAddress = current;
      if (nextAddress >= numberOfDevices)
        nextAddress = 0;
      }  // end of setNextAddress

    // Here to process an incoming message
    void processMessage ()
      {

      // we cannot receive a message from ourself
      // someone must have given two devices the same address
      if (message.address == myAddress)
        {
        digitalWrite (ERROR_PIN, HIGH);
        while (true)
          { }  // give up
        }  // can't receive our address

      digitalWrite (OK_PIN, HIGH);

      // handle the incoming message, depending on who it is from and the data in it

      // make our LED match the switch of the previous device in sequence
      if (message.address == (myAddress - 1))
        digitalWrite (LED_PIN, message.switches [0]);

      digitalWrite (OK_PIN, LOW);
      } // end of processMessage

    // Here to send our own message
    void sendMessage ()
      {
      digitalWrite (SEND_PIN, HIGH);
      memset (&message, 0, sizeof message);
      message.address = myAddress;

      // fill in other stuff here (eg. switch positions, analog reads, etc.)

      message.switches [0] = digitalRead (SWITCH_PIN);

      // now send it
      digitalWrite (XMIT_ENABLE_PIN, HIGH);  // enable sending
      myChannel.sendMsg ((byte *) &message, sizeof message);
      digitalWrite (XMIT_ENABLE_PIN, LOW);  // disable sending
      setNextAddress (myAddress + 1);
      digitalWrite (SEND_PIN, LOW);

      lastCommsTime = micros ();   // we count our own send as activity
      randomTime = JKISS32 () % 500000;  // microseconds
      }  // end of sendMessage

    void loop ()
      {
      // incoming message?
      if (myChannel.update ())
        {
        memset (&message, 0, sizeof message);
        int len = myChannel.getLength ();
        if (len > sizeof message)
          len = sizeof message;
        memcpy (&message, myChannel.getData (), len);
        lastMessageTime = micros ();
        setNextAddress (message.address + 1);
        processMessage ();
        state = STATE_RECENT_RESPONSE;
        }  // end of message completely received

      // switch states if too long a gap between messages
      if  (micros () - lastMessageTime > noMessagesTimeout)
        state = STATE_NO_DEVICES;
      else if  (micros () - lastCommsTime > PACKET_TIME)
        state = STATE_TIMED_OUT;

      switch (state)
        {
        // nothing heard for a long time? We'll take over then
        case STATE_NO_DEVICES:
          if (micros () - lastCommsTime >= (noMessagesTimeout + randomTime))
            {
            Serial.println (F("No devices."));
            digitalWrite (SEARCHING_PIN, HIGH);
            sendMessage ();
            digitalWrite (SEARCHING_PIN, LOW);
            }
          break;

        // we heard from another device recently
        // if it is our turn, respond
        case STATE_RECENT_RESPONSE:
          // we allow a small gap, and if it is our turn, we send our message
          if (micros () - lastCommsTime >= TIME_BETWEEN_MESSAGES && myAddress == nextAddress)
            sendMessage ();
          break;

        // a device did not respond in its slot time, move onto the next one
        case STATE_TIMED_OUT:
          digitalWrite (TIMEOUT_PIN, HIGH);
          setNextAddress (nextAddress + 1);
          lastCommsTime += PACKET_TIME;
          digitalWrite (TIMEOUT_PIN, LOW);
          state = STATE_RECENT_RESPONSE;  // pretend we got the missing response
          break;

        }  // end of switch on state

      }  // end of loop

As it currently stands, if you close a switch on A0 (short to ground) it will turn off a LED (pin 13) on the next highest device in sequence. This proves that the devices are talking to each other. Of course in practice you would have something more sophisticated in the packet which is being broadcast.

I found in testing that the LED appeared to come on and off instantly.

With all devices disconnected the first one connected will "hunt" for other devices. If you have debugging LEDs connected as I did you can see the "search" LED come on at random intervals as it broadcasts its packet with randomly-varying gaps. Once you have a second one connected they settle down and just exchange information. I tested with three connected at once.

It would probably be more reliable with HardwareSerial - I used SoftwareSerial to help with debugging. A few small changes would accomplish that.

---

## Amended schematic

[![RS485 moving master schematic][3]][3]

---

## Screen-shots of the code in action

These images show the code working. First, with only one device connected:

[![RS485 - one device][4]][4]

You can see from the pulses there that the device is broadcasting its data at randomly-varying intervals, to avoid continuing to clash with another device that powered up at the same moment.

---

[![RS485 - two devices][5]][5]

Now we see blocks of data from two devices, with roughly the same size gaps in the middle. I configured it for four devices, but only two are present, so we see two blocks of data, and two gaps.

---

[![RS485 - three devices][6]][6]

Now with three devices online, we see three blocks of data, and one gap, as the missing device is bypassed.

---

If you are checking the figures, these were taken with the baud rate doubled, as a test, to 19200 baud.

---

## Cable run test

For a proper hardware test, I connected the devices up to my in-house UTP cabling. I have cat-5 cable running from various rooms to a central plug-board. Going from one end of the house to another (a reasonable length run) it still works fine. There is 5 m cable between the Arduino and the wall socket, for a start. Plus another 5 m cable at the other end. Then there are about 2 x 15 m runs from the rooms to the switch room, and inside that there is a short bridging cable to connect them together.

This was with the boards still programmed to run at 19200 baud.

  [1]: https://i.stack.imgur.com/unAvv.png
  [2]: https://i.stack.imgur.com/7Kttu.jpg
  [3]: https://i.stack.imgur.com/IbHz8.png
  [4]: https://i.stack.imgur.com/3vqnR.png
  [5]: https://i.stack.imgur.com/4KZCZ.png
  [6]: https://i.stack.imgur.com/gPYau.png


body:
Remember RS485 is not a protocol, it is a definition of a physical transport layer.  With the Mega as you chose you can use serial 1,2,3 and run them in full duplex mode over the RS485 network e.e. you can receive what you send.

I have it operating in a multi master configuration.  Each mega when it transmits it also receives what it just sent and can determine on a byte by byte basis if it needs to back off.  The delay before coming back on line is determined by the node address and when the bus becomes available.

The code will use the write function instead of the print function allowing each byte to be checked. (In time I probably will do it via software and emulate CAN or just use a can controller). Yes 8 bits works just fine, the ninth bit is a parity bit or other uses depending on who is defining it.

My test system is operating with packets and sends in this format:

 |Length|Target|Source|Sequence|Command|Flags|Data|Check

and expects an ACK in response.  This is relative simple first pass and has no illegal codes. All bytes are Hex but you can use what you want.

This gives me Carrier Sense, multiple access but with destructive arbitration.  If you want CSMANDA just use a CAN physical layer or bit bang the data you send then you can arbitrate on a bit by bit basis.  It won't be that much different in software other then the transmit portion.

I am planning on using the RPi with Linux as the main node. With 8 bit data it will work just fine.  I just started about two weeks ago on this configuration and so far it is going well. I am operating at 9600 baud and have a lot of free time.

Gil


body:
If you want to use Nick Gammon's protocol you might find this useful: https://github.com/Sthing/Nick-Gammon-RS485

It is my implementation of the protocol in Python (for use on a RaspberryPi).
I have only tested python-to-python yet, testing against Nick Gammon's code is next on my to do list.

/Thing


body:
I think the CDBUS protocol for RS485 is exactly what you want, it introduce an arbitration mechanism that automatically avoids conflicts like the CAN bus. I can even transfer video stream through it:

[![enter image description here][1]][1]
Full video:
https://youtu.be/qX5dh4wcfSk

The Raspberry Pi can output preview video and control command at the same time. We can monitor the recognition process on the PC. When problems are encountered, it is convenient to know the reason and adjust the parameters, and disconnecting the PC will not affect the demo operation.

[![enter image description here][2]][2]
In addition, the Raspberry Pi can access the internet at any time through the PC, and it is easy to update software and for remote control.

Details about the CDBUS:

 - https://github.com/dukelec/cdbus_doc (Introduction)
 - https://github.com/dukelec/cdbus_ip (Protocol details & FPGA IP core)

Update:
Connect the CDCTL-Bx controller to an Arduino:
[![arduino and cdctl][3]][3]

  [1]: https://i.stack.imgur.com/09PiM.jpg
  [2]: https://i.stack.imgur.com/R7KJt.png
  [3]: https://i.stack.imgur.com/uKIOh.jpg


message:
How to network multiple Arduinos so they react to the same signal

I want to build a project that contains multiple Arduino nano's, each connected to one controlling Raspberry Pi.  I would like to send one signal (a string of characters or numbers) which would be the master state, which the other Arduinos would react to based on their programming.  What is the best way to do this?

Can the Arduino support a protocol for this, or will it need additional hardware?

Max distance: 30 meters

body:
Rule 1 do not connect Arduino pins to long wires.

You can achieve your your goal in many ways, a serial interface looks good from here.  I am doing it with a RS485 interface, note it is an interface not a protocol. You can use CAN, Wi-fi and many others.  It sounds like all the units except 1 will be receiving data, the other is transmitting it to the other devices.  RS485 will work good and it needs only 5V.  It will work over several thousand feet and some reasonable speeds. You can use a UART either hardware or software to accomplish the task with a RS-485 driver at each node.  You need to remember you need to wire from point to point with the terminating resistors only on the end nodes.


message:
SSH and web interface broken on Yun

I have two Arduino Yuns that are not accessible *at all* on the network. I can't go to the arduinoname.local, ssh arduinoname.local, as I previously could. I know at least one it working because it sends emails as I programmed it, yet it seems there is no longer a way to ssh into it. Any ideas?

Yes, I have unplugged, plugged in the router,  and the yuns.

body:
It turns out the problem is a fairly common one - Actiontec wireless access points break this way when set to Both, not AES - see https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network

Apparently on other routers this bug is marked as a feature, "Wireless Isolation" or something.


message:
What are some fun things you can do using the ICSP header?

I bought 10 Arduino Nanos for a project, each with all of their headers soldered in place.  Each was going to go into a tiny space, so I found myself needing do desolder the ICSP headers.

This led to a bit of a moral conundrum.  What would I lose by removing these useful looking headers.  They cover quite a lot of space on the nano, so they must be important right?  Am I going to regret removing these things when I finally realize how useful they are (I thought to myself.)

In the end, I did remove the ICSP headers, but the event got my thoughts going.  What is this header all about?  Why is it there?  What can I do with it?  I began to search for things that I could do with the ICSP header, but engaging results were not forthcoming ( except for this project:  [https://www.arduino.cc/en/Hacking/ParallelProgrammer][1] )

Anyway, I was more interesting in things that flash, move, jump, sing, and such, so are there any interesting things that can be done with the ICSP header?

  [1]: https://www.arduino.cc/en/Hacking/ParallelProgrammer

body:
 1. You can use *every single last byte* of flash on the device.

    Since you're performing low-level programming of the device you get the entire chip to play on, without having to worry about bootloaders and such.

 2. You can debug (breakpoint, single-step, watch, disassemble, etc.) the code on the chip using software on your computer.

    Admittedly the devices you'd need in order to do so are more expensive than a simple ISP programmer and it only works with specific pieces of software, but it can be done.


body:
One interesting thing I just came up with: you could use this header to attach a simple control panel for your Arduino.

Imbed the Arduino in any place/box/machine you like. Then use a cable with a 6 pin connector to connect the header to a small control panel.  The panel could have 3 buttons or LEDs, a reset button and a power plug.


message:
Using for loop to set pinMode

I notice problems with my output pins when I use this method of setting their `pinMode`:

    int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};

    for(int a = 0; a < sizeof(allOutputPins); a++){
       pinMode(allOutputPins[a], OUTPUT);
      }//end for

Am I doing something wrong?

body:
Re  “Am I doing something wrong?”, yes :)

The `sizeof(allOutputPins)` expression returns the size of `allOutputPins[]` in terms of bytes, so is 24 because the array contains 12 two-byte integers.  The loop's last 12 `pinMode()` calls will be garbage.

Among other ways of fixing the problem, you could change the expression to `sizeof(allOutputPins)/sizeof(int)` [which has the same value, 12, as `(sizeof allOutputPins)/sizeof(int)`; eg see the syntax entries for the [sizeof operator](http://en.cppreference.com/w/cpp/language/sizeof) at cppreference.com] or you could change the base type of the array to `byte` or `uint8_t`.


message:
Inheritance: error in calling the constructor of the base class?

I want to write a library for the RGBDigit shield (http://rgbdigit.com/), which essentially is an Adafruit Neopixel strip, packed as a 7 segment display. The shield also has a DS3231 clock and an IR receiver.

So my plan was to make a class *RGBDigit*, which inherits from the *Adafruit_NeoPixel* class and add private objects *DS3231* and *IRrecv*.

This is my RGBDigit.h:

<!-- language: c -->

    #ifndef RGBDigit_h
    #define RGBDigit_h

    #include <Arduino.h>
    #include "Wire.h"
    #include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
    #include "../IRremote/IRremote.h"
    #include "../DS3231/DS3231.h"

    class RGBDigit : public Adafruit_NeoPixel {
        public:
            RGBDigit(int nDigits);
            ~RGBDigit();
        private:
            int _nDigits;
            DS3231 _clock;
            IRrecv* _ir;
    };

    #endif

This is RGBDigit.cpp:

<!-- language: c -->

    #include "RGBDigit.h"

    RGBDigit::RGBDigit(int nDigits)
        : Adafruit_NeoPixel(8 * nDigits, 12, NEO_GRB + NEO_KHZ800),
        _nDigits(nDigits)
    {
        _ir = new IRrecv(10);
        _ir->enableIRIn(); // Start the receiver
        Adafruit_NeoPixel::begin();
    }

    RGBDigit::~RGBDigit()
    {
        delete _ir;
    }

And this is my Arduino sketch:

<!-- language: c -->

    #include <Wire.h>
    #include <RGBDigit.h>

    RGBDigit display = RGBDigit(4);

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

    }

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

    }

I get al lot of "undefined reference" errors:

    RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::RGBDigit(int)':
    /home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `Adafruit_NeoPixel::Adafruit_NeoPixel(unsigned int, unsigned char, unsigned char)'
    /home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `DS3231::DS3231()'
    /home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:25: undefined reference to `IRrecv::IRrecv(int)'
    /home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:26: undefined reference to `IRrecv::enableIRIn()'
    /home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:27: undefined reference to `Adafruit_NeoPixel::begin()'
    RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::~RGBDigit()':
    /home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:30: undefined reference to `Adafruit_NeoPixel::~Adafruit_NeoPixel()'
    collect2: error: ld returned 1 exit status

But I don' t understand why. What am I doing wrong?

body:
    #include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
    #include "../IRremote/IRremote.h"
    #include "../DS3231/DS3231.h"

What you're doing there is telling the *compiler* where, relative to where it's performing the compiling (or one of its include directories), the header files you list are.

What you're *not* doing is telling the *IDE* where the CPP files are to compile and link with your sketch.

When including *anything* external to the sketch folder that is *more* than *just a header file* you *must* treat it as an Arduino library - that is, place it in one of the standard library folders and name it properly (libraries should be named `LibraryName/LibraryName.h`).

Then you include the libraries properly:

    #include <Adafruit_NeoPixel.h>
    #include <IRremote.h>
    #include <DS3231.h>

You must do that in *both* your sketch *and* your custom library.  That way the IDE knows where to look for the files to compile - the compiler doesn't understand the concept of an Arduino library (and thus the CPP files associated with a header file) - that is purely down to the IDE gathering the data by examining your sketch and locating the right files to then pass to the compiler.


message:
Pause code untill a button is pressed

I need some code to pause the Arduino code until a button is pressed. I have a long program and at point I need a condition that if a Button on pin A2 is pressed then go forward, otherwise wait.

I tried using `if` with a condition but it failed for my purpose. I think this is because when `if(...)` detects that the button is not pressed, it moves to next lines (as usual). But I have a long program and I want to wait forever until the button is pressed.

body:
The construct you are looking for is called `while`.

Instead of doing "If the button is pressed then continue" you need to do "while the button is not pressed do nothing".

Assuming you have an "active low" button (that is, a resistor pulling it up to +5V when not pressed, so `digitalRead(A2) == LOW` is "pressed"), you can do:

    while (digitalRead(A2) == HIGH) {
      // Do nothing
    }

So while it's not pressed (`digitalRead(A2) == HIGH`) don't do anything.  As soon as `digitalRead(A2)` returns LOW (so it is not `== HIGH` any more) the `while` loop will finish and your sketch can continue.

I write all about the `while` loop in an article [here](https://majenko.co.uk/blog/while-loop).


body:
Here are two ways you might have wired the button. If you wired it with a pullup, you will need to test for LOW (the button will ground its output when pressed). If pulldown, the button will raise its output when pressed and you would test for HIGH.

If you will be testing the button again within less than a second, don't forget to debounce it. Switches send a bunch (technical term :) of pulses for a significant fraction of a second during a make or bread. See Nick Gammon's ["Switches" page][1] for a thorough discussion.

[![Pullup vs. Pulldown Schematic][2]][2]

  [1]: http://www.gammon.com.au/switches
  [2]: https://i.stack.imgur.com/sVu2L.jpg


body:
 > I need a code to pause arduino code until a button is pressed.

I wrote a simple [function][1] to do this.

### Usage:

    buttonWait(<pin_number>);

### Code:

    /* the function */
    void buttonWait(int buttonPin){
      int buttonState = 0;
      while(1){
        buttonState = digitalRead(buttonPin);
        if (buttonState == HIGH) {
          return;
        }
      }
    }

    void loop() {
      buttonWait(2); // wait for button press on pin 2
      // do something
      // ...
    }

This code assumes that you have a pulldown resistor, but you can easily modify it to work with a pullup resistor instead, if you feel the need:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/DTfwv.png)

<!-- End schematic -->

  [1]: https://gist.github.com/rahuldottech/839cb13140f24debae8f72343115de4b

See example code [here](https://gist.github.com/rahuldottech/839cb13140f24debae8f72343115de4b)!


message:
Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)

I’m sorry if I sound ignorant and naive, but I’m brand new to Arduino;  very keen, but know very little.

I started with a Sainsmart Arduino Uno clone board.  I downloaded the software, which opened OK (or at least seemed to), but the Serial Monitor kept telling me that there was a communication error, and a yellow light kept flashing on the Sainsmart board.

I got hold of a genuine Arduino (from Jameco), uninstalled everything Arduino, and started again from scratch.

Now I get the message:

    Arduino: 1.6.5 (Mac OS X), Board: "Arduino/Genuino Uno"
    Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)
      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

And after enabling the verbose output, got:

    Arduino: 1.6.5 (Mac OS X), Board: "Arduino/Genuino Uno"
    Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)

Tried again, and:

    Arduino: 1.6.5 (Mac OS X), Board: "Arduino/Genuino Uno"
    Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)

I’m using a MacBook Pro, using Yosemite 10.10.5.

body:
You are not selecting the correct port to upload to - hence the strange message about the Bluetooth modem. Start by unplugging your Uno and running Arduino. Select Tools -> Port from the menu bar. You should see a list of options. Now plug in your Uno and do the same again. You should see an extra port listed now - this will be the Uno. Select it. You will need to check this every time you connect a board.

Also, before you click Upload, make sure you have Arduino Uno selected under Tools -> Board in the menu bar.


message:
AVRdude + Arduino leonardo: can't flash over bootloader, not in sync: resp=0x3f

I would like to program an arduino leonardo board with atmega32u4 on win8.1 x64.
I have the latest AVRdude.
I installed the necessary drivers, after reset it can be enter programming mode, and I can program with **arduino studio**.
But now, the avrude gives this:

        C:\>avrdude -carduino -P COM5 -n -p m32u4 -b19200 -v

    avrdude: Version 6.1-svn-20131205, compiled on Dec  5 2013 at 17:34:22
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "c:\GNU_GCC_ARM\bin\avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : arduino
             Overriding Baud Rate          : 19200
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x3f
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x3f

    avrdude done.  Thank you.
I tried also with 57600 baud.
Any idea? Thanks.

body:
You're specifying the wrong bootloader protocol via -carduino. The Arduino bootloader is for boards using the Diecimila bootloader. The Leonardo uses the "AVR109" bootloader - named after the [Atmel Application Note][1] which describes its protocol.

Try this command on for size:

    avrdude -cavr109 -P COM5 -n -p m32u4 -b57600 -v

Don't forget to press the reset button (or open and close COM5 at 1200 baud) first to run the bootloader.

[1]: http://www.atmel.com/Images/doc1644.pdf


message:
Arduino Serial Monitor

I am currently trying to see the result of a query to a thingspeak field.
This works great when I just use a empty sketch and type the commands manually, but using the following sketch I cannot see the value of +IDP,0,1:1
This means, at field 1, the value 1 is stored. If 0 was stored, it would be +IDP,0,1:0
How it is possible to "ask" if "+IDP,0,1:0" exists at the serial message from the ESP8266? Serial.find does not work....

Here my sketch:

    #include<stdlib.h>
    #include <SoftwareSerial.h>

    SoftwareSerial monitor(2,3); //rx tx
    #define SSID "WLAN-0E0265"
    #define PASS "2738564673200634"
    int ledPin = 13;
    String c;
    void setup() {
      Serial.begin(9600);
      monitor.begin(9600);
      monitor.println("AT");
      delay(1000);
      monitor.println("AT+CIPMUX=1");
      delay(1000);
      monitor.println("AT+CWJAP=\"WLAN-0E0265\",\"2738564673200634\"");
      delay(5000);
      if(monitor.find("OK"))
        Serial.println("JAP worked");

      monitor.println("AT+CIPSTART=0,\"TCP\",\"api.thingspeak.com\",80");
      delay(2000);
      if(monitor.find("OK"))
        Serial.println("CIPSTART worked");
      monitor.println("AT+CIPSEND=0,110");
      delay(2000);
      if(monitor.find(">"))
        Serial.println("CIPSEND worked");
      monitor.print("GET https://api.thingspeak.com/channels/54209/fields/1/last \r\n");
      delay(10000);
      monitor.println("GET https://api.thingspeak.com/channels/54209/fields/1/last");
      delay(2000);
      String readString;
      ledPin = 13;
      //++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //SEARCH FOR THE :0 or :1                           <-- Here is the problem, rest works fine
      if(Serial.find(":0")){
     //turn pin off
    }
      if(Serial.find(":1")){
     //turn pin on
    }

    }

    void loop(){

    }

body:
The problem is that you can't use serial's `find` function to look for one thing *or* another.  It is a greedy function and it will consume everything coming in to the serial port until it finds what it's looking for or until it times out.  That includes the `:1` if you are using `find` to look for the `:0` at the time.

Instead you either need to receive the whole string into memory and examine the string to see what it contains, or you need to manually process the data as it comes in character by character to decide what there is.


message:
avrdude: ser_open(): can't open device "\\.\COM3"?

My computer cannot detect my Arduino Uno anymore,

 - Reset button- > L led light blinks and it turns on forever
 - Arduino 1.6.5: Tools->Port (greyed out) I remembered that previously it wasn't like this
 - Unable to upload any sketch codes into the Uno anymore
 - The existing code uploaded onto the Uno is FastLED(FirstLight) and it will work on my LEDs when I plugged them in

I have tried to .... but none fix my issue

 - Restart my computer
 - Press the reset button on the Uno
 - Using the device mananger to change COM ports
 - Device manager -> Other devices -> (nothing about Arduino Uno is found here)
 - Plugged Uno into another computer but still doesn't work
 - Reinstalled IDE

Problem shown in sketch,
> avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the file specified.
>
>Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body:
I have experienced a similar issue after plugging in another Arduino device. I didn't set up my environment for a long time and thus forgot he iterates the COM-Index. Maybe this is too easy, but you didn't provide much information.

This solved my problem:
Open Arduino application > Tools > Port > Change to the target Port

If you are unsure which port to choose from: (on Windows)
Open Device Manager > Connections (COM & LPT) > Usb Serial Port (COM[x])
where "[x]" is the index you are looking for.


message:
Arduino microphone

I have an arduino schematic from here

http://www.arduino-hacks.com/arduino-vu-meter-lm386electret-microphone-condenser/

I have a problem, the output of the circuit (the pin which is going to connect to the analog pin of the Arduino), from what I have measured has 4.5 V (I think it is a bit high). If I print on the serial it gives me something like 827, 826. However when I clap my hands near the microphone or put music on, the data that I get doesn't change a lot (like 1 -2 units). Should I worry about the schematic or about my microphone?

EDIT:
  After I rebuilt the circuit and when playing a song at a medium volume, I get values like this: 419-670. I think it is working, though I would like more opinions about these values (the output voltage is now around 3.20 V).

body:
The schematic seems to have both inputs of the opamp at 0V (the one connected to the microphone would actually swing a small amount ±). The opamp also seems to be running open loop, with no feedback and would have a very high gain.

This is poor circuit design, ideally the inputs should be biassed at Vcc/2. At best the output would be severely distorted.

I suggest you search for a more suitable circuit.


message:
Drive 12V Piezo Buzzer (Arduino)

I want to drive this 12V piezo buzzer:
http://www.conrad.com/ce/en/product/130256/Kemo-L001-High-Freqeuncy-Piezo-Speaker-Component-12-24-V

This is the circuit I am using.

[![Circuit][1]][1]

The Arduino is powered by a 12V DC adapter trough the DC IN jack.

I have tested the following code:

<!-- language: c -->

    void setup() {
    }

    void loop() {
      int pinOut = 9;
      int freq = 10;
      int duration = 100;
      while(1)
      {
        for(int i=0; i<1000 ; i++)
        {
          tone(pinOut, freq*i, duration);
          delay(duration * 1);
          noTone(pinOut);
        }
      }
    }

When run I can hear the tones changing but is really really low. I have measured the voltage between buzzer pins and it is 12V (as expected) so the MOSFET seems to be properly working.

This piezo buzzer should be louder (I have tested it with this 12V tone generator http://www.kemo-electronic.de/en/Car/Modules/M048N-Ultrasonic-Generator.php )

I am making any mistake?
Thanks in advance!

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

body:
The usable frequency range of the speaker is 2500 - 45000 Hz. In your script, you sweep from 10Hz to 10kHz which is a bit low. Try to change the start frequency to a higher value:

    void setup() {
    }

    void loop() {
      int pinOut = 9;
      int freq = 2500;
      int duration = 100;
      while(1)
      {
        for(int i=0; i<1000 ; i++)
        {
          tone(pinOut, freq+(i*50));
          delay(duration);
          noTone(pinOut);
        }
      }
    }


body:
The piezo element acts like a capacitor, not like a more-or-less resistive element as in a conventional speaker. You need to discharge the capacitor during the 'off' time or you just get a click and little sound after that. That's why your resistor helps. Push-pull would be much better, and an H-bridge would give you much more output (maybe too much for the speaker).

Also the IRZ44 is not specified to be driven from 5V (it's specified at 10V Vgs) so you may not get much current. Further, if you're trying to get 10's of kHz, you won't be able to drive the MOSFET gate that fast with a 1K resistor, in fact the Arduino may not be able to source enough current and you may have to use a gate driver.

If you can measure the capacitance and provide the frequency of interest, more specific recommendations would be possible. At 2kHz about 3K would be okay with a 10nF element, but that resistance would decrease with increasing resistance and with increasing capacitance, and at some point the power dissipation in the resistor will become excessive.

Edit: You can do something like the below with a 10nF/20kHz requirement:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/PhsXe.png)

<!-- End schematic -->

You could even duplicate the above circuit and add an inverter in series with one of the halves and get 24Vpp across the piezo, but you might want to use somewhat beefier transistors (Zetex perhaps).


message:
Programatic FOTA (Firmware-Over-The-Air) upgrades with Uno R3

I have been searching for a way to upgrade the sketch on my Arduino Uno wirelessly (preferable WiFi, but not a must). Does the Uno support such function?
If not - are there any other boards that might support it?

Also, to further extend on the problem - I wouldn't want to upload a new sketch through the Arduino IDE but rather do it programmatically (trying to integrate it with a version management system of my own).

body:
There's two ways you can go about this - hardware and software.

To do it in software would mean writing a new bootloader that supported whatever wireless medium you chose.  The bootloader might end up quite large and thus restrict the size of sketch you are able to support.  It may also require advanced programming techniques in order to fit it into memory.  Not a task for a beginner.

Doing it in hardware is easier but more restrictive.  You need a wireless medium that can emulate a serial device *including the ability to perform a reset of the Arduino*.  There are bluetooth interfaces for the Arduino that can perform this kind of functionality, but I am not aware of anything WiFi or Ethernet that even remotely comes close.

There are Arduino boards available with this kind of bluetooth interface built in.

A possible third option is something in between - you have two Arduinos (or some other external MCU based system, like an ATTiny for instance), the "target" and the "programmer".  The "programmer" is what is connected to the wireless and accepts instructions and commands over the air.  It is then capable of putting the "target" into bootloader mode (reset it) and pass data through to its serial port for programming.  It does mean the "target" isn't directly connected to the wireless though, so it is up to the "programmer" to support whatever wireless functionality is needed and communicate properly with the "target" to get it to do everything it should.  There is no way to do FOTA to the "programmer" though, so you're back at square one if you want to reprogram that...


body:
There are plenty of examples of Arduinos being used to reprogram Arduinos:

* [Using an Arduino as an AVR ISP (In-System Programmer)](https://www.arduino.cc/en/Tutorial/ArduinoISP)
* [Standalone AVR ISP Programmer Shield Kit](http://www.adafruit.com/products/462)
* [Atmega chip stand-alone programmer to upload .hex files](http://www.gammon.com.au/uploader)
* [Atmega bootloader programmer](http://www.gammon.com.au/bootloader)

So the obvious choice here is to have **two** chips. One does the real work, the other one programs the first one, when required.

The "programmer" chip could be written to read from a disk file, accept data over Ethernet, WiFi or whatever. And it could be programmed to reprogram the target chip at a certain time of day, or on command.

In this system the "main" chip gets on with whatever-it-is it is doing, and the "programmer" chip just monitors its source of new code.

>  Does the Uno support such function? If not - are there any other boards that might support it?

I don't know of any boards that directly support that. These boards are generally built as educational tools, not as ready to deploy in the field as robust auto-upgrading devices. For one thing, keeping things cheap enough for students to purchase, perhaps one for each student in a classroom of 30, was one of the design criteria.


body:
You can wire an ESP32-based board or module to your Arduino, and use https://vcon.io for a remote OTA. vcon firmware can act as an AVR (and not just AVR) programmer, and reflash your Arduino remotely.

Also, as a side-effect, you'll get remote control capability for your Arduino. https://dash.vcon.io cloud service gives you device dashboard and an API for remote control and OTA.

Disclaimer: I do represent https://vcon.io product.


message:
Newbie Question with 4 pin button

I suspect this is a very Naive question.
But the answer will teach me a lot.

Why does [this circuit](https://www.arduino.cc/en/Tutorial/ButtonStateChange) work when I connect the Digital Input (Digial Pin 2) to Pin 4 of the push button. But does not when I connect the push button to Pin 3. I missing something about how power flows when the button is pushed.

Ray K

body:
Internally those little tactile switches look like this:

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

That means that the two pins on the same *long* side are connected together.  So you can use, when you hold the switch vertically as in the image on the page you link to the two left-hand pins are linked together, and the two right-hand pins are linked together.

So you can use either both the top pins, both the bottom pins, or the top left and bottom right or the top right and bottom left.

Using either both left hand pins or both right hand pins will be as if you were sat on the button and it was permanently pressed.

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


message:
Problem with reading multiple potentiometer values on Arduino Uno

I'm working on an Arduino sketch that will read in values from two potentiometers. The code for this is below:

    int lastPotentiometerOneValue = 0;
    int lastPotentiometerTwoValue = 0;

    void setup() {
      // initialize serial communication at 57600 bits per second:
      Serial.begin(57600);
    }

    void loop() {
      delay(10);
      readAndSendPotentiometerDataIfChanged();
    }

    void readAndSendPotentiometerDataIfChanged(void) {

      //Potentiometer One
      int newPotentiometerOneValue = analogRead(A0) / 10.2;
      if (newPotentiometerOneValue == lastPotentiometerOneValue) return;

      Serial.print("!pos1");
      Serial.print(newPotentiometerOneValue);
      Serial.print(";");
      lastPotentiometerOneValue = newPotentiometerOneValue;

      //Potentiometer Two
      int newPotentiometerTwoValue = analogRead(A1) / 10;
      if (newPotentiometerTwoValue == lastPotentiometerTwoValue) return;

      Serial.print("!pos2");
      Serial.print(newPotentiometerTwoValue);
      Serial.print(";");
      lastPotentiometerTwoValue = newPotentiometerTwoValue;
    }

The schematic for my circuit is below (I've left out the code for reading the state of the push-button in my listing above, as that's in a separate method from the method that reads in the potentiometer data):

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

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

However, there seems to be a rather subtle error I'm experiencing. If I turn Potentiometer One, it will display the correct output in the serial monitor. If I turn Potentiometer Two, no value will be displayed. *However*, if I remove Potentiometer Two from the circuit board and turn Potentiometer One, then the serial monitor will display the Potentiometer Two as having the same data as Potentiometer Two.

I'm sure the problem is with my circuit, but I'm not quite sure what I'm doing wrong. Does anyone have some insight? Thank you!

body:
One problem is that if the value for pot1 has not changed, the value for pot2 will never be sent, even if it has changed, due to the early return when checking the value of pot1. You could fix this by changing to:

    void readAndSendPotentiometerDataIfChanged(void) {

      //Potentiometer One
      int newPotentiometerOneValue = analogRead(A0) / 10.2;
      if (newPotentiometerOneValue != lastPotentiometerOneValue) {
          Serial.print("!pos1");
          Serial.print(newPotentiometerOneValue);
          Serial.print(";");
          lastPotentiometerOneValue = newPotentiometerOneValue;
      }

      //Potentiometer Two
      int newPotentiometerTwoValue = analogRead(A1) / 10.2;
      if (newPotentiometerTwoValue != lastPotentiometerTwoValue) {
          Serial.print("!pos2");
          Serial.print(newPotentiometerTwoValue);
          Serial.print(";");
          lastPotentiometerTwoValue = newPotentiometerTwoValue;
      }
    }


message:
Arduino GPSlim 236

I'm looking to connect an old GPSlim236 device to my Arduino via serial comms. I have seen references online on how to connect the device but in the data sheet it says TTL level between 3V - 5V.  Does this mean that the GPS can automatically switch between logic level 5V -3V when needed?

Here is the link to data sheet for the GPS - http://www.holux.com/JCore/UploadFile/3205400.pdf

body:
The datasheet says:

>  Power Supply
>
> External Voltage: 5VDC +/- 10%

So I take that to mean you supply 5V to it.

---

Later on it says:

> Transmit Data. From organizer to peripheral. (Voltage Level is 3.3V ~ 5.0V)

I presume that means that it will supply (or accept) 3.3V to 5V as a high level, and less than 3.3V as a low level. This is perfectly normal for an Arduino.

---

> Does this mean that the GPS can automatically switch between logic level 5v -3v when needed ?

No I would not read it like that. If you read the datasheet for the Arduino processor chips it states things like an output high is a range of voltages, similar to what this device is saying. A "high" is not necessarily 5V exactly, it might be 4.7V, for example. However the Arduino input pins are similarly designed to take a range of voltages.

---

> My confusion here is that the datasheet says 3-5v but what if I connect the device to a raspberry pi which (I think) only accepts 3v, would it still work?

Well, the datasheet says 5V +/- 10% for charging the internal battery. I'm not sure what your situation is if you are trying to run it from a Pi.


message:
How to compile, upload and monitor via the Linux command line?

Interfacing an Arduino Uno (uploading etc.) with the Arduino IDE (using the Fedora package) works fine under Fedora 21.

But I rather want to use vim + make + vim-quickfix-mode etc.

How can I do that?

Preferably via the tools available from the Fedora repositories.

I assume that the IDE calls externals command line utilities for the uploading etc.

The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. `screen`) to `/dev/ttyACM0`, right?

Perhaps there is a good example project one can look at the makefile?

body:
What you need is a Makefile.  There are a few Makefile projects around for Arduino.  Googling for "Arduino Makefile" returns many results including what looks like a good one on Github: https://github.com/sudar/Arduino-Makefile

Compiling from the command line isn't trivial due to the way the Arduino IDE handles libraries.

> The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. screen) to /dev/ttyACM0, right?

For the serial monitor I would recommend minicom. It is a fully functional terminal emulator (vt102) on the command line.

    minicom -D /dev/ttyACM0 -b 115200

... for example.


body:
I would suggest Googling for Makefile projects. I did one a while back for the Blink program, by basically seeing what got generated by the IDE and replicating that in a more general way.

    #
    # Simple Arduino Makefile
    #
    # Author: Nick Gammon
    # Date: 18th March 2015

    # where you installed the Arduino app
    ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

    # various programs
    CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
    CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
    AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
    OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

    MAIN_SKETCH = Blink.cpp

    # compile flags for g++ and gcc

    # may need to change these
    F_CPU = 16000000
    MCU = atmega328p

    # compile flags
    GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
    CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
    CC_FLAGS  = $(GENERAL_FLAGS)

    # location of include files
    INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

    # library sources
    LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

    build:

     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
     rm core.a
     $(AR) rcs core.a malloc.c.o
     $(AR) rcs core.a realloc.c.o
     $(AR) rcs core.a WInterrupts.c.o
     $(AR) rcs core.a wiring.c.o
     $(AR) rcs core.a wiring_analog.c.o
     $(AR) rcs core.a wiring_digital.c.o
     $(AR) rcs core.a wiring_pulse.c.o
     $(AR) rcs core.a wiring_shift.c.o
     $(AR) rcs core.a CDC.cpp.o
     $(AR) rcs core.a HardwareSerial.cpp.o
     $(AR) rcs core.a HID.cpp.o
     $(AR) rcs core.a IPAddress.cpp.o
     $(AR) rcs core.a main.cpp.o
     $(AR) rcs core.a new.cpp.o
     $(AR) rcs core.a Print.cpp.o
     $(AR) rcs core.a Stream.cpp.o
     $(AR) rcs core.a Tone.cpp.o
     $(AR) rcs core.a USBCore.cpp.o
     $(AR) rcs core.a WMath.cpp.o
     $(AR) rcs core.a WString.cpp.o
     $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
     $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
     $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

You would need to change `ARDUINO_DIR` at least, to reflect where you installed the IDE. If you use other things like the Wire library you would need to expand it somewhat to compile additional libraries. Again, you can use what the IDE generates itself to guide your changes.

The lines with the leading spaces above would need the **tab** character instead of spaces, as is normal for a Makefile.


body:
I use the [command-line interface to the `arduino` command](https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc).

I run it like this:

    arduino --upload sketch/sketch.ino --port /dev/ttyUSB*

[There is a page](http://playground.arduino.cc/Learning/CommandLine) which describes other command-line tools, like `inotool`. That page also has an example `Makefile`. These alternatives seem enticing, but apparently, as of this writing, none of them work. I'm assuming this is due to some recent changes in Arduino IDE distribution files which they depend on.

Running `arduino` as above is a bit slow, because it has to load Java I guess, but at least it works. There is also an [`arduino-builder`](https://github.com/arduino/arduino-builder) command that comes with the Arduino IDE distribution. As of this writing, it was not sufficiently well-documented for me to be able to figure out how to use it. For instance there are no example command lines in the README or in any of the tutorials I came across, and I couldn't figure out how to use it to upload code to the board. However, presumably it is able to give us a faster compile than `arduino`. The README also mentions being able to reuse object files from a previous compile, so there is some make-like functionality.

----

To view serial output [I use something like](https://arduino.stackexchange.com/questions/24741/how-do-i-read-from-dev-ttyacm0-in-linux-without-a-terminal-emulator)

    stty -F /dev/ttyUSB* 1000000 raw -clocal -echo
    cat /dev/ttyUSB*

The number 1000000 should match the number you pass to `Serial.begin()` in your board code. You can also use `screen` if you have a board program which is appropriately interactive, or you can use whatever utility to write directly to the device. By the way, my Due shows up as `/dev/ttyACM0` (rather than `/dev/ttyUSB0` for the Uno).


body:
If you want a fully compatible solution for your arduino project (yes, you can share your project with other people that use just plain Arduino IDE) you need to check [amake][1] a tool to simplify the cli of the arduino, I use it with Geany but others are using it with vi, Atom, etc.

It's inspired and the now dead Ino and Arturo projects; please take 5 minutes to test it and please give feedback.

Example use:

    cd ~/Arduino/Blink/
    [move to your arduino project folder]

    amake -v uno Blink.ino
    [to compile/verify your code]

    amake -u uno Blink.ino /dev/ttyUSB0
    [to upload your code to an arduino connected via USB]

It has some smart glue in there, it can remember the board and file, and even autodetect the usb of the board; so after a successfull "amake -v" command you can do this on the command line and it will work.

    amake -v
    [to compile/verify your code]

    amake -u
    [to upload your code to an arduino connected via USB]

If you use some IDE macros you can craft the compile and upload commands easily, for example using Geany IDE it will became:

 - **Compile/Verify:** cd %d; amake -v uno %f
 - **Upload:** cd %d; amake -u uno %f

You can get more help running just "amake" or "amake -h" once installed.

Also, it can support **EVERY** board/lib/programmer you have installed/configured in your Arduino IDE, yes, modern board like the Adafuit Trinket M0 / Arduino M0 etc...

Just fire your Arduino IDE, go to the board manager, install support and that's all, jut follow some simple instructions and your are set.

The board you have is not supported? not a problem, detect the fqbn (read the README.md file) and pass it along as the board name.

I'm looking for testers to grow up the number or board aliases and auto detection of the proper USB signatures.

Remember this is a private grown tool, now shared with the public, you know, just a programmer scratching it's itch...

Cheers.

  [1]: https://github.com/pavelmc/amake


body:
# Official CLI tool

The arduino team is developing a **cli** client
https://github.com/arduino/arduino-cli

**Announcement**: https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/

You can do almost everything with this, from downloading boards and libraries, to compile and upload scripts. What's missing is the monitoring part (you can use [Metamorphic's method][1] using `stty` `cat`, It works!)

The commands are very similar to [Metamorphic's answer][1] since this tool is branching out of that one

Instructions in the [Github repo][2] and the man page:

```bash
    $ arduino-cli Arduino Command Line Interface (arduino-cli).

    Usage:   arduino-cli [command]

    Examples: arduino <command> [flags...]

    Available Commands:
      board         Arduino board commands.
      compile       Compiles Arduino sketches.
      config        Arduino Configuration Commands.
      core          Arduino Core operations.
      help          Help about any command
      lib           Arduino commands about libraries.
      sketch        Arduino CLI Sketch Commands.
      upload        Upload Arduino sketches.
      version       Shows version number of Arduino CLI.
```

  [1]: https://arduino.stackexchange.com/a/24802/48663
  [2]: https://github.com/arduino/Arduino-cli


body:
A great way to compile for and flash an Arduino device from the command line and integrate with Vim is to use [PlatformIO Core (CLI)][1].

Since it's written in Python it's easy to install even when it's not packaged for your Linux distribution. PlatformIO supports [many microcontroller devices][4], not just Arduino ones. Thus, you don't have to switch your development environment when you target another platform. PlatformIO takes care of downloading the right toolchain (compiler etc.) for your target.

## Example

Getting started with PlatformIO and an Arduino Pro Mini 3.3v clone on Fedora 35:

```
mkdir -p ~/local
cd ~/local
python -m venv platformio
source platformio/bin/activate
pip install platformio
```

This installs PlatformIO (CLI) in a virtual environment, i.e. its main command is then available from `~/local/platformio/bin/pio` and `pio` is found in your `PATH` when the virtual environment is activated.

Next, we need to find the right board ID for setting up a new project:

```
pio boards arduino | less
```

That means search for `Pro.*Mini` in the listing. There are several versions of the Pro Mini, in our example the `pro8MHzatmega328` (3.3 V, 8 MHz, ATmega328, 30 kb flash, 2 kB RAM) is the right one as can be validated by looking at the board markings as well as its voltage regulator, and CPU markings.

To set up a new project

```
mkdir ~/project/some_new_project
cd ~/project/some_new_project
pio project init --board pro8MHzatmega328 --ide vim
```

Which prints:

```
The current working directory /home/juser/project/arduino/pro-mini will be used for the project.

The next files/directories have been created in /home/juser/arduino/pro-mini
include - Put project header files here
lib - Put here project specific (private) libraries
src - Put project source files here
platformio.ini - Project Configuration File
Platform Manager: Installing atmelavr
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
Platform Manager: atmelavr @ 3.4.0 has been installed!
Tool Manager: Installing platformio/toolchain-atmelavr @ ~1.70300.0
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
Tool Manager: toolchain-atmelavr @ 1.70300.191015 has been installed!
The platform 'atmelavr' has been successfully installed!
The rest of the packages will be installed later depending on your build environment.

Project has been successfully initialized including configuration files for `vim` IDE.
```

For a first test one can copy a simple blink-led example using the usual `setup()`/`loop()` functions. It's possible to re-use an existing 'sketch' from the Arduino IDE, one just has to add `#include <Arduino.h>` at the top and place it under `src/some-name.cc` or `src/some-name.cpp`.

To compile everything:

```
pio run
```

Which prints:

```
Processing pro8MHzatmega328 (platform: atmelavr; board: pro8MHzatmega328; framework: arduino)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/pro8MHzatmega328.html
PLATFORM: Atmel AVR (3.4.0) > Arduino Pro or Pro Mini ATmega328 (3.3V, 8 MHz)
HARDWARE: ATMEGA328P 8MHz, 2KB RAM, 30KB Flash
DEBUG: Current (avr-stub) On-board (avr-stub, simavr)
PACKAGES:
 - framework-arduino-avr 5.1.0
 - toolchain-atmelavr 1.70300.191015 (7.3.0)
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 5 compatible libraries
Scanning dependencies...
No dependencies
Building in release mode
Compiling .pio/build/pro8MHzatmega328/src/sos-switch.cc.o
Linking .pio/build/pro8MHzatmega328/firmware.elf
Checking size .pio/build/pro8MHzatmega328/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.4% (used 9 bytes from 2048 bytes)
Flash: [          ]   3.8% (used 1170 bytes from 30720 bytes)
========================= [SUCCESS] Took 0.51 seconds =========================
```

So for this example I created `src/sos-switch.cc` which is compiled to `.pio/build/.../sos-switch.cc.o`.

To upload (flash) the device:

```
pio run --target upload
```

As always, a common pitfall are the permissions of the USB device. For example, on Fedora, my USB2TTL serial device registers as `/dev/ttyUSB0` with read-write permissions for just `root:dialout`. Thus, you have to add your user to the `dialout` group or adjust the permissions by other means.

## Vim Quickfix Mode

For integrating with Vim's quickfix mode a simple makefile is sufficient, e.g.:

```

.PHONY: all
all: build

.PHONY: build
build:
 pio run

.PHONY: upload
upload:
 pio run --target upload
```

Thus, everything is built when `:make` is invoked in Vim, and there one can navigate the quickfix mode as usual.

## Serial Monitoring

An easy way to monitor the serial interface is to use [picocom][2], e.g.:

```
picocom --baud 9600 --echo --imap lfcrlf --noreset /dev/ttyUSB0
```

where:

- `--imap lfcrlf` maps newline to carriage return + newline such that we can just write `Serial.print("multi\nlines\n')` instead of `Serial.print("multi\r\nlines\r\n")` in our program
- `--noreset` tells picocom to **not** clear DTR - without it, when DTR is connected, the Anrdoid device is reset

Of course, one has to terminate picocom when uploading.

---

Alternatively, one can use the PlatformIO monitor command:

```
pio device monitor
```

In contrast to picocom, it doesn't require explicit mapping or DTR handling. However, as with picocom, it must be terminated when uploading/flashing. That means PlatformIO doesn't automatically suspends monitoring when `pio run --target upload` is invoked.

## Closing Remarks

- PlatformIO is [currently packaged][3] for Fedora and thus might be directly available in Fedora 36 or so
- the classic Arduino IDE was packaged for Fedora, but isn't available anymore in Fedora 35 because of the big Java package exodus
- there is also a PlatoformIO plugin for VSCode which seems to be quite popular

[1]: https://docs.platformio.org/en/latest/core/index.html
[2]: https://github.com/npat-efault/picocom
[3]: https://bugzilla.redhat.com/show_bug.cgi?id=2021751
[4]: https://platformio.org/platforms


message:
Loop though array values at end of each for loop cycle

I'm using the [NeoPixel][1] Ring from Adafruit and trying to pulse though and array of colors. However, I'm having trouble with having the loop go to the next color at the end of each pulse (end of loop). Here is what I currently have:

    uint32_t color[] = {red, green, blue,yellow,teal,magenta};

    void pulseUp(uint8_t speed){
      int fadeAmount = 10; //how much to increase each loop
      int n = 0; //get first color
      for(int b = 100; b >= 10; b = b - fadeAmount) { //start pulse for loop
        for (int i = 0; i < strip.numPixels(); i++) { //select all pixels
          strip.setPixelColor(i, color[n]); //set color from our array
          }
        strip.setBrightness(b); //set brightness based on b
        strip.show(); // send the changes to the strip
        delay(speed); //wait before running again
        //if at the end of the loop (brightness is 10) change color
        if (b == 10){
          if( n > 6){ //if we are at last color in our loop start over
            n = 0;
          }
          else{
            n++; //auto increment color value
          }
        }
      }
    }

I'm sure the problem is with the if statements but not sure how to fix it.

  [1]: https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.h

body:
<!-- language-all: lang-C++ -->

I can't quite make out what your `if` test is supposed to be doing, but don't you want a loop within a loop? Like this?

    uint32_t color[] = {red, green, blue,yellow,teal,magenta};

    void pulseUp(uint8_t speed)
      {
      const int fadeAmount = 10; //how much to increase each loop
      for (int currentColor = 0; currentColor < 6; currentColor++)
        {
        for (int i = 0; i < strip.numPixels(); i++)
          { //select all pixels
          strip.setPixelColor(i, color[currentColor]); //set color from our array
          }
        for(int brightness = 100; brightness >= 10; brightness -= fadeAmount)
          { //start pulse for loop
          strip.setBrightness(brightness); //set brightness based on brightness
          strip.show(); // send the changes to the strip
          delay(speed); //wait before running again
          }  // end of brightness loop
        }  // end of colour loop
      }  // end of pulseUp


message:
Arduino programmers for hire?

How do I best connect with Arduino programmers who are willing to design small projects for some extra cash?

body: The Arduino Forum has a [Gigs and Collaborations](https://forum.arduino.cc/index.php?board=26.0) section where such questions are welcome.


message:
Arduino Uno and Agilent ADNS-3080 not reading from SPI

I am trying to interface with a mouse sensor and am not able to get data back.
[datasheet link][1]
  [1]: http://prototypejax.com/datasheets/Agilent ADNS-3080.pdf
I have it still soldered to the original PCB but have cut the traces to pins 1-4,6,7 (NCS [SS], MISO, SCLK, MOSI, RESET, NPD [power down {set to 3.3v}])

PLEASE LET ME KNOW IF ANYTHING SEEMS WRONG HERE.

According to the Datasheet, by default the sensor is setup with the pull-up resistors enabled [pg. 29] which enables the open-drain, allowing me to directly connect NCS,MISO,SCLK,MOSI directly to the 5v microcontroller [pg. 15]. This also requires the SPI speed set to 500khz [pg. 10]. RESET is in a (10k)(10k+10k) resistor bridge.

SPI should be set to Mode3 as SCLK is normally high and data should be captured on the rising edge of the clock pulse [pg. 16]

Here is my code:

    #include <SPI.h>
    const int MOUSEVERSION = 0x00; //mouse version
    const int CSmouse = 10;
    const int mouseReset = 2;
    char val;

    void setup() {
      Serial.begin(9600);
      SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE3));
      pinMode(CSmouse, OUTPUT);
      pinMode(mouseReset, OUTPUT);
      digitalWrite(CSmouse, HIGH);
      //pull reset pin high for a half second to make sure mouse is ready to go after powering on [pg. 22]
      digitalWrite(mouseReset, HIGH);
      Serial.println("setup");
      delay(500); //half a second
      digitalWrite(mouseReset, LOW);
      Serial.println("end setup");
    }

    void loop() {
      Serial.println("Start loop");
      digitalWrite(CSmouse, LOW); //CS enable
      SPI.transfer(MOUSEVERSION); //0x00 = read register Product_ID, should reply 0x17
      delayMicroseconds(75);
      Serial.println(SPI.transfer(0)); //actually just gives 0
      delay(500);
    }

body:
You have `SPI.beginTransaction` but no `SPI.begin()`.

`SPI.begin()` is needed to initialize the SPI hardware.

More details about SPI at [SPI - Serial Peripheral Interface - for Arduino](http://www.gammon.com.au/spi).