body:
I'm working on using a GUI in Processing to control some [LED rope from Adafruit][1], and using this [multiplexer][2].

I've gotten the following Arduino code working the way I want to cycle through the various strands of LED rope and turn them on:

    #include <SoftwareSerial.h>

    //Mux1 control pins
    int s0 = 8;
    int s1 = 9;
    int s2 = 10;
    int s3 = 11;

    //Mux2 control pins
    int s4 = 12;
    int s5 = 13;
    int s6 = 14;
    int s7 = 15;

    //Mux in "SIG" pin
    int SIG_pin = 3;

    //Voltage vlaue to write to the LEDs
    int testValue = 255;

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

      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);
      pinMode(s4, OUTPUT);
      pinMode(s5, OUTPUT);
      pinMode(s6, OUTPUT);
      pinMode(s7, OUTPUT);
      pinMode(SIG_pin, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
      digitalWrite(s4, LOW);
      digitalWrite(s5, LOW);
      digitalWrite(s6, LOW);
      digitalWrite(s7, LOW);
    }

    void loop(){

      for(int i = 0; i <= 19 ; i ++){
        Serial.println(i);
        testValue = 255;
        writeMux(i);
        delay(500);
    //    testValue = 0;
    //    writeMux(i);

      }

    }

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

      int muxChannel[20][8]={
        //Mux 1
        {0,0,0,0,0,0,0,0}, //channel 0
        {1,0,0,0,0,0,0,0}, //channel 1
        {0,1,0,0,0,0,0,0}, //channel 2
        {1,1,0,0,0,0,0,0}, //channel 3
        {0,0,1,0,0,0,0,0}, //channel 4
        {1,0,1,0,0,0,0,0}, //channel 5
        {0,1,1,0,0,0,0,0}, //channel 6
        {1,1,1,0,0,0,0,0}, //channel 7
        {0,0,0,1,0,0,0,0}, //channel 8
        {1,0,0,1,0,0,0,0}, //channel 9

        //Max 2
        {1,1,1,1,0,0,0,0}, //channel 0
        {1,1,1,1,1,0,0,0}, //channel 1
        {1,1,1,1,0,1,0,0}, //channel 2
        {1,1,1,1,1,1,0,0}, //channel 3
        {1,1,1,1,0,0,1,0}, //channel 4
        {1,1,1,1,1,0,1,0}, //channel 5
        {1,1,1,1,0,1,1,0}, //channel 6
        {1,1,1,1,1,1,1,0}, //channel 7
        {1,1,1,1,0,0,0,1}, //channel 8
        {1,1,1,1,1,0,0,1}, //channel 9
      };

      //loop through the 4 sig
      for(int i = 0; i < 8; i ++){
        digitalWrite(controlPin[i], muxChannel[channel][i]);
    //    Serial.println("CHANNEL IS ");
    //    Serial.println(muxChannel[channel][i]);

    //    Serial.println("Control pin IS ");
    //    Serial.println(controlPin[i]);
      }

      //write the value at the SIG pin
      analogWrite(SIG_pin, testValue);

    //    Serial.println("Test value IS ");
    //    Serial.println(testValue);

      //return the value
      return 0;
    }

I'm working on converting this Arduino code to a Processing sketch so I can control the lights with a GUI. I've run the Standard Firmata sketch on my Uno before running my Processing sketch. However, nothing seems to happen...I know that my circuit is working (since it worked for the Arduino sketch), and most of my Processing code should be correct. Logging shows the sketch is trying to write the values I want. Anyone have any ideas? Below is the relevant part of the Processing sketch:

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

    int [] muxChannel;

    //Mux1 control pins
    int s0 = 8;
    int s1 = 9;
    int s2 = 10;
    int s3 = 11;

    //Mux2 control pins
    int s4 = 12;
    int s5 = 13;
    int s6 = 14;
    int s7 = 15;

    //Mux in "SIG" pin
    int SIG_pin = 3;

    //Voltage vlaue to write to the LEDs
    int testValue = 255;

    void setup() {
      size(700,400);
      noStroke();
      cp5 = new ControlP5(this);
      println(Arduino.list());

      //// Set up Arduino and pin output modes
      arduino = new Arduino(this, Arduino.list()[1], 96000);

      arduino.pinMode(s0, Arduino.OUTPUT);
      arduino.pinMode(s1, Arduino.OUTPUT);
      arduino.pinMode(s2, Arduino.OUTPUT);
      arduino.pinMode(s3, Arduino.OUTPUT);
      arduino.pinMode(s4, Arduino.OUTPUT);
      arduino.pinMode(s5, Arduino.OUTPUT);
      arduino.pinMode(s6, Arduino.OUTPUT);
      arduino.pinMode(s7, Arduino.OUTPUT);
      arduino.pinMode(SIG_pin, Arduino.OUTPUT);

      arduino.digitalWrite(s0, Arduino.LOW);
      arduino.digitalWrite(s1, Arduino.LOW);
      arduino.digitalWrite(s2, Arduino.LOW);
      arduino.digitalWrite(s3, Arduino.LOW);
      arduino.digitalWrite(s4, Arduino.LOW);
      arduino.digitalWrite(s5, Arduino.LOW);
      arduino.digitalWrite(s6, Arduino.LOW);
      arduino.digitalWrite(s7, Arduino.LOW);
    }

    void draw() {
      background(bgColor);

        for(int i = 0; i <= 19 ; i ++){
        testValue = 255;
        writeMux(i);
        delay(500);
      }
    }

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3};

      final int[][] muxChannels = {
        //Mux 1
        {0,0,0,0,0,0,0,0}, //channel 0
        {1,0,0,0,0,0,0,0}, //channel 1
        {0,1,0,0,0,0,0,0}, //channel 2
        {1,1,0,0,0,0,0,0}, //channel 3
        {0,0,1,0,0,0,0,0}, //channel 4
        {1,0,1,0,0,0,0,0}, //channel 5
        {0,1,1,0,0,0,0,0}, //channel 6
        {1,1,1,0,0,0,0,0}, //channel 7
        {0,0,0,1,0,0,0,0}, //channel 8
        {1,0,0,1,0,0,0,0}, //channel 9

        //Max 2
        {1,1,1,1,0,0,0,0}, //channel 0
        {1,1,1,1,1,0,0,0}, //channel 1
        {1,1,1,1,0,1,0,0}, //channel 2
        {1,1,1,1,1,1,0,0}, //channel 3
        {1,1,1,1,0,0,1,0}, //channel 4
        {1,1,1,1,1,0,1,0}, //channel 5
        {1,1,1,1,0,1,1,0}, //channel 6
        {1,1,1,1,1,1,1,0}, //channel 7
        {1,1,1,1,0,0,0,1}, //channel 8
        {1,1,1,1,1,0,0,1}, //channel 9
        };

      //loop through the 4 sig
      for(int i = 0; i < 4; i ++){
        arduino.digitalWrite(controlPin[i], muxChannels[channel][i]);
      }

      //write the value at the SIG pin
      arduino.analogWrite(SIG_pin, testValue);

      int val = 0;
      return val;
    }

  [1]: https://www.adafruit.com/products/2440
  [2]: http://bildr.org/2011/02/cd74hc4067-arduino/

EDIT: I put the project and a little explainer on GitHub to show what this type of project can or can't be useful for here: https://github.com/narner/Analog-LED-Multiplexing-Example

title: Interface with mux-controlled LED rope

Answers: 2

body:
You're using a 16-channel analog multiplexer to talk to your devices (the LED ropes) via a single pin on your Arduino. "Multiplexer" is just a fancy name for a switch; "analog" means that it's switching analog connections, basically, wires that can have any voltage on them, as opposed to digital connections that carry only logic high (usually +5 volts) or low (0 volt) signals.

The first place to start is the datasheet. From the [product link], we can see that the chip we're using is a CD74HC4067. Their datasheet links don't work, but searching in [Octopart] for just "74HC4067" eventally led me to an actual [datasheet]. These datasheets are the key source for information on the parts you're using and are always worth reading through. Even if you don't understand everything in them, they'll usually have the information you need, and reading them gets easier with practice.

Section 5 has a functional diagram (Fig. 1) which shows the important connections.

* Z is what you'll hook up to an I/O pin on your Arduino. When the
  chip is enabled, Z will be connected to one of the Y connections.
* Y0 through Y15 are what you'll hook up to your individual devices;
  one (and only one) of these at a time will be connected to Z,
  connecting the device to your Arduino I/O pin.
  (The other Y connections will be in a [high impedance] state.)
* Ē is the "enable" signal, the bar over top indicating that it's
  "active low." That is to say, when you ground (0 V) Ē the mux will
  be active and the selected Y will be connected to Z. When you hold Ē
  high (5 V) the mux will be inactive and all the Ys and Z will be
  disconnected (high impedance again).
* S0 through S3 are the select inputs to the mux; they determine which
  Y is connected to Z (when the device is active) in a way we'll show
  below.

Depending on the project, you may not want to switch the connection between the Z and Y pins (by changing S0-S3) while the devices connected to the Ys are active so that you don't accidentally get a a little bit of signal meant for one device going to another. The steps to do this would be as follows:

1. You start by having Z connected to, say, Y0, with the signal you
   want to send to Y0 going through Z.
2. Disable the device by bringing Ē high. Now Y0 (and all other Ys)
   are disconnected.
3. Change the value on S0-S3 to select, e.g., Y1.
4. Change the signal you're sending to Z to the correct signal for Y1.
5. Bring Ē low to enable the device and now Z will be connected to Y1.

In your project you likely don't need to worry about being this careful with your switching so long as you change S0-S3 and Z as closely together as possible, so I'm going to simplify the code I show here by leaving out the enabling and disabling step; you can just wire Ē to ground for the moment.

The key to the switch is what you send on S0-S3 to select which Y is connected to Z. This input is just a binary number, which you'll need to understand to use it effectively. Following is a short summary, but if you don't understand it completely (or the C code later on), there are plenty of tutorials on the web that can give you further help.

Counting in binary is just like counting in tens except you have only the numbers 0 and 1. So instead of counting 0, 1, 2, ..., 9, 10, 11 you count 0, 1, 10, 11, 100, 101, ... (which represent the numbers 0, 1, 2, 3, 4, 5, ... in decimal). The S0 input on the mux is the least signifcant bit (the one furthest right), the S1 in put the second least significant bit (second from the right) and so on.

So you need to hook up four digital ouput pins from your Arduino to the S0 through S3 inputs on the mux and then manipulate those pins to send the appropriate number to the mux to select your chosen Y that you want to connect to X.

The following program, which counts sequentially from 0000 (0) through 1111 (15) on the four output pins; shows you how to do this. It would be a good idea to build up a small circuit on a breadboard with four LEDs (remember to use a 330 Ω or so resistor in series with the LED) that you can hook to your four pins so you can see visually what your program is doing as you experiment.

We start by declaring some constants for the pins:

    // Multiplexer control pins are assumed to be sequentially
    // assigned from `mux_base` onward.
    //
    const int mux_base = 8;
    const int mux_len = 4;                  // 2^4 values, 0 through 15
    const int mux_max = (1 << mux_len) - 1;

`mux_base` is the first pin of the four sequental pins you'll hook up to the S0-S3 (or the LEDs); I use pin 8 here but you can use pretty much any pin you like. `mux_len` is the number of bits in the mux selector input; S0, S1, S2, S3 is 4 bits, so this determines that I'm using pins 8, 9, 10 and 11 on the Arduino to control the mux.

`mux_max` is purely a calculation (from the previous two constants) of the highest value you can select on the mux; in this case it's 15. The details of how I caculate it are a bit beyond the scope of this answer, but it's worth working out yourself how that C code works from what you learn later in the code and can find out elsewhere on the web.

We need, as usual, to set up our chosen pins as digital outputs; `setup_mux()` does just that:

    void setup_mux() {
        for (int pin = mux_base; pin < mux_base+mux_len; pin++) {
            pinMode(pin, OUTPUT);
            digitalWrite(pin, LOW);
        }
    }

We start with the first selector pin and loop through to the last one, for each one setting it to output mode and setting the current value to `LOW` so that we have known starting conditions.

For the selection of the Y to connect to Z on the multiplexer, it's convenient to have a function that takes an `int` indicating that Y and sets our selector pins to the correct values for this. Thus, `set_mux(value)` below. This is probably the most complex part of this answer, and bears detailed study.

    void set_mux(int value) {
        for (int offset = 0; offset < mux_len; offset++) {
            int bit = (value >> offset) & 1;
            digitalWrite(mux_base + offset, bit ? HIGH : LOW);
        }
    }

1. The first line loops through our `mux_len` (4 from above) selector
   pins; each of these will have to be set to the correct `HIGH` or
   `LOW` value for the desired Y selection.
2. The second line determines the binary bit from `value` for the
   particular selector pin we're setting in this iteration of the
   loop. We do this by doing a binary shift of the value to the right,
   and then clearing all bits except the lowest one, leaving us with a
   final value for `bit` of 1 or 0. For example, if we pass 14 to the
   function, which is 1110 in binary, when the offset is 2 in the loop
   we'll use the `>>` operator to shift that right two bits, through 0111
   to 0011. (With each shift the right bit drops off and a 0 is added
   at the left.) Doing a logcal AND (the `&` operator) of 0011
   with 0001 keeps only the bits that are set in both, leaving us
   with 0001. (Only the far right bit is set in both.)
3. We then need to set the output pin to HIGH if `bit` is 1 or LOW if
   `bit` is 0; the ternary operator (_condition_ `?` _when-true_ `:`
   _when-false_) provides a concise way of doing this.

That's our core "library" code, if you will. In this simple example the only setup we need to do is to call `setup_mux()`:

    void setup() {
        setup_mux();
    }

Our main program, for demonstration, will count upwards in binary on the selector outputs, delaying a half second between each count so you can see your LEDs blink:

    int counter = 0;

    void loop() {
        set_mux(counter);
        delay(500);
        counter++;
        if (counter > mux_max)
            counter = 0;
    }

Once you understand this example, you have everything you need to start using your multiplexer with something more sophisticated than just counting.

One last important thing to emphasize: the mux allows you to use just one signal I/O (plus the four selector outputs) on your Arduino, but that signal I/O is connected to only one device at a time. This won't work if you must always be sending a signal to several devices at the same time, which it appears might be the case from your [other question]. That said, if there's any time at which you're sending 0 V to a device, that is time you could be spending sending a non-0 V signal to another device.

For example, holding Z at +5 V and cycling the signal outputs through Y0-Y3 quickly will give you what's effectively a +5 V PWM with 25% duty cycle on Y0-Y3. In some cases, this technique can be useful.

Oh, one additional note: this example controls just one multiplexer; you can easily control two with two sets of selector pins, but this starts to use up a lot of pins. Instead, you may wish to have one set of selector pins on the Arduino hooked up to _both_ your muliplexors (and one I/O pin hooked up to both Zs) and use two more Arduino pins to control the Ē on each mux, having only one mux enabled at a time. This will save you three pins, at the cost of some complexity, but it's a good exercise to see if you really understand multiplexing technique since it's a straightforward extension of what you're doing with a single mux.

[product link]: http://bildr.org/2011/02/cd74hc4067-arduino/

[Octopart]: https://octopart.com
[list of parts]: https://octopart.com/search?q=cd74hc4067
[TI product page]: https://www.ti.com/product/cd74hc4067/technicaldocuments?HQS=TI-null-null-octopart-df-pf-null-wwe

[datasheet]: http://datasheet.octopart.com/74HC4067DB,112-Philips-datasheet-11553400.pdf
[high impedance]: https://en.wikipedia.org/wiki/Three-state_logic
[other question]: https://arduino.stackexchange.com/questions/36856/

body:
After reading your github page, I came to realize that:

1. you do not require full color control, but only setting the strips to
   full red or full blue
2. you are using MOSFETs for driving them.

Given these conditions, I believe the project may be feasible with your
current setup. The trick is that MOSFETs have some gate capacitance: if
you set the gate either HIGH or LOW, and then disconnect it, it will
keep that state for some time, until the charge stored in the gate
leaks. This means you do not need to address each MOSFET _continuously_:
you can just periodically “refresh” them, and let the gate capacitance
“remember” the state between refreshes. This is similar to how DRAM
memory works.

I wrote the following code based on this idea. Note that I did not test
it, as I do not have the required hardware. It uses a timer interrupt
firing every 1024 µs to cycle through the ten used mux channels:
each channel gets then refreshed every 10.24 ms. It also uses
[direct port access][] instead of `digitalWrite()`: not only it's way
faster (and you want to be fast in an ISR) but, more importantly, it
allows changing several outputs _simultaneously_. This is important in
order to avoid glitches.

    /*
     * Patterns to send to the multiplexers. bit_patterns[mux][chann] is the
     * pattern to send to the multiplexer `mux' in order to update the
     * channel `chann'. Bits 0..3 hold the channel number, bit 4 is the
     * data. The data bits are all initialized to zero.
     */
    volatile uint8_t bit_patterns[2][10] = {
        { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
    };

    /*
     * Periodically cycle through the 10 used multiplexer channels, updating
     * the MOSFETs. The TIMER0_COMPA interrupt has to be enabled for this to
     * automatically run every 1024 microseconds.
     */
    ISR(TIMER0_COMPA_vect)
    {
        static uint8_t i;            // channel index
        PORTB = bit_patterns[0][i];  // update MUX 0
        PORTC = bit_patterns[1][i];  // update MUX 1
        if (++i >= 10) i = 0;        // cycle channels
    }

    void setup()
    {
        DDRB   =  0x1f;         // set PB0..PB4 as outputs
        DDRC   =  0x1f;         // set PC0..PC4 as outputs
        TIMSK0 |= _BV(OCIE0A);  // enable TIMER0_COMPA interrupt
    }

This code relies on Timer 0 being in the standard Arduino configuration,
where it loops every 1024 µs. It also needs a specific wiring,
where each multiplexer is connected to a single AVR port, as follows:

    Arduino   multiplexers
    ----------------------
       8      S0 of MUX 0
           ...
      11      S3 of MUX 0
      12      SIG of MUX 0
      A0      S0 of MUX 1
           ...
      A3      S3 of MUX 1
      A4      SIG of MUX 1

In order to change the strip colors, you just have to update the stored
bit patterns:

    /*
     * On each of PORTB and PORTC, bits 0..3 are wired to the address select
     * pins of a multiplexer, whereas bit 4 goes to the SIG pin of the same
     * multiplexer.
     */
    const uint8_t SIG_BIT = 0x10;

    /* These are the only available colors. */
    typedef enum { BLACK, RED, BLUE, MAGENTA } color_t;

    /* Set the color of a strip. Strips are numbered from 0 to 9. */
    void set_color(uint8_t strip, color_t color)
    {
        /* Find the relevant multiplexer and channels. */
        uint8_t mux, red_ch, blue_ch;
        if (strip < 5) {
            mux = 0;
            red_ch = 2 * strip;
        } else {
            mux = 1;
            red_ch = 2 * (strip - 5);
        }
        blue_ch = red_ch + 1;

        /* Update the bit patterns. */
        if (color == RED || color == MAGENTA)
            bit_patterns[mux][red_ch] |= SIG_BIT;
        else
            bit_patterns[mux][red_ch] &= ~SIG_BIT;
        if (color == BLUE || color == MAGENTA)
            bit_patterns[mux][blue_ch] |= SIG_BIT;
        else
            bit_patterns[mux][blue_ch] &= ~SIG_BIT;
    }

The function `set_color()` assumes the following connections between the
multiplexers and the strips:

    MUX  channel    strip  color
    ----------------------------
     0      C0        0     red
     0      C1        0     blue
     0      C2        1     red
     0      C3        1     blue
                ...
     0      C8        4     red
     0      C9        4     blue
     1      C0        5     red
     1      C1        5     blue
                ...
     1      C8        9     red
     1      C9        9     blue

**Hardware considerations**

All this scheme may or may not work depending on some hardware factors
such as the gate capacitance of your MOSFETs, the leakage current of the
multiplexers when in high-impedance and the timing characteristics of
the same multiplexers. If the gate capacitance is too weak to hold the
value for 9 ms, you may want to add capacitors in parallel, maybe
something in the 100 pF range. If you add more than that, you may
also want to put resistors in series with pins 12 and A4 of the Arduino,
in order to protect them from the inrush current. But then you may also
want to slow down the scanning of the channels, which would require
configuring a timer.

[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation


body:
I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over **MODBUS TCP**. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are **READ_HOLDING_REGISTER** and **WRITE_SIGLE_REGISTER** and Function Code are **0x03** and **0x06** respectively.  I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??

The Document of Fronius Inverter for MODBUS TCP is [Fronius MODBUS TCP Datamanger][1]

  [1]: https://drive.google.com/open?id=0B7NXiG9jOGhmbFpMckJkNDFMdEE

title: Need Help to implement MODBUS TCP Master over Atmega32 MCU

Answers: 1

body:
So if you want to the atmega as client this means it will start the conection and made the request for values, so translating into modbus words your atmega will be a modbus master and the solar will be a modbus slave.

first you need a way to interface the micocontroller to the tcp/ip stack. you can use an ic or arduino shield which has this ic like a w5100 or enc28j60.

then you can write a library over tcp sockets to start the comunication or change some from the arduino.

https://www.google.com.br/url?sa=t&source=web&rct=j&url=http://myarduinoprojects.com/modbus.html&ved=0ahUKEwj9zMvjiYDTAhXJkpAKHfsNBz0QFggpMAE&usg=AFQjCNEfRhDgPGJNK-IUqrUw1FXEnBcxwQ&sig2=Xs0JNEWi_F_XiPgkTQdy-w


body:
I have an Adafruit motor shield v1 stacked on an Arduino Uno. I want to add a 433Mhz receiver to the Uno so I can control it wirelessly. However as you know the motor shield completely covers the Arduino board and all its pins, except perhaps the analog ones (it appeared to me).

So can you please suggest a way to connect the receiver if possible. I desperately need it and can't afford to buy a Mega now.

Please help asap.

title: How to connect receiver in an Arduino with a motor shield?

Answers: 1

body:
Adfruit Motor Shield v1 takes digital pins(D12 to D2) left only digital pins (D13,D1,D0) and all Analog pins of Arduino uno. So if you want to hookup RF receiver with Arduino then you have go this way.. connect RF Receiver output to the Digital pin D0 that is RX.

Here the schematic

[![Wiring RF receiver with Arduino][1]][1]

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


body:
I'm extremely frustrated at my ESP8266 right now, with the Arduino. I am using a 6v DC battery power supply (4xAA batteries), and a 3.3v voltage regulator (NTE1904). I have the connections as shown:

 - Vcc - 3.3v rail
 - CH_PD - 3.3v rail
 - RST - 3.3v rail (I put it into GND when I need to reset)
 - GPIO 0 - GND (I momentarily put the reset in ground after)
 - TXD - Rx
 - RXD - Tx

I have the 6V from the 4xAA batteries into the Vin of the 3.3V voltage reulgator, it's ground to the ground of batteries (and therefore connected to Arduino), and the output connected to the 3.3v rail.

I had the circuit working before, and I had it not receiving a packet header, but when I resembled the circuit fully I am now getting these errors when uploading my code:

`Sketch uses 232778 bytes (53%) of program storage space. Maximum is 434160 bytes.
Global variables use 31981 bytes (39%) of dynamic memory, leaving 49939 bytes for local variables. Maximum is 81920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed`

I've tried a bunch, and I am not sure where my problem is. Note:

 - I have changed my platform.txt (*Arduino15/packages/.../esp8266/2.2.0/platform.txt*)'s `tools.esptool.upload.pattern` to: `tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"` *(or have I? It seems quite unorganized I've changed it in the past from a tutorial saying that esptool doesn't work properly on OS X, but the page is quite hard to locate again. Please tell me what you use currently)*

Again, I am on OS X (10.11.4)

Thank you for any help. It is extremely frustrating trying to get this, and I cannot seem to find any up-to-date tutorials with my problem. If you know anything I could try, that would be great.

title: My ESP8266 01 is saying at espcomm_sync failed, espcomm_open failed, and (2x) espcomm_upload_mem failed. OS X

Answers: 0


body:
I am using the MPU6050 in conjunction with an Arduino and Jeff Rowberg's i2cdev library, and my project requires that the gyro rate outputs be more precise than the default setting, which is 1/16.4 of a degree (+/-2000 deg/sec range). The gyro outputs can be changed with `mpu.setFullScaleGyroRange(uint8_t range)` for which I passed in `MPU6050_GYO_FS_500` for range to get a higher precision

In this project, I also need the YPR position, which I obtain through `mpu.dmpGetQuaternion(&q, fifoBuffer)` and `mpu.dmpGetGravity(&gravity, &q)` and `mpu.dmpGetYawPitchRoll(ypr, &q, &gravity)`.

The problem is with the new gyro output range, the YPR position changes drastically when the MPU is being rotated and slowly catches up again once the MPU is held still. I think there is an error in the filter that combines the gyro and accel data that is making the gyro to sensitive. Maybe the DMP is dividing the GYRO rate data by the default sensitivity factor (16.4) when it should be dividing by the new one (131)?

**How can I get accurate YPR readings without delay?**

Here is a screenshot of the data. The axis aren't labeled, but the x-axis represents about 16 seconds of time. The blue line is the **gyro rate data**, and the pink line is the **roll position** of the MPU. The graph shows two rotations of the MPU.
[![enter image description here][1]][1]

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

title: MPU6050: Setting Gyro Output Range Throws of Positional Reading

Answers: 1

body:
Had the same problem, it appears that MPU6050 DMP code works like that once you change accelerometer and gyro scales.

Works better once you use +\-2000 deg/sec and +\-2g scaling settings.

        mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
        mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

The issue lies in the way "DMP" inner logic fuses data, i suppose it has "constants" that are tuned for these settings only.

In case you need both "changed settings" and "yaw\pitch\roll" data, you might want to implement sensor data fusion by yourself or use existing libs.

The easiest i may suggest would be implementing Complementary Filter.
More complex, yet accurate would be using Kalman Filter, all depends on time and patience you have to research those topics :)


body:
Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question
" how can I do this with a MCP23017 ? ".
I have searched the web a fair bit but no luck.
Is there a modified Servo library out there??
It's such an obvious solution i figure it must have been done before.
Any suggestions..Thanks.

title: Using MCP23017 to control Servos

Answers: 6

body:
> Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question " how can I do this with a MCP23017?

The Servo library could be modified to allow toggling of GPIO pins on a MCP23017 but there are some issues with timing.

The library uses Timers and Interrupt Service Routines (ISR) to handle the pulse width. The servo pin is toggled in the ISR.

At 100 KHz (100 Kbps) I2C at least 3 bytes need to be transmitted to the MCP230017 to toggle a pin. That is approx. 300 us and not possible to do from the Servo ISR. Another execution pattern is required.

Cheers!

body:
Theoretically, yes. It would be pretty interesting to see, but running multiple servos would account for a huge amount of what you can reasonably do with your code and probably be a huge headache.

Perhaps a better solution would be to use a PWM expander like the [PCA9685][1].

  [1]: https://core-electronics.com.au/adafruit-12-channel-16-bit-pwm-led-driver-spi-interface-tlc59711.html

body:
> how can I do this with a MCP23017 ? ".

you can but it would be fairly expensive in processing power, as you need to keep track of both rising and falling edges of every channel at all times, and send the data to the chip -> may not be doable given i2c's speed limitations.

> I have searched the web a fair bit but no luck.

I wrote a variety of approaches / implementations on driving multiple servo channels off of one timer, with or without output compare, here: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

it will branch out to a few other variants, depending on resources available to you.

body:
For PWM, the MCP23017 would have to be software-driven.
I would suggest one of the PCA9685 boards, which give you hardware PWM (and can also provide digital pins).
These are a bit more expensive, but very easy to use, and are driven by I2C in the same way.

body:
For example...

    unsigned long long servo_timing[2]={0,0};
    int A_data=0;
    void servo_ini()
    {
      Wire.beginTransmission(0x20);
        Wire.write(0x00);      // address bank A
        Wire.write(0x00);
        Wire.endTransmission();
    }
    void servo_set(unsigned int servo_tim,bool servo_mod){
       if(servo_mod==1){
        servo_tim=map(servo_tim,0,180,200,1900);
       }
       //if(servo_vector<=0)/*lcd_tim=650;*/servo_tim=220;/0
       //if(servo_vector==1)/*lcd_tim=1400;*/servo_tim=1000;/90
       //if(servo_vector>=2)/*lcd_tim=2255;*/servo_tim=1870;/180
       if(micros()-servo_timing[0]>servo_tim)
       {
         A_data&=0b11111110;
         Wire.beginTransmission(0x20);
         Wire.write(0x12);      // address bank A
         Wire.write(A_data);
         Wire.endTransmission();
         if(micros()-servo_timing[1]>(20000-servo_tim))
         {
           A_data|=0b00000001;
           Wire.beginTransmission(0x20);
           Wire.write(0x12);      // address bank A
           Wire.write(A_data);
           Wire.endTransmission();
           servo_timing[0]=micros();
           servo_timing[1]=micros();
         }

      }
    }

body:
I succeeded in pwm (servo control) with mcp23017.
Moreover, it is 16ch.
The mcp23017 in the Arduino Library also has a wordwrite write, but the frequency still couldn't catch up.
There is no choice but to create a library by yourself and generate a pulse of 0.5msec .. 2.5msec in 20msec 50Hz to drive the servo motor.
We are currently organizing the library
thank you
https://twitter.com/chrmlinux03/status/1534834169737789441?s=20&t=EqkVXJ2v1H3i_tfZsXfjHQ

https://github.com/chrmlinux/


body:
I am trying to flash a program onto an attiny167
(already bootloaded with the [micronucleus bootloader](https://github.com/micronucleus/micronucleus))
with a Raspberry Pi via avrdude and USB.

# Background
I have 50 Raspberry Pi 3B's connected to an amazon server collecting data.

I have 50 custom attiny167 based USB sensor PCBs which I will connect to the Pis
via USB ([see this previous issue for more detail](https://electronics.stackexchange.com/questions/280993/how-to-write-bootloader-and-drivers-to-attiny167?noredirect=1&lq=1))
It is a struggle to access and connect each device (especially 50 of them),
and I thus need to be able to reflash a program to them via the commandline of an RPi.

I have bootloaded them all from my windows 10 machine and can flash any program via USB.

# RPis
 I have flashed programs from the RPi with an Arduino Uno, both with the IDE and avrdude.
 Arduino and avrdude are installed and working (installed both with apt-get).

 The RPi can run an already flashed program, with reading and writing
 possible from the USB device.
 When plugged in the device is viewed by the lsusb command for 5 seconds.
 The pre-flashed program then runs and lsusb shows no device:

 **`lsusb` immediately after device is plugged into port**

 pi@raspberrypi:/usr/bin $ lsusb
 Bus 001 Device 005: ID 046d:c077 Logitech, Inc.
 Bus 001 Device 006: ID 413c:2011 Dell Computer Corp. Multimedia Pro Keyboard
 Bus 001 Device 004: ID 413c:1005 Dell Computer Corp. Multimedia Pro Keyboard Hub
 Bus 001 Device 007: ID 16d0:0753 MCS Digistump DigiSpark
 Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
 Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
 Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

 **`lsusb` ~5 seconds after device is plugged into port**

 pi@raspberrypi:/usr/bin $ lsusb
 Bus 001 Device 005: ID 046d:c077 Logitech, Inc.
 Bus 001 Device 006: ID 413c:2011 Dell Computer Corp. Multimedia Pro Keyboard
 Bus 001 Device 004: ID 413c:1005 Dell Computer Corp. Multimedia Pro Keyboard Hub
 Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
 Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
 Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

### udev rules
I have followed the
[tutorial for udev rules by digistump](http://digistump.com/wiki/digispark/tutorials/linuxtroubleshooting)
and placed the file at /etc/udev/rules.d/49-micronucleus.rules

UDEV of [tinseey](https://www.pjrc.com/teensy/49-teensy.rules) (similar to bootloaded micronucleus for attiny167)

# AVR Device

[this post](http://www.raspberry-pi-geek.com/Archive/2014/03/Adding-analog-input-to-the-Pi-using-the-Digispark/(offset)/2)
hints it may not be possible,
however this issue may have been resolved, as I am using an attiny167 (rather than an 85),
and the Pi does not reboot on the USB being plugged in.

On using dmesg you can see it is unable to enumerate.
`dmesg`

[ 9820.701327] usb 1-1.2: new low-speed USB device number 7 using dwc_otg
[ 9820.803813] usb 1-1.2: New USB device found, idVendor=16d0, idProduct=0753
[ 9820.803838] usb 1-1.2: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[ 9825.208851] usb 1-1.2: USB disconnect, device number 7
[ 9828.001334] usb 1-1.2: new low-speed USB device number 8 using dwc_otg
[ 9833.081359] usb 1-1.2: device descriptor read/64, error -110
[ 9833.271389] usb 1-1.2: device descriptor read/64, error -71
[ 9833.461352] usb 1-1.2: new low-speed USB device number 9 using dwc_otg
[ 9833.541349] usb 1-1.2: device descriptor read/64, error -71
[ 9833.731352] usb 1-1.2: device descriptor read/64, error -71
[ 9833.921349] usb 1-1.2: new low-speed USB device number 10 using dwc_otg
[ 9834.341388] usb 1-1.2: device not accepting address 10, error -71
[ 9834.421361] usb 1-1.2: new low-speed USB device number 11 using dwc_otg
[ 9834.841371] usb 1-1.2: device not accepting address 11, error -71
[ 9834.841480] usb 1-1-port2: unable to enumerate USB device

# avrdude
I'm using the command, with different serial ports

usr/bin/avrdude -p attiny167 -c arduino -C /etc/avrdude.conf -b 19200 -P [COM PORT] -U flash:w:[MyHexFile.ino.hex]:i

this gives the error

avrdude: ser_open(): can't open device "[COM PORT]": No such file or directory

avrdude done.  Thank you.

The same method works with the Uno on the Pi, and the AVR device on my windows 10 machines.

I have updated the configuration file `avrdude.conf` to include the attiny167,
as I did with my windows 10 machine.

# Serial port

serial and ttyACMO appears with Uno in /dev, not for the AVR device.

# Arduino IDE
I've attempted to do this through the IDE but get the error:

/home/pi/Downloads/arduino-1.8.1/arduino-builder -dump-prefs -logger=machine -hardware /home/pi/Downloads/arduino-1.8.1/hardware -hardware /home/pi/.arduino15/packages -tools /home/pi/Downloads/arduino-1.8.1/tools-builder -tools /home/pi/Downloads/arduino-1.8.1/hardware/tools/avr -tools /home/pi/.arduino15/packages -built-in-libraries /home/pi/Downloads/arduino-1.8.1/libraries -libraries /home/pi/Arduino/libraries -fqbn=digistump:avr:digispark-tiny -ide-version=10801 -build-path /tmp/arduino_build_279218 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=/home/pi/.arduino15/packages/digistump/tools/micronucleus/2.0a4 -prefs=runtime.tools.avr-gcc.path=/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5 -verbose /home/pi/sensicorn/sensicorn/indoorSoftware/Arduino Code/neopixel_simple/neopixel_simple.ino
/home/pi/Downloads/arduino-1.8.1/arduino-builder -compile -logger=machine -hardware /home/pi/Downloads/arduino-1.8.1/hardware -hardware /home/pi/.arduino15/packages -tools /home/pi/Downloads/arduino-1.8.1/tools-builder -tools /home/pi/Downloads/arduino-1.8.1/hardware/tools/avr -tools /home/pi/.arduino15/packages -built-in-libraries /home/pi/Downloads/arduino-1.8.1/libraries -libraries /home/pi/Arduino/libraries -fqbn=digistump:avr:digispark-tiny -ide-version=10801 -build-path /tmp/arduino_build_279218 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=/home/pi/.arduino15/packages/digistump/tools/micronucleus/2.0a4 -prefs=runtime.tools.avr-gcc.path=/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5 -verbose /home/pi/sensicorn/sensicorn/indoorSoftware/Arduino Code/neopixel_simple/neopixel_simple.ino
Using board 'digispark-tiny' from platform in folder: /home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7
Using core 'tiny' from platform in folder: /home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7
Detecting libraries used...
"/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections  -w -x c++ -E -CC -mmcu=attiny85 -DF_CPU=16500000L -DARDUINO=10801 -DARDUINO_AVR_DIGISPARK -DARDUINO_ARCH_AVR  "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/cores/tiny" "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/variants/digispark" "/tmp/arduino_build_279218/sketch/neopixel_simple.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections  -w -x c++ -E -CC -mmcu=attiny85 -DF_CPU=16500000L -DARDUINO=10801 -DARDUINO_AVR_DIGISPARK -DARDUINO_ARCH_AVR  "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/cores/tiny" "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/variants/digispark" "/tmp/arduino_build_279218/sketch/neopixel_simple.ino.cpp" -o "/tmp/arduino_build_279218/preproc/ctags_target_for_gcc_minus_e.cpp"

fork/exec /home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++: no such file or directory
Error compiling for board Digispark (Default - 16.5mhz).

when I type `which avr-g++`: /usr/bin/avr-g++, this is just a copy from my windows machine.
I found this [github issue](https://github.com/Robot-Will/Stino/issues/275)
and it seems to be irrelevant for now, just a path issue.

I've had to use a custom json file for the board manager to find micronucleus and Digispark Pro.

When I plug in the AVR device no new serial port is shown in Tools->Port (unlike Arduino UNO, ttyACM0 appears).

I'd much prefer to do flash via avrdude or similar on the commandline, so I have not focused on this.

---
# My question
Is it possible to flash the AVR device with a Raspberry Pi over USB?
If so, what am I doing wrong?

title: Software flashing attiny167 from RPi with avrdude

Answers: 0


body:
I am trying to execute some webbased calls, but my string keep "disappearing", and I am highly confused about why.

I can println a string directly, but if I have it in a variable, it will disappear :I

I tried googling around, but could not find a reason for it. Is it because of the curly brackets ? Is it a memory issue ?

I feel I really can't code on and juggle web calls, if I can't even handle regular string commands..

**Code:**

 Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
 String message = "Testing time {0}";
 Serial.println(message);
 Serial.println(String(message));
 Serial.println("Testing time {0}");
 Serial.println(message.substring(3,6));

**Response:**

    - CONSOLE/STRING WEIRDNESS -
    (nothing)
    (nothing)
    Testing time {0}
    (nothing)

[![The code and the debugger][1]][1]

**Update**

This seems to happen whenever there is a number inside a string, it even happends with a simple string like this:

**Code:**

 Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
 String message = "Testing time here is a number 0";
 Serial.println(message);
 Serial.println(String(message));
 Serial.println("Testing time here is a number 0");
 Serial.println(message.substring(3,6));

**Response:**

    - CONSOLE/STRING WEIRDNESS -
    (nothing)
    (nothing)
    Testing time here is a number 0
    (nothing)
  [1]: https://i.stack.imgur.com/Fw3nP.jpg
  [2]: https://i.stack.imgur.com/YPfRZ.png

title: Confusion about String handling

Answers: 2

body:
The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.

I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).

Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.

Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:

    Serial.println(F("Some string to print"));

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.

To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:

    Serial.print(F("Test time: ");
    Serial.println(test_time);

body:
Give this article a read, it highlights how strings are actually stored in the Arduino memory, and explains how strings should be used.

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


body:
I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large.
I have several different devices used in this project:

 - The LED matrix
 - A DS3232 RTC
 - An MSGEQ7 DSP chip
 - 7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.

What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.

Any help would be greatly appreciated, I can upload the source code if its needed.

Cheers

As a side note, I'm using "Sublime Text 3" along with Stino.

title: What is the correct way to create large project files?

Answers: 1

body:
Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.

It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.

If it has a lot of interactions, maybe you should put the patterns itself in a different class.

Normally what I keep as guidelines:
- Not more than a few hundred lines in a class
- Not more than 7 (class) variables in a class
- Not more than 7 functions/methods in a class

Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.

Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about [SOLID][1].

  [1]: https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)


body:
To make an oscilloscope in matlab environment, for data acquisition on arduino side, when inbuilt `analogRead()` is used, it's working fine, but with very low sampling rate, that aliasing is clearly observed. That too, non-uniform sampling. Thus listing out the drawbacks:

 1. Very slow data rate, even if, sent with 115200 baudrate,
 2. Aliasing
 3. Non-uniform sampling

[![Observed waveform, analogRead()][1]][1]

Thus, to overcome above, ADC in free running mode was used, with 16 as prescaling factor, thus 76.9KHz sampling rate (counting each ADC as 13 clock cycles). Thus, data is uniformly sampled now. Also it is quite fast, because of sampling, and is observed. The only problem now exists is, output has a specific noise. The data being sampled is 50Hz sinusoidal current waveform by current sensor ACS712. It overlays instantaneous current waveform over a bias of 2.5V. Thus, when signal is not present, a constant voltage of 2.5V is observed, thus, 512, because of mapping to 255 range.. 127. But in the case of free running mode, along with 127, 191, 63 only are observed. And it can also be seen that nearly 127 = 63*2, and 191 = 63*3. And when current waveform exists, it's highly distorted, but perceptible that it's not the previous signal of just 127, 191, 63. In the below plot, current is passed since 33.5sec.
[![Observed waveform, free running mode][2]][2]

I am unable to understand this, structured noise. What may be the reason ? I have once read, last two MSB bits get noisy at this sampling rate, but then how would 127, jump to 191. Why is 63 getting added, subtracted at each instant ?
I understand the reason for non-uniform sampling now is because of `Serial.print()`, whose interrupts are obstructing the ADC interrupts, but don't understand the reason behind the noise observed.

Following is the code uploaded in arduino. Serial data is read from matlab by `fread()` function.

    long t1=0,ts1=0,ts2=0;
    int aval=0, val=0;

    void setup() {

     TIMSK0 = 0x00;           // disable timer (causes anoying interrupts)
     DIDR0 = 0x3F;            // digital inputs disabled
     ADMUX = 0x40;            // measuring on ADC0, right adjust, AREF reference
     ADCSRA = 0xAC;           // AD-converter on, interrupt enabled, prescaler = 16
     ADCSRB = 0x00;           // AD channels MUX on, free running mode
     bitWrite(ADCSRA, 6, 1);  // Start the conversion by setting bit 6 (=ADSC) in ADCSRA
     sei();
     Serial.begin(115200);
     t1=millis();
     }

    ISR(ADC_vect)
    {
     aval = ADCL;
     aval += ADCH << 8;
    }

    void loop() {
    val = map(aval, 0, 1023, 0, 255);
    Serial.write(val);
    delay(10);
    }

  [1]: https://i.stack.imgur.com/kuBUf.png
  [2]: https://i.stack.imgur.com/4wkzE.png

title: Specific noise while using arduino ADC in free running mode

Answers: 3

body:
If you use an ISR to retrieve the ADC result, you will need to protect the read of the variable. An interrupt may occur when reading `aval` in the `loop()`, as this is a 16-bit value and the read requires several instructions. This may give corrupt values.

    void loop() {
      noInterrupts();
        val = aval;
      interrupts();
      val = map(val, 0, 1023, 0, 255);
      Serial.write(val);
      delay(10);
    }

Cheers!

body:
Not sure what "structured noise" you are referring to but some advices.

1. Check the datasheet to see adc timing requirement. When not enough time is given, acc results are highly correlated serially.

2. In the acc isr, make sure that atomicity is preserved.

3. Isr has its overhead so make sure that it is consistent with your acc speed setting.

4. If you are using only the msb. You can configure the acc to be left alighened, saving you lots of time and headache.

body:
It is very unclear what you are trying to achieve here. You are clocking
the ADC at its maximum frequency, which has it take one reading every
13 µs, and yet you are delaying for 10 ms after sending one
reading through the serial port. So basically your Matlab program is
getting one reading out of every 769 you take.

If you want fast data acquisition with a consistent sampling frequency,
you basically have two options:

* clock the ADC as fast as you dare, buffer the data in RAM and, when
  the buffer is full, send it to the host computer
* set a high baud rate and take the data as fast as the UART can send
  it.

The first option allows for faster sampling rates, but only as short
bursts, as limited by the available RAM. Given what you have already
written I assume you want continuous acquisition, and thus the second
option. I also assume you are using an Arduino Uno or similar.

At 115.2 kb/s (actually 117.647 kb/s given the rounding), every bit sent
takes 136 CPU cycles, or 8.5 µs. One byte takes 10 bits
(start bit + 8 data bits + stop bit), i.e. 85 µs.
This means there is no point in clocking your ADC that fast: you can set
the prescaler to 64 and each reading will take 52 µs.

What I would do here is configure the ADC to be triggered by
Timer 1, and have that timer deliver the trigger signal every
1360 CPU cycles _exactly_. Then,

<!-- language: lang-c++ -->

    ISR(ADC_vect)
    {
        Serial.write(ADCH);
    }

assuming of course you have set the left-adjust mode (`ADLAR` bit in
`ADMUX`).

With the ADC and the UART working at the very same frequency, you keep
the UART busy without ever filling the output buffer. If your ADC runs
faster than the UART, the buffer will fill out and your timings will get
nasty. On the other hand, if you are really confident in your timings,
you could skip the `Serial` managing of that buffer and just do
`UDR0 = ADCH` in the ADC ISR.


body:
I was connecting my arduino uno to a adafruif micro SD card breakout and everything worked just fine, i could read the sd, write to it and see all the info about it. To do it i just followed the tutorial in [here](https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/library?view=all).

My problem is that when I arrived home the exact some thing wouldn't work and I couldn't read the SD card anymore.

 I was thinking it could be a bad contact problem since sometimes i get:

    Initializing SD card...initialization failed. Things to check:
    * is a card inserted?
    * is your wiring correct?
    * did you change the chipSelect pin to match your shield or module?

And other times (almost never), i would just get:

    Initializing SD card...Wiring is correct and a card is present.
    Card type: SD2
    Could not find FAT16/FAT32 partition.
    Make sure you've formatted the card

I would like to know if I can assume it is the breakout board failling and I would buy a new one, or if it can be any other thing.

Thank you in advance!

title: Problem with Micro SD card breakout

Answers: 1

body:
Did you try:

 1. Reading the SD card in your computer ... if  you can read (or write) files, that means the SD card is intact
 2. Use a SD card that worked before or similar. Some bigger SD cards (like SDHC, SDXC have less good compatibility). Preferably use a 2 GB or smaller card (unless you have used bigger cards successfully and of the same or smaller type, e.g. SD, SDHC, SDXC).
 3. Try different formattings, like FAT, FAT16, FAT32. I think FAT is the mostly recognized formatting.
 4. Check connections/wires to/from SD breakout, maybe during your leave accidentally you (or someone else) or due to pressure/tension, a contact/wire got loose.
 5. Check another SD card in the SD breakout where the SD card you know is good. If this also does not work, it must be the breakout (or Arduino).
 6. Replace every piece of hardware (including wires) one by one and recheck if it works (after you are sure the SD card itself is ok).


body:
I want to make my Arduino Uno and Genuino Zero communicate using UART. My Genuino Zero is the transmitter and the receiver is the Arduino Uno.

For the Arduino Uno, I am using the SoftSerial library. I have uploaded the transmitter and receiver codes.

My connection is as below:

>Genuino Zero (RX) pin 0 ---------------- Arduino Uno pin 11
>
>Genuino Zero (TX) pin1  ---------------- Arduino Uno pin 10
>
>Ground ----------------------------------   Ground

The Arduino Uno's pin 10 is Rx and pin 11 is Tx, using SoftSerial.

The transmitter transmits 'a'. The receiver receives 'a' and turns a LED on. My problem is that on the receiver, I am not getting anything.

My code is here:

https://www.dropbox.com/s/4w8o2h2k4zs0it5/transmitter.txt?dl=0
https://www.dropbox.com/s/d50uizoz3iove9w/receiver.txt?dl=0

-------------------receiver---------------------

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX, TX

    /* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

    /* Use a variable called byteRead to temporarily store
       the data coming from the computer */
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
      Serial.begin(9600);
       mySerial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      char a[8];
      /*  check if data has been sent from the computer: */
      if (Serial.available()) {
        /* read the most recent byte */
        byteRead = Serial.read();
        Serial.print("rushin\r\n");
        /*ECHO the value that was read, back to the serial port. */
        if(byteRead == 0x61) {
          digitalWrite(LED_BUILTIN, HIGH);
          Serial.write(byteRead);
        }
      }
      if (mySerial.available()) {
        /* read the most recent byte */
        byteRead = mySerial.read();
        mySerial.print("rushin\r\n");
        /*ECHO the value that was read, back to the serial port. */
        if(byteRead == 0x61) {
          digitalWrite(LED_BUILTIN, HIGH);
          mySerial.write(byteRead);
         }
      }
    }

    -------------------transmitter----------------------------------

    /*
      DigitalReadSerial
     Reads a digital input on pin 2, prints the result to the serial monitor
     This example code is in the public domain.
     */

    // digital pin 2 has a pushbutton attached to it. Give it a name:
    int pushButton = 7;
    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
      // make the pushbutton's pin an input:
      pinMode(pushButton, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input pin:
      int buttonState = digitalRead(pushButton);
      // print out the state of the button:
      Serial.println("a");
      delay(1000);
      // delay in between reads for stability
    }

title: Communication between Genuino Zero and Arduino Uno using UART

Answers: 1

body:
Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.

So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):

    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial1.begin(9600);
      // make the pushbutton's pin an input:
      pinMode(pushButton, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input pin:
      int buttonState = digitalRead(pushButton);
      // print out the state of the button:
      Serial1.println("a");
      delay(1000);
      // delay in between reads for stability
    }


body:
I need to send 6 bytes value from Arduino UNO to the [actuator][1] using serial port in order to make it extends. I have added a button to send the data. For example, 0 20 1 1 0 0. The communication settings are 9600 baud rate, 8 data bits, no parity and 1 stop bit. I have used MAX 232 to build a TTL to RS232 circuit. The actuator does not move. Are there any problems on my program? I am new to create USART code. I think I have some problems on transmit function. I am using the build in USART with c code. Here is my code:

 #define BAUD_PRESCALER 0x67
 int buttonPin1 = 4;
 int buttonState1 = 0;

 void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin1, INPUT_PULLUP);
 }

 unsigned char data1 = 0x00; // 0
 unsigned char data2 = 0x14; // 20
 unsigned char data3 = 0x01; // 1
 unsigned char data4 = 0x01; // 1
 unsigned char data5 = 0x00; // 0
 unsigned char data6 = 0x00; // 0

 void USART_Init(void) {
  /*Set baud rate */
  UBRR0 = BAUD_PRESCALER;
  UCSR0A = 0x00;
  /*Enable receiver and transmitter */
  UCSR0B = 0x08;
  /* Set frame format: 8data, 1stop bit */
  UCSR0C = 0x06;
 }

 void USART_Transmit( unsigned char data ) {
  /* Wait for empty transmit buffer */
  while ( !( UCSR0A & (1<<UDRE0)) )
  {
   ;
  }
  /* Put data into buffer, sends the data */
  UDR0 = data;
 }

 void loop() {
  // put your main code here, to run repeatedly:
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == LOW)
  {
   USART_Init();
   USART_Transmit(data1);
   USART_Transmit(data2);
   USART_Transmit(data3);
   USART_Transmit(data4);
   USART_Transmit(data5);
   USART_Transmit(data6);
  }
 }

  [1]: http://www.zaber.com/wiki/Manuals/T-LA#Initial_Setup_and_Testing

title: Arduino UNO USART problems

Answers: 3

body:
I would recommend you to use the arduino's built in UART library. Try this code:

    int buttonPin1 = 4;
    int buttonState1 = 0;

    unsigned char data1 = 0;
    unsigned char data2 = 20;
    unsigned char data3 = 1;
    unsigned char data4 = 1;
    unsigned char data5 = 0;
    unsigned char data6 = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);           // set up Serial library at 9600 bps
      while (!Serial);              // wait till UART initialized, for arduino UNO

      pinMode(buttonPin1, INPUT_PULLUP);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        buttonState1 = digitalRead(buttonPin1);
        if (buttonState1 == LOW)
        {
            Serial.write(data1);
            Serial.write(data2);
            Serial.write(data3);
            Serial.write(data4);
            Serial.write(data5);
            Serial.write(data6);
        }
    }

You should know that as long as the button is pressed data is being sent to the actuator. With that being said, with one button press you may have the commands sent 10 times. Thus, you have to deal with that in your code.

body:
The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.

Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.

body:
I think that your BAUD rate setting is wrong. The `UBRR0` register is a 16 bit wide one thus should be accessed in two 8 bit part, via `UBRR0H` and `UBRR0L`. You can check it in the [datasheet][1].

If you further check the datasheet there is an example code in addition to the USART description which shows a correct way of initialization.

>     #define FOSC 1843200 // Clock Speed
>     #define BAUD 9600
>     #define MYUBRR FOSC/16/BAUD-1
>     void main( void )
>     {
>         ...
>
>         USART_Init(MYUBRR)
>         ...
>     }
>
>     void USART_Init( unsigned int ubrr)
>     {
>         /*Set baud rate */
>         UBRR0H = (unsigned char)(ubrr>>8);
>         UBRR0L = (unsigned char)ubrr;
>         /* Enable receiver and transmitter */
>         UCSR0B = (1<<RXEN0)|(1<<TXEN0);
>         ...
>     }

As you can see the UBRR's value is calculated using the system clock speed `FOSC`, with `MYUBRR` macro which is an equation from the datasheet. Later this value is being set in two part upper 8 bit:

    UBRR0H = (unsigned char)(ubrr>>8);

lower 8 bit:

    UBRR0L = (unsigned char)ubrr;

(Your transmit function seems to be correct. And as I commented it is enough to call the USART init once in the `setup()`.)

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


body:
Is it garanteed (with some precision) that the phase of a PWM-signal generated by `tone` is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?

I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).

title: What is the phase of tone?

Answers: 3

body:
The [arduino.cc description of `tone()`](https://www.arduino.cc/en/reference/tone) says “Only one tone can be generated at a time”, so presumably you are using some other software to generate tones on multiple pins.  For example, [Brett Hagman's `play()` code](https://code.google.com/archive/p/rogue-code/wikis/ToneLibraryDocumentation.wiki), which Arduino `tone()` is derived from, uses multiple timers, one per tone.

When using `play()`, you probably can adjust phase by calling  [`delayMicroseconds()`](https://www.arduino.cc/en/Reference/DelayMicroseconds) between the two  `play()` calls that start up the tone generation; for example:

    play(11, 440);
    delayMicroseconds(235); // Move 2nd tone 8 cm closer
    play(9, 440);

Note, because `tone()` and `play()` use one timer per output (for example, timer 2 for first tone, timer 1 for next tone, timer 0 for third tone) there usually will be some timer prescale mismatches between 8-bit and 16-bit timers, which may result in slightly different frequencies, leading to some constant phase shift rate if you use that method.

With the speed of sound about 340.29 m/s in air at standard pressure, the wavelength of say 440 Hz would be under a meter, so I presume you would move speakers just a few tens of cm for phasing; hence a few hundred to a few thousand microseconds of phase offset.  If you want good programmatic control, and also want to have quite a few speakers, external hardware in the form of a delay line or a bucket brigade chip is an obvious approach.

You could simulate a program-controlled delay line fairly easily using a handful of 74HC595 SIPO shift registers, as follows:  Connect the DS of the first '595 to your `tone()` output pin.  Connect the Q7S output of each '595 except the last to the DS of the following '595.

Now use another timer to repeatedly clock your tone data into the shift register chain.  That is, connect all STCP and SHCP inputs in parallel to a timer output pin.  (Eg, OC1A, OC1B, OC2A, or OC2B, which might be pins like 9–12 on an Uno or Nano).  Run that timer at 10 to 100 KHz, ie, at some rate *f* that gives you the resolution and range of phase changing that you need.

Calling the shift register outputs o₀, o₁, o₂..., we have oⱼ delayed by (j-i)/*f* seconds relative to oᵢ.  That is, successive SR outputs represent different taps for different delays.

body:
The main principle behind working with buzzers, in its simplest form, comes down to something along the lines of

    digitalWrite(buzzerPin,HIGH);
    delay(half_tone_frequency);
    digitalWrite(buzzerPin,LOW);
    delay(half_tone_frequency)

that, when repeated is enough to generate some tone on a single buzzer. However - to get desired tones (frequencies) right, you have to be mindful of the exact time that passes between each part of the code (the pin needs to oscillate in some frequency to produce a tone of that frequency)

So technically, its possible to create different sounds on different buzzers connected on different(!) pins at the same time, if you know exactly how much time each pin spends HIGH and LOW. This is naturally simpler when they do not need to be active concurrently.

body:
If you want fine control over the phases, I assume you may also care
about having low phase noise. In this case your best bet is to avoid
toggling the pins in software and go for a hardware signal generation.

With an Arduino Uno or similar board, this can probably achieved by
programming a timer. I would try the following:

Configure Timer 1 in waveform generation mode 12, i.e. CTC
mode with TOP = ICR1. Set the compare output mode of both channels
to toggle on compare match. Set ICR1 so that the timer has _half_ the
period of the signal you want. Now you can independently adjust the
phases of both outputs by writing to `OCR1A` and `OCR1B`.

Note that those registers are not double buffered in this mode, so you
have to be careful about when you write them.

The Arduino core library has no support for such timer configuration:
you will have to learn how to program it yourself. If you are not
familiar with the subject matter, I recommend you start by reading
[Nick Gammon's tutorial on timers](https://www.gammon.com.au/timers).


body:
I've made a small interface using the asio C++ library to open serial ports and do I/O from/to them.
It works with my Arduino Uno and other hardware as well (industrial weighing machines), but I only specify the port and baud rate.

The following code is run in the client application, which runs both on my Windows 10 Student Edition x86_64 machine, and on old 32 bit  Win XP machines that communicate with the weighing machines:

    /*this is inside a constructor*/
    /*iosvc gets passed by reference, port_ is a member variable of type asio::serial_port,
     npuerto is the name of the port (e.g. "COM3") */

    port_(iosvc_, npuerto),

    /*...*/

    port_.set_option(asio::serial_port_base::baud_rate(baudios));

 The Arduino is programmed to do a serial echo of whatever is sent to it, for testing purposes. This is the echo code:

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

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

It works fine with my Arduino until I unplug it and plug it back in. After replugging it all the values returned are garbage, specifically some sort of '?' character inside a black box, don't know the bit value though, but it's constant. The problem gets fixed when I open an arduino IDE Serial Port monitor.
If I close it, and once again use my own software to open up the serial port, all the values are fine.

From this I concluded that the Arduino IDE Serial Port monitor is doing something when it opens up the port that I'm not doing.

Any clues? Flow control? Handshake?
Thanks

title: Serial Port configuration with asio C++ library

Answers: 1

body:
Can you include all the other calls you make related to setting up the serial port along with `asio::serial_port_base::baud_rate(baudios)`? Ideally, split that out into a separate function (that takes parameters such as baud rate) that you know is the only thing doing this setup.

As I mentioned in the comment, getting back the right number of chararacters but incorrect characters looks as if the baud rate is correct but something else is wrong. The first thing that comes to mind is the bits/parity/stop bits settings. Typically you want to be using 8 bits, no parity, often referred to as "8N1".


body:
Different boards have different number of pins.

Is there a way to know this number in code (at least digital and analog pins), or do I have to determine board type (like in [this thread][1]) and know the number of pins by myself?

----------

*Reasoning for this is that I'm creating prototype using Uno and using 2-3 analog pins for temperature readings, but I want to be able to use the same code for different board in the future with eg. 8 analog pins, so I don't have to remember to change pin numbers in code and maybe solder it convenient way etc. Also being able to use for eg. "last available analog pin" for certain job could help keep code/schematics nice and clean.*

  [1]: https://arduino.stackexchange.com/questions/21137/arduino-how-to-get-the-board-type-in-code

title: How to get number of available pins in code?

Answers: 3

body:
In the ultimate case, a "board" is not something you can determine programmatically in software; it's not possible in general to tell if, e.g., a particular pin on the microcontroller is connected to a corresponding head pin on the board.

That said, as [Edgar Bonet point out](https://arduino.stackexchange.com/a/36683/31794), the Arduino board definitions used in the IDE will generally do what you want. Just keep in mind, these are just someone saying "the board should be like this"; a cheap clone board, for example, might be different without a new and proper board definition.

With running code on the microcontroller itself, examining what it can see of the board, you can usually tell which microcontroller you're using. But that just tells you about the chip and its pins, and not about where leads from those pins might go. It sounds to me as if you're asking to find a way to see if your particular microcontroller (e.g., an ATmega328P) is on, say, an [Arduino Uno](https://www.arduino.cc/en/Main/ArduinoBoardUno) or some other board where certain MCU pins may or may not be hooked up to board pins. The MCU can't tell whether any of its particular pins are connected to headers on the board. As a more specific example, someone could build a board with an MCU with 100 digital IO pins available, yet if only ten of these are brought out to pins on the board, the others are not easily usable.
uino.cc/en/Main/ArduinoBoardUno) or [Arduino Nano]

For your application, you're thinking in a good direction when considering how to make things easier for others using your code. However, I'd suggest that in the long run it's better just to have clear definitions in an obvious place in your sketch (at the top of the file in a single-file sketch, perhaps in a `config.ino` in a multi-file sketch, or passed in to an initialization function for a library) that says explicitly what pins are used and is easy to change for others. Having the default pins used by the sketch move around if I load the sketch on a different board strikes me as rather confusing.

Keep in mind your audience: the people who are going to be using this on a board different from yours are Arduino hobbyists, and so they're already (or will soon become :-P) familiar with the idea of pins, pin definitions in code, and pin conflicts.

body:
It is quite easy actually:

<!-- language: lang-c++ -->

    Serial.print("number of digital pins: ");
    Serial.println(NUM_DIGITAL_PINS);
    Serial.print("number of analog inputs: ");
    Serial.println(NUM_ANALOG_INPUTS);

Note that these are compile-time constants defined as macros in a file
named `pins_arduino.h`. There is one such file for every board supported
by the Arduino environment. Just to take Curt J. Sampson's example, if
someone “made a board with an MCU with 100 digital IO pins available,
yet if only ten of these are brought out to pins on the board”, then the
macros would tell you you have 10 digital pins. Assuming of course that
you installed the proper support package for that particular board.

body:
You can identify the host processor at run time - each one has its own signature - but not necessarily the board it's running on (consider an Uno and a breadboard-uino for example). So you'd have to make each kind of board you use distinguishable in some way, such as jumpering 3 pins each high or low to make a 3-bit binary code representing one of 8 board types. The next solution is to define that code or some other identifier at compile time with a #define statement, and use the identifier in one or more #ifdef statements to compile board-specific pin definitions.

If you plan on using standard boards the IDE knows about, the IDE pre-defines some useful symbols for you. Here's the compile command the IDE used for an empty sketch for an UNO (I've reformatted it for readability):

    "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++"
    -c
    -g
    -Os
    -Wall
    -Wextra
    -std=gnu++11
    -fpermissive
    -fno-exceptions
    -ffunction-sections
    -fdata-sections
    -fno-threadsafe-statics
    -MMD
    -flto
    -mmcu=atmega328p
    -DF_CPU=16000000L
    -DARDUINO=10612
    -DARDUINO_AVR_UNO
    -DARDUINO_ARCH_AVR

The last four lines make the equivalent of #defines for the clock-frequency, the IDE version number, the Arduino-board, and the overall MCU architecture, respectively.

So in your code, a block like:

    #ifdef ARDUINO_AVR_UNO
       // pin definitions for Uno here
    #endif

will only be compiled if you selected "Arduino/Genuino Uno" as your board type in the IDE. There are similar symbols for other board types. So for a Nano, `ARDUINO_AVR_NANO` would be defined instead.


body:
I have this adafruit-feather-huzzah-esp8266:
https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts

and I want to connect a Fona board. But I am not certain which pins have the aforementioned software serial pins
necessary to make the required connections.
https://www.arduino.cc/en/Reference/SoftwareSerial

from the Fona tutorial:
https://learn.adafruit.com/adafruit-fona-3g-cellular-gps-breakout/arduino-wiring

which pins on the adafruit-feather-huzzah-esp8266 should I use for pin:
"TX connects to digital 3 (9 on Leo/Micro, 10 on Mega) "

where the feather doesn't have this a pin3.
similarly, which pins correspond to RST and RX?

title: How can I connect a Fona to an Adafruit feather?

Answers: 0


body:
I've been trying to make a wattmeter using arduino but cannot find the shield I need to buy to put onto my arduino to make it. There are no such parts in the Arduino Store and online the best I could find is [this][1]. This measures the arduino's energy consumption, however, not other things. I am really new at this and thoroughly lost. I would be really glad if someone could help me with this problem :)

  [1]: http://www.robotshop.com/en/energy-monitor-shield-arduino.html?gclid=CJD6jtrgiNMCFQmqaQody_0CPQ

title: Trying to make a wattmeter

Answers: 1

body:
You will need an Ampere meter and a Voltmeter. Watts is `Volt` * `Ampere`.

There are logic level compatible units out there for ampere meters ranging from a few mA to at least dozens of Amperes.

Also for voltmeters there are several logic level compatible units available, to plug in your project.

The rest is math. (Watts = A * V )


body: I'm trying to communicate with a device which only uses a single wire at 9600 Baud. How can I use my Arduino UNOs RX/TX-Pins to recieve and transmit on that one wire?

title: Single-channel serial communication

Answers: 1

body:
Bidirectional Asynchronous Serial schemes are not uncommon.  The famous ones, like RS485, utilize special line drivers and differential signalling, but for short distances you can accomplish something similar using the ability of most MCU's, including the Arduino's ATmega, to tristate the serial transmit pin.

Essentially, you would wire the shared line to both the receive and transmit pins, and when it is not the Arduino's "turn" to transmit, you would configure the Transmit pin as an *input* rather than as an output.

It's then up to a software protocol to make each node transmit at only the appropriate time.  Often a bus master can transmit essentially at whim, and subservient device(s) are only allowed to transmit in reply to specific queries from the master.  Of course the master should not transmit when it has just request a reply.

Also note that you cannot change the pin over to input mode when the last character is *loaded* into the UART, rather it has to stay in output mode until the last sent character has been clocked out onto the wire.

While putting a resistor between the transmit pin and the shared line could provide some theorectical safety against bus contention introduced by software errors, in practice the hardware will typically survive such conflicts during development, and having too large a resistor there may cause problems with signal quality.  If you are going to use a resistor, it should be sized for source termination of the line impedance, *not* for electrical protection.  You may also want a weaker pulling resistor to give the bus a known state when no one is driving it.  If this state matches the last driven one, the resistor won't have to overcome capacitance to "drive" the line, but rather merely "hold" it in the last driven position.

If you are using a device like the Uno which has only one hardware serial interface, you will have to decide if you are going to use the hardware interface at the cost of breaking the ability to use that to debug or upload sketches, or if you are going to use a software UART ("Software Serial" or its variants) on arbitrary digital pins.  If you do the later, it would be entirely possible to rework a library to receive and transmit on the *same* pin, rather than requiring two distinct ones.


body:
Does anyone know if there is a way to create a queue of some sort for arduino?

My project consists of simulating multiple traffic lights with crossing pedestrians on an Arduino breadboard. Since I need to assume the situation where on all sides are cars waiting + pedestrians having pressed the button, I needed to figure out a way to store these inputs into an array of some sort.

However, the problem with array I believe is that it doesn't allow me to shift the data to the left, so that the next one will be selected in the queue. Deleting the data inside an array would only merely make it null, which doesn't work.

Greatly appreciated if someone can help me by pointing to the right direction.

title: Creating a queue in Arduino?

Answers: 3

body:
Regarding how to “create a queue of some sort for Arduino”, about the first thing to settle is how many items may need to be queued.  On a typical personal computer with gigabytes of RAM, queue size often is not much of an issue ... one just allocates a few more megabytes whenever necessary.  On an typical Arduino, however, with a few kilobytes or few tens of kilobytes of RAM, use of dynamic (heap) allocation is risky unless you carefully analyze possible execution paths.

If you are ok with a fixed queue size, the next issue is what kind of queue, eg FIFO, LIFO, priority, etc.  The question's concern about a “shift the data to the left, so that the next one will be selected in the queue” issue suggests a FIFO (first in first out) queue is desired.  For this, a [circular buffer or circular queue](https://en.wikipedia.org/wiki/Circular_buffer) is a relatively-low-overhead method often used.  Using terms from the wikipedia article, Start and End pointers are maintained, marking next-data-out and last-data-in positions.  Via modular arithmetic or `if` tests, each of these pointers wraps to array front whenever it goes past the array end.   The queue is empty if `Start == End` (modulo N, if queue size is N) and full if `Start == End+1`.

If an interrupt-driven process can modify pointers asynchronously to the main thread of execution, then synchronization methods need to be used to ensure atomic updates of pointers.  (This is true for all kinds of queues, not just circular ones.)

If instead of a FIFO queue you need a priority queue, a [binary heap](https://en.wikipedia.org/wiki/Binary_heap) is easy to implement. Usually [Fibonacci heaps](https://en.wikipedia.org/wiki/Fibonacci_heap) and [binomial heaps](https://en.wikipedia.org/wiki/Binomial_heap) are not worth the extra trouble of implementing, except when you need efficient heap merging or secondary operations like decreasing keys of elements.  The [Summary of running times](https://en.wikipedia.org/wiki/Binomial_heap#Summary_of_running_times) section of wikipedia's binomial heap article shows the complexity of different operations across different heap structures.  Note that with Arduino RAM being so limited, a complexity difference like Θ(log n) vs Θ(1) is negligible; simplicity of code, leading to a compact implementation, is more important.

Note, also see [*QueueList Library For Arduino*](http://playground.arduino.cc/Code/QueueList) at arduino.cc.  This library apparently uses dynamic allocation.  It provides methods `push(), pop(), peek()` et al.  Also see [*QueueArray Library For Arduino*](http://playground.arduino.cc/Code/QueueArray) at arduino.cc, which provides the same methods as *QueueList*, plus `enqueue` and `dequeue()` as synonyms for `push()` and `pop()`.  Where *QueueList* uses lists to build its data structures, *QueueArray* uses arrays.

[*OsWrap* at arduino.cc](http://playground.arduino.cc/Code/OsWrap) is a heavy package (eg 15KB flash, 1.5KB RAM) that supports various message and priority queue structures.

Depending on your rationale for using a queue, [*Task Scheduler Library*](http://playground.arduino.cc/Code/TaskScheduler) may also be of interest.

As noted in Mikael Patel's comments above, [Cosa](https://github.com/mikaelpatel/Cosa) platform software includes a [Queue](https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh) class, which is a “Template class for ring-buffer for queueing data elements”, with usage of the class illustrated in an [Event](https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Event.hh) class, which in turn is used in a [Job](https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Job.hh) class.

body:
I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here:
[Queue](https://github.com/SMFSW/Queue)

I think you need FIFO implementation, but LIFO is also implemented in the lib & possibility to overwrite previous records when full.
It can handle any structure or data type (as long as it's size is fixed for memory allocation), defining a number of records in the queue, then you're good to go.

2 methods are implemented to interact with the queue, push() & pull().
I'll probably add a peek() later on if needed.

I also noticed this other FIFO only queue lib in the library manager when I commited mine: [MD_CirQueue](https://github.com/MajicDesigns/MD_CirQueue)

Hope this can help!

body:
I had an arduino project that I needed to build a queue for.

You can [download the source code][1] and copy into a file called `Queue.h` next to your arduino `project.ino` file.

Here is a simple interactive example (with the Serial monitor) to see how its used, make sure you set the `baud rate` to 115200 and `No new line`.

    #include "Queue.h":

    Queue<char> queue(10);

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

    void loop() {
      while(Serial.available()) {
        queue.push(Serial.read());
      }

      Serial.print(millis() / 1000);
      Serial.print(": ");
      int count = queue.count();
      if (count > 0) {
        Serial.print("Found ");
        Serial.print(count);
        Serial.print(" items.. '");
        Serial.print(queue.pop());
        Serial.print("' is the oldest. Next is.. '");
        Serial.print(queue.peek());
        Serial.println("'.");
      } else {
        Serial.println("Nothing to process...");
      }
      delay(2000);
    }

  [1]: https://github.com/sdesalas/Arduino-Queue.h/blob/master/Queue.h


body:
I am trying to set up several ATSAM-based AVR chips in a master/slave broadcasting arrangement. I want the master to be able to send a broadcast message to I2C address 0, and then for slaves to respond with different information. I have seen other implementations where this has been successful since I2C devices will typically self-arbitrate and if they are configured to back-off when arbitration is lost, the master can repeat its request and iterate over all addresses on the bus.

The challenge is that while I have Wire.beginTransmission(0) working to reach my slaves from the master, I cannot get Wire.requestFrom(0,6) to work. The slave acts as though no message had arrived in the reply case. This is in the reduced case of one master and one slave.

In the example below, changing RequestFrom to the slave address will work.

I am aware that on the SAMD architecture, ArduinoCore does not configure the SERCOM for I2C broadcasts so I made a one-line modification as follows to enable it:

    sercom->I2CS.ADDR.reg = SERCOM_I2CS_ADDR_ADDR( ucAddress & 0x7Ful ) | // 0x7F, select only 7 bits
                          SERCOM_I2CS_ADDR_ADDRMASK( 0x00ul ) |
                          SERCOM_I2CS_ADDR_GENCEN // added by JAG

My master code:

    #include <Wire.h>

    void setup() {

      Serial.begin(9600);
      Serial.println("Sketch start" );

      Wire.begin(); // join i2c bus (address optional for master)
    }

    byte x = 0;

    void loop() {

      Serial.print("-- Top of loop:" );
      Serial.println( millis() );

      Wire.beginTransmission(0); // transmit to device #8
      Wire.write("x is ");        // sends five bytes
      Wire.write(x);              // sends one byte
      Wire.endTransmission(true);    // stop transmitting

      // delay( 500 );

      uint8_t recvSize = Wire.requestFrom(0, 6);    // request 6 bytes from slave device #8

      Serial.print( "Got bytes: " );
      Serial.print( recvSize );
      Serial.print( "---> ");

      while (Wire.available()) { // slave may send less than requested
        char c = Wire.read(); // receive a byte as character
        Serial.print( "[") ;
        Serial.print(c);         // print the character
        Serial.print( "]" );
      }
      Serial.println();

      x++;
      delay(500);
    }

 My slave code:

    #include <Wire.h>

    void setup() {
      Wire.begin(9);                // join i2c bus with address #8
      Wire.onReceive(receiveEvent); // register event
      Wire.onRequest(requestEvent); // register event
      Serial.begin(9600);           // start serial for output
      Serial.println( "Starting up" );
    }

    void loop() {
      delay(500);
        Serial.print( "In top of loop (slave): " );
        Serial.println(millis() );
    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
        char c = Wire.read(); // receive byte as a character
        SerialUSB.print(c);         // print the character
      }
      int x = Wire.read();    // receive byte as an integer
      SerialUSB.println(x);         // print the integer
    }

    // function that executes whenever data is requested by master
    // this function is registered as an event, see setup()
    void requestEvent() {
      Wire.write("hello"); // respond with message of 6 bytes
      // as expected by master
      Serial.println( "<<<< Writing a response." );
    }

title: I2C broadcast and reply on Arduino M0+

Answers: 2

body:
If you broadcast data using Wire.send(data), the slaves would receive this in there onReceive handler but as far as I can remember, the I2C slave will not respond on a Wire.requestFrom(...) broadcast from the master.

Imagine x slaves responding all at the same time to the request...

body:
The I2C protocol supports bus arbitration only for masters sending (if more than one master in the bus starts sending at the same time). So, if any slave device would really respond to the General call address 0 with data, the data would geht corrupted if another slave would send data too. With this background it is reasonable, why an I2C slave device wouldn't respond to a request at the General call address.

If you have too many chips in the bus or don't want to address Thema directly due to another reason, you can send a trigger message to the General call address and let the other chips send their data as masters. Keep in mind, that in this case all involved chips must implement correct bus arbitration (and I'm not sure if the Wire library supports this).


body:
I want to write a variable value into a text file in the SD card and modify it while reading if needed.
I found a text reading code which reads a desired line in the text file.(not tested)

   //reading code

    #include <SD.h>

    int stepToLoad = 1;
    int endOfLineNumber = 0;
    int stepCount = 0;
    int stringIndex = 0;
    File configFile;
    char inputString [1280];
    char inputChar;

    void setup() {
      stepToLoad = 13;
      if (!SD.begin(36)) {
        return;
      }

      if (SD.exists("config.txt")) {
        configFile = SD.open("config.txt");
        getStepCount();
        getStepData();
        configFile.close();
      }
    }

    void loop() {

    }

    void getStepData() {

      if (configFile) {
        while (configFile.available()) {
          inputChar = configFile.read(); // Gets one byte from serial buffer
          if (inputChar != '^') { // define breaking char here

            inputString[stringIndex] = inputChar; // Store it
            stringIndex++; // Increment where to write next

          } else {
            endOfLineNumber++;
            stringIndex++;
            if (endOfLineNumber == stepToLoad) { //this is the correct line to load

              break; //break out of the "while" loop
            } else { //not the correct line to load, reset and continue

              stringIndex = 0;
            }
          }

        }

      }
    }

    void getStepCount() {
      if (configFile) {
        while (configFile.available()) {
          inputChar = configFile.read(); // Gets one byte from serial buffer
          if (inputChar == '^') { // define breaking char here
            stepCount++;
          }
        }
      }
    }

title: Arduino : How to write a variable value into a text file and modify it in the SD card?

Answers: 3

body:
As far as I know it is not possible to read a file and meanwhile change a value.

What normally is done is:

- Read the file
- Store it in memory
- Change the value in memory
- Write the file

However, since the SRAM memory is very limited, the following approach is better:

- For every buffer (512 bytes):
  - Read 512 bytes buffer
  - Change values in the buffer if needed
  - Write 512 bytes to another file
  - Until the end of the file to read is reached
- Remove the original file
- Change the name of the new file to the old file

body:
> How to write a variable value into a text file and modify it in the SD card?

This software design issue depends much on the chosen representation on file. In principle, there are two design dimensions. The first is textual or binary representation. The second is fixed or variable size records.

With textual representation (e.g. Serial.print) values are converted to text and stored on the file. The size of the record (e.g. line) depends on the number of characters needed for the value. New-line is often used as the record delimiter. To locate a specific record the file has to be scanned. There is no way to calculate the position of a record. When reading back the value the textual representation must be parsed and the internal representation in memory restored.

With binary representation (e.g. Serial.write) values are written directly from memory to the file. The size of the record is fixed as the size of a struct. Locating a specific record is easy; record index time record size. The SD library file.seek(position) is perfect to index the record. When reading the value back to memory there is no need for conversion as in textual representation.

It should be added that fixed size textual representation is also possible, e.g. make each line the same length by using a padding character (space, etc).

A text file with variable values is the more difficult as it is both textual representation and variable record. It is also the most inefficient as it requires compute power for the value representation conversions. The major advantage is that the text file can be generated with a ordinary text editor. No special tool or program is needed.

Binary file format with fixed records will require initialization.

Cheers!

body:
It was super complicated for me at first but I understand it now. I'll upload just the DS3231 Code with the SD card functionality

    #include <Wire.h>
    #include <DS3231.h>
    #include <SPI.h>
    #include <SD.h>

    DS3231 clock;
    RTCDateTime dt;
    File myFile;
    String fileName = "000000.txt";

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

      // Initialize DS3231
      Serial.println("Initialize DS3231");;
      clock.begin();

      // Set sketch compiling time
      clock.setDateTime(__DATE__, __TIME__);

      // Set from UNIX timestamp
      // clock.setDateTime(1397408400);

      // Manual (YYYY, MM, DD, HH, II, SS
      // clock.setDateTime(2016, 12, 9, 11, 46, 00);
    }

    void getName(){
      String date = clock.dateFormat("mdy", dt);
      fileName[0] = date[0];
      fileName[1] = date[1];
      fileName[2] = date[2];
      fileName[3] = date[3];
      fileName[4] = date[4];
      fileName[5] = date[5];
    }

    void sdCard() {
      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }

      Serial.println("initialization done.");

      getName();

      myFile = SD.open(fileName, FILE_WRITE);

      if (myFile) {
        Serial.print("Writing to file...");
        myFile.println("testing 1, 2, 3.");
        Serial.println("done.");
      }
      else {
        Serial.println("error opening file");
      }
    }

    void loop()
    {
      dt = clock.getDateTime();

      Serial.print("Long number format:          ");
      Serial.println(clock.dateFormat("H:i:s", dt));

      sdCard();
      getName();

      myFile = SD.open(fileName, FILE_WRITE);
      myFile.println("Testing 1...2...3...")

    }

So what I did here was initialize the variable for the text name with placeholders and I used the date in a 6 digit format. Both variables being a string, I can set the first position of the text name to be the first position of the date. So all values are replaced. Should be the same thing for an 8 digit text name, but after that there is a limit, not including the file extension.


body:
hello there my code is here.

    /* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

    /* Use a variable called byteRead to temporarily store
       the data coming from the computer */
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
      Serial.begin(9600);
    }

    void loop() {
       char a[8];
        int b;
       /*  check if data has been sent from the computer: */
      if (Serial.available())
      {
        /* read the most recent byte */
        byteRead = Serial.read();
        Serial.print(byteRead,HEX);
      }

  now when i send '12' from terminal, it prints 3132. means it is ASCII value. but i want to print 12. can you help me?? how to do it??

title: Convert serial value into hex using in Genuino zero

Answers: 2

body:
To convert Decimal or Integer value to Hexadecimal you can go this way..

    byteRead = Serial.read();  //Read your value
    myValue =  String(byteRead, HEX); //Convert it into Hexadecimal
    Serial.println(myValue); //Print in serial Monitor
    myValue1 = String(byteRead,DEC); //Convert it ino Decimal
    Serial.println(myValue1); //Print in serial Monitor

body:
There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.

The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.

Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').

The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.

Scanning the string requires skipping whitespace and then collecting characters until a whitespace.

The sketch could look something like this:

    void setup() {
      Serial.begin(57600);
      while (!Serial);
      Serial.println(F("Serial started..."));
    }

    void loop() {
      const size_t BUF_MAX = 16;
      char buf[BUF_MAX];
      char* bp = buf;
      char c;

      // Skip whitespace
      do {
        while (!Serial.available());
        c = Serial.read();
      } while (c <= ' ');

      // Scan token until whitespace
      *bp = c;
      do {
        while (!Serial.available());
        c = Serial.read();
        *++bp = c;
      } while (c > ' ');
      *bp = 0;

      // Print scanned token
      Serial.println(buf);

      // Convert to number and print
      const int BASE = 16;
      long val = strtol(buf, &bp, BASE);
      if (*bp == 0)
        Serial.println(val);
      else
        Serial.println(F("not a number"));
    }

This allows scan of hexadecimal numbers with possible sign (as defined by `strtol`). By changing the BASE to zero `strtol` will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by `strtol`(*bp != 0).

Cheers!