message:
How to restart USB subsystem?

I'm developing on the Arduino platform (ESP8266 with USB -> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.

As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.

I'm using Mac OS X Sierra.

body:
You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.

If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.

What can you do? Well, two things:

1. Use an adaptor that requests enough current for your needs (may be hard to find)
2. Power your circuit separately using another power source.

Of the two I would suggest external power.


sender: user

sender: assistant

body:
You're probably thinking of `kext[un]load`.

    sudo kextunload /Library/Extensions/SiLabsUSBDriver.kext
    sudo kextload /Library/Extensions/SiLabsUSBDriver.kext


message:
Switching between SPI Devices when one is an SD card

I'm using a USB Barcode scanner connected via a USB shield, I'm able to get the readings from the barcode using [this][1] example, After getting this readings, I'd like to save it to an SD card but the SD card won't initialize since the barcode also uses SPI, how can I deactivate the ICSP in order to activate the SD card? Or how to switch between multiple SPI slaves?

 [1]: https://github.com/felis/USB_Host_Shield_2.0

body:
with SPI there is an implicit slave select pin on each device that must be pulled low to enable the device.

Connect each slave select pin of the SPI device to their own unused digital pin on your arduino and keep it pulled high until you want to talk to the slave.

However not all SPI devices will properly put the MISO pin into high impedance when SS is pulled high so you may need to use a tristate buffer on that pin or use a multiplexer.

When adding your own tristate buffer (for example a HS125) you need to connect each MISO pin of the SPI device to the input of a buffer, the slave select is then connected to the output enable pin of the tristate. The outputs of the buffers can be connected together along with the MISO pins of the devices that do properly go high impedance to the MISO of the master.

When using multiplexers there are 2 options:

1. You can daisy chain 2:1 multiplexers by connecting the MISO of the device to the 0-input of the mux and the Slave select to the select input pin of the mux.

2. you can use a >2 multiplexer to select the correct MISO line based on the address of a set of S lines. Then with a decoder you can provide the actual SS signal to the SPI device. This way you only need 2 SS pins for 4 SPI devices.


body:
Refer to the schematic below for a visual explanation of what is explained in this thread regarding a tri-state buffer.  I have used this circuit successfully on a PCB.[![enter image description here][1]][1]
I got this schematic from:
© 2017 Vishnu M Aiea. www.vishnumaiea.in

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


message:
Analog output low voltage issue, how to troubleshoot

I have connected my arduino according to the schematics in the image, with a few additions.

**The setup**

1. A DC motor (water pump) drawing power from Vin, going to ground via a transistor based in A0 analog output. Between the transistor and A0 is a 270 ohm resistor. In parallel to the motors poles is a diode, for protection.

2. A 3,1" (4x20) LCD screen with an I^2C chip (draws 5V, A4 and A5 and GND)

3. A Potentiometer directly on the I^2C chip LED pins (replacing the jumper) - for control of the light intensity. (Vin and middle pin of pot, gnd unconnected)

4. A Potentiometer connected to A1, 3,3V and GND.

**Code description:**
Using the Timer and the LiquidCrystal_I2C library,
Once every other second the LCD is refreshed
Once every day the water pump is started with an analogWrite(A0, HIGH) and it runs for 1-60 seconds based on the potentiometer setting.

**The issue.**

It seems the output of A0 does not deliver enough voltage to trigger the pump. This is a new error, before I got the screen, it ran the pump fine.

I suspect one of three things. 1: I have broken something in the arduino power regulator, and the voltage outputs on analog pins are lower than they should be (or their ability to supply current) -> Must get new arduino. 2: I have somehow saturated the ground pin or there is a connection issue. 3: The LCD display is drawing too much current. (Leading to either 2 or 1, but won't be fixed by getting a new arduino)

**What have I already tried**

I have tried, with the arduino connected via mains to short it between 3,3V and the transistor base, and then it runs. So the transistor is OK, the pump is OK. I have tried to map the output to another analog pin to display the value of this pin while the program is running, and it does display a value while the pump is supposed to be running, so it is doing something. I have used a multimeter to measure the pins, but I really don't know what "normal" is so I decided to stop fiddling around with that. I have also tried using other analog outputs (excepting 4 and 5, they are claimed by the lcd I^2C logics)

Can anyone of you please give me some pointers in the right direction, to help me to determine the error in question? What should I try?

Disclaimer, due to having the normal issues of life, love and the fact that a day only has 1440 minutes, I usually only have time to work on my pet projects during weekends...

If this question is not relevant or poorly written, please let me know, I'll try to clarify (or delete it).

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

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

body:
why analogWrite? analogWrite parameter values are 0 to 255 (or 1023) so analogWrite(pin, 1) is close to 0.

analogWrite is PWM on digital ports and doesn't work on analog ports
[analogWrite reference][1]

use digitalWrite

  [1]: https://www.arduino.cc/en/Reference/AnalogWrite


body:
The analog pins are for analog **input** not output. You can only use them for *digital* output.

Change

    analogWrite(A0, HIGH)

to:

    digitalWrite(A0, HIGH)

`analogWrite()` can only be used on PWM capable pins (the ones marked with `~`). On any other pin it sets the pin HIGH if the analog value > 127 and LOW if the analog value <= 127.

Since you are writing HIGH, which is equal to 1, the output is LOW because 1 < 127.


message:
RFID access system with PN532 reader

I have a PN532, so it's capable of both reading and writing. I've used it for a few perfectly functional things, but I want it to authenticate based on the contents (for example 1024 bytes) of a tag.

I'd generate some pseudorandom data, possibly on my PC, and write that into each card, and use a checksum of that as the key.

Should I just stick with the standard authentication of tokens, or is this a worthwhile alternative method? The UIDs of the tokens are not interesting for authentication.

If worthwhile, what checksumming algorithms should I use? If not, would someone care to explain how I can program the memory of tokens, and how to use that in addition to UID for auth?

Thanks in advance.

body:
First off, you don't want to use a checksum for authentication.

A checksum can be thought of as a hash with a very small size. The smaller the size of a hash the less unique it is. The less unique it is the more likely it is that incorrect data will generate the same hash and authenticate someone it shouldn't.

For instance, a 32 bit checksum (hash) of 1kB data (8192 bits of information) is a 256-fold reduction in the uniqueness of the value. At 32 bits you get 232 unique values. With 8192 bits you get 28192 possible values. I can't calculate how many values that actually is, but as you can imagine there will be many billions of billions of combinations that would all equate to the same checksum.

If you must use a checksum then make it an actual recognised hash. For instance an MD5 (considered weak by today's standards) has 128 bits. SHA-256 has, as you would imagine, 256 bits.

However calculating these hashes on an Arduino is not a simple matter owing to a lack of memory. Not impossible, but not that easy.

If you're going as far as to use such large amounts of data for authentication and using heavy mathematical routines to create a hash you may as well go the whole hog and use a proper cryptographic key pair.

One method would be to encrypt the UUID of the card off-line and store the encrypted result on the card - that data would then be unique to that card and tied to it - you wouldn't be able to clone the card unless you could clone the UUID as well.

Then either the UUID is read by the Arduino and also encrypted using the same key and if the results match authentication succeeds. Or the encrypted value is decrypted by the Arduino and compared to the UUID to see if they match. Which you choose depends on if you have asymmetric or symmetric encryption (the former is more like a hash but requires the encryption key to replicate it whereas a hash doesn't).

You can also include other information with the UUID, such as the name of the card owner (for identification purposes), etc - as long as you are able to already know that data to create the cryptographic has to compare with what is on the card.


message:
Arduino Wire communication with MCP23008 GPIO pin expander to turn on an LED with a button press

I am using an Arduino Uno and an MCP23008 GPIO pin expander, I have a momentary button connected to GPIO 2 on the MCP23008 and an LED light connected to GPIO 1 on the MCP23008. What I want is for the LED to turn on when the button is pressed down, and off otherwise. The code I currently have is this:

       #include "Wire.h"       //import Wire library
       byte inVal;             //declare byte variable

       void setup() {

          Serial.begin(9600);
          Wire.begin();
          Wire.beginTransmission(0x20);   //MCP23008 i2c addr
          Wire.write(0x00);               //MCP23008 internal register addr for I.O.dir
          Wire.write(00000010);           //set all pins as output, except for #2 as input
          Wire.endTransmission();
        }

        void loop() {

          Wire.begin();
          Wire.beginTransmission(0x20);   //MCP23008 i2c addr
          Wire.write(0x09);               //MCP23008 internal register addr for GPIO access
          //Wire.write(0xFF);             //set all output pins to HIGH, commented out for now.
          Wire.endTransmission();
          Wire.requestFrom(0x20,1);       //get one byte of input input from MCP23008
          inVal=Wire.read();              //set pyte as variable

          //Serial.println(inVal,BIN);    //output byte to serial monitor, commented out for now

          Serial.println(bitRead(inVal, 1)); //output second bit from byte(1 or 0, for HIGH or LOW, depending on the press of the momentary button.
          if((bitRead(inVal, 1)==1))      //if the bit from the button is high,
          {
            Wire.beginTransmission(0x20);
            Wire.write(0x09);
            Wire.write(0xFF);             //then set all output pins as HIGH
            Wire.endTransmission();
          }

          else if((bitRead(inVal, 1)==0))  //if the bit from the button is low,
          {
            Wire.beginTransmission(0x20);
            Wire.write(0x09);
            Wire.write(0x00);             //then set all output pins as LOW
            Wire.endTransmission();
          }
        }

I don't know as much Arduino as I do Python, and I have even less experience with i2c connections and the Wire library, but this looks to me like it should be working.

The bit printed on the serial monitor is HIGH, until I press the button once, then it stays LOW forever until I modify and re-upload the code to the Arduino.
Not sure what's going wrong here. Anything helps, thanks.

body:
I see one major thing wrong at first glance:

      Wire.write(00000010);           //set all pins as output, except for #2 as input

That doesn't set GPIO 1 (which you call number 2 - counting starts at 0 not 1) to be an input, that sets GPIO 3 (number 4) as an input.  Numbers starting with `0` are octal, not binary. For binary the prefix is `0b`:

      Wire.write(0b00000010);           //set all pins as output, except for #2 as input

And then you read using:

    bitRead(inVal, 1)

which would have read GPIO 1 which is configured as an output.

So you have a switch on GPIO 1 which is an output, which you then drive high (causing a short internally which can damage the pin), and as a result you drive the pin HIGH internally. Now it's always high, so a read of the pin sees the HIGH you are driving from it. Hence it gets stuck at 1.

Fixing your IODIR write should help solve that problem.


message:
How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive]

I am working on an assignment that converts a reading of force into pounds and then finds the maximum and average of all the values received

This is my code:

    void setup()
    {

     // put your setup code here, to run once:

     Serial.begin(9600);

      // declare the outputs and inputs
      pinMode( 0 , INPUT);

      //figure out what pin the reading is going to be input to

      fsrReading = analogRead( 0 ) ;
      //the # is the same pin used to get input

      //or use analogRead ( # ), it depends if the pin input is on the analog side of the arduino

      // should this be under the while loop or here?

      //list functions here
      long ForceInPounds(long);
      long FindMax(long);
      long FindAvg(long);

      //declaring variables of functions
      FM = FindMax(new long);
      FA = FindAvg(new long);

            Serial.println("The max value is:");
            Serial.println(FM); //calls FindMax function

            Serial.println("The average value is:");
            Serial.println(FA); //calls FindAvg function

      }

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

     int counter1= 0;

      while (counter1< 100)
      //runs test 100 times

      //should I just make this a function? instead of embedding it in the void loop

     {
          Serial.print("Analog reading = ");

          Serial.println(fsrReading);

          //declaring variable of function used in this segment
          FiP = ForceInPounds(new long);

          Serial.print("Force in Newtons:");
          Serial.println(FiP); //calls ForceinPounds function

          counter1 ++;
      }

    }

    //FUNCTIONS

    long ForceInPounds(const long)
    // converts recorded voltage to resistance to conductance to force to pounds
    {
     fsrReading = fsrVoltage;

     if (fsrVoltage== 0)
     {
       Serial.print("No pressure");
     }
     else
     {
       fsrResistance = 5000.0 - fsrVoltage;
       //convert voltage to resistance
       fsrResistance *= 10000.0;
       fsrResistance /= fsrVoltage;
       fsrConductance = 1000000.0 ;

       //convert resistance to conductance
       fsrConductance /= fsrResistance;
       if (fsrConductance <=1000.0)
       //convert resistance to conductance
       {
         fsrForce = fsrConductance/80.0;
       }
       else
       {
         fsrForce = fsrConductance - 1000.0;
         fsrForce /= 30.0;
       }
       fsrPounds = fsrForce/4.45;

       //convert force to pounds
     }

     return fsrPounds;
    }

    long FindMax(long)
    {
      int counter2 = 0;

      while (counter2 < 100);
      {
        if ( fsrPounds > maximum)
        {
              maximum = fsrPounds;
              counter2++;
        }
        else
        {
              maximum = maximum;
              counter2++;
        }

      }
      return maximum;

    }

    long FindAvg (long)
    {
      long start = 0;
      //variable to begin avg function
      long avg;
      int counter3 = 0;

      while (counter3 < 100);
      {
        start = start + fsrPounds ;
        counter3 ++;
      }

      avg = start/100;
      return avg;
    }

What am I doing wrong? This is my first time working with Arduino.
Thanks

body:
This is most likely not what you want to be doing

    //declaring variables of functions
    FM = FindMax(new long);
    FA = FindAvg(new long);

And it is entirely incompatible with these definitions

    //list functions here
    long ForceInPounds(long);
    long FindMax(long);
    long FindAvg(long);

With the result that you pass a *pointer* to a `long` (ie, its address in memory), to a function which is instead expecting the *value* of a `long`.

However, it's going to be hard to propose a solution until you edit the body of the functions into your question.

There's probably no reason to use `new` here at all - let the functions allocate their own *temporary* variables on the stack, since they seem to return a value rather than a pointer.  Most likely even if this worked, the `new long` you create would be abandoned - ie, a memory leak.


body:
There are several fundamental problems with the code. It appears your understanding of function declaration, definition, and usage are not accurate.

This part:

      //list functions here
      long ForceInPounds(long);
      long FindMax(long);
      long FindAvg(long);

Is unneccesary.

`setup()` is not the place to declare function variables:

      //declaring variables of functions
      FM = FindMax(new long);
      FA = FindAvg(new long);

If your functions use variables internally, the place to declare them is within the function definition.

In your FUNCTIONS section, you start off defining this function:

    long ForceInPounds(const long)

The first `long` declares that the function will return a `long`, and the `(const long)` would normally declare what variable types your function accepts as parameters, as well as the name(s) of said parameters. You have only provided a type `long`, and a modifier `const`, but no name. It doesn't make sense to pass in a `const` variable anyway, as the `const` indicates the content of the variable will never change from the initial value. In your code, not only is the variable not named, it is not given an initial value.

Within that `ForceInPounds()` function, you start with:

      fsrReading = fsrVoltage;

which overwrites your initial `fsrReading = analogRead(0);` with an undefined value, as you have neither declared a type for `fsrVoltage`, nor given it an initial value.

Also, you call `analogRead(0)` once in setup, so it only captures the value once. The `fsrReading` variable is not continually updated with the analog reading. You have to keep calling `analogRead(0)` and storing it in a variable each time through your loop.

There are other problems with the code, but these are a few of the fundamental problems. There is no simple/quick fix to your code.

If you don't come from a C or C++ background, you may want to read a quick overview of them, at a minimum. Start with some of the Arduino example sketches and get a good understanding of how functions are defined and how they work.


message:
Communication with ESP, HTTP requests or WebSocket?

Here is my problem. I'm working on making a wifi addressable RGB LED (like WS2812b) controller, I'm using an ESP8266 as the hardware. I'm also creating a phone application for controlling the device and setting different modes. What I'm doing right now is that I communicate with the module by sending GET commands from my phone app. For example to change the brightness I send `http://192.168.4.1/I125I` Then on the ESP side the code is as follows:

    WiFiClient client = server.available();
      if (client) {
      String inData= client.readStringUntil('\r');
      if (inData.indexOf("I")!=-1){
     BRIGHTNESS=str2int(inData.substring(inData.indexOf("I")+1,inData.lastIndexOf("I")));
    }}

  It works, but I'm not sure if this way of sending data is efficient at all. if change colors too rapidly the ESP resets. I recently found another code that uses GET and POST commands but different methods are used, like the following

    server.on("/brightness", HTTP_POST, []() {
        adjustBrightness();
      });

Then inside adjustBrightness function brightness is adjusted. This way it looks more professional but Is it more efficient?

I recently bought a commercial [RGB LED controller][1] that uses ESP8266 as its core. I tried to see what the phone app sends to the controller using the [Drony][2] app. For my app I could see all the get command the app was sending

    192.168.4.1/I255I

    192.168.4.1/R200RG90GB76B

    ...

but for the commercial controller I just saw one connection, something like "157.10.12.10:5172"

Is this using websockets?
Is using websocket a better way? is it more robust?

I'm writing the code in Arduino IDE.

  [1]: https://www.amazon.com/SUPERNIGHT-Wireless-Controller-Working-Android/dp/B01JS0KEBW/ref=sr_1_5?ie=UTF8&qid=1487557438&sr=8-5&keywords=wifi led controller
  [2]: https://play.google.com/store/apps/details?id=org.sandroproxy.drony&hl=en

body:
> This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (`GET`) or as part of the body (`POST`).

> Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.

Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.


message:
Connecting Arduino Uno to a smartwatch via bluetooth

I have a U80 Smartwatch from Bluetooth Watch International, which has bluetooth function. It is meant to be connected via to my smartphone (and it works perfectly).

I also have an Arduino Uno board and a corresponding BLE ZS-040 bluetooth chip.

I need for my smartphone to be able to detect my Arduino board, so I can send data from a simple circuit connected to the Arduino board to the smartphone.

Basically, my circuit is meant to be a simple push button. When the button is pushed, and the circuit is closed, the Arduino board will send a signal to the smartwatch. This will cause the smartwatch to ring and vibrate, as if it is receiving a call. Then to turn off the ringing and vibrating, the user can simply 'answer the phone call', and it will stop.

From what I understand, (I'm very new to Arduino) I have to connect the Arduino board to the smartwatch first, which means I have to somehow get the board to be detected by my watch, which it's not doing yet, eventhough the bluetooth module is connected to the board.

Then the push button needs to send a signal to the watch. Which means the command {if buttonpush='1', send (receiving call)}, so when the button is pushed, the signal is sent and the watch acts as if it is receiving a call. Basically showing all the physical signs (eg. vibrating and/or ringing based on the watch's setting, showing 'answer/deny call', etc.). Btw, the push button is not to be held down. As long is the button is pushed and released once, the signal should be sent, and the watch will buzz until the 'phone call' is answered or denied.

1. I have absolutely no idea how to get the board connected to the smartwatch via bluetooth.
2. And while I have a rough idea on the push button circuit I need, I also need to send the signal for the watch to act like it has received a call.

Mainly, I'm looking for any help with coding here. If anyone can help with the physical circuit connections, that would be awesome too.

body:
HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).

The two are not compatible.

You will need a BLE module for the Arduino which is capable of running as a "Central Device".


body:
This isn't exactly an answer but I will like to share my experience after attempting a similar project for the past week.

I have an Arduino UNO and a HM-10 Bluetooth module that is capable of functioning in central mode. I referred to http://www.martyncurrey.com/hm-10-bluetooth-4ble-modules to setup.

I am trying to connect the Arduino UNO/HM-10 with a Hexiwear (http://www.hexiwear.com) bluetooth IoT development smartwatch that is capable of sending sensor data such as steps, heartrate, temperature etc. via bluetooth to a BLE central device.

The Hexiwear will generate a random 6 digit pin when you attempt to connect to it. It works with its own companion Android app and reads sensor data perfectly. Someone managed to pull in the hexiwear's sensor data to a Raspberri Pi via BLE here: https://mcuoneclipse.com/2016/12/19/tutorial-ble-pairing-the-raspberry-pi-3-model-b-with-hexiwear/comment-page-1/#comment-97375.

With my Arduino UNO, I managed up to the point were I could connect the hexiwear and it pops up to ask for the random 6 digit pin so that it could pair to my Ardunio.

And then I am stuck, because I know nothing about the Arduino UNO and HM-10 that can send the pin code back to the Hexiwear.

Here's where I thought might be useful:

1) Do you have the U80's BLE specifications. This is how much hexiwear's BLE specification looks like https://github.com/MikroElektronika/HEXIWEAR/blob/master/documentation/HEXIWEAR Bluetooth Specifications.pdf.

My Hexiwear wearable comes with source code. If I try hard enough I can probably hack it to make what I want to do possible.

2) Does U80 require pairing with pin code? I am stuck here in my project.

3) Is the library for your BLE chip capable to sending said BLE requests and responses to communicate with the U80? This is where I believe I am going to be stuck further.

Hope this helps in some ways.


message:
RF receiver becomes weakened after motor turns on

I recently bought a simple SMAKN 315MHz RF receiver and transmitter, and I got everything working so that the transmitter transmits the value of a joystick, and the receiver receives that and uses it to set the analogWrite() of a motor on a PWM pin.

However, the moment the motor turns on, the receiver just weakens tremendously. At that point it only gets a message when I stick the receiver right against the transmitter. I’m powering the arduino and motor with a 3.7v LiPo battery btw.

Any help? I’ve tried with a 9V alkaline and a 9V adapter and nothing significantly changed.

body:
That behaviour is to be expected. Motors are very noisy and cause massive amounts of interference in radio signals.

The best thing you can do is to try and suppress that interference. For this you will need three 0.1µF (100nF) ceramic capacitors.

One capacitor is connected between the terminals of the motor to reduce noise transferred down the wires (wires make good antennae). The other two connect between each of the terminals and the metal body of the motor.

The metal body of the motor then becomes a shield to trap the noise.

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

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


message:
Unplanned behavior with two power sources

I'm trying to control [this servo][1], and whenever I leave the Uno connected, via USB, to the PC, most of the time the servo barely moves, and sometimes jitters.

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

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

<!-- End schematic -->

I connected the oscilloscope to try to understand / solve my problem, and I see that the signal I send is the same whether or not the USB is connected. I measured the voltage over the 5V/GND and it's constant at 5V and doesn't dip/spikes. I tried with a pull-down resistor on the signal pin (don't know if it's a good idea) and it doesn't change anything.

If I unplug the battery, but keep the USB connected, the servo stays immobile, but I figure that's because the Arduino can't feed a servo, hence why I wanted to use an external power for it. The second power source is a [PowerBoost 1000C][2] with a LiPo battery.

As soon as I unplug the USB port, the servo just starts moving properly, so I figured it must be interference of some kind. I saw the accepted answer to [this question][3] and it has me doubt whether I should use a battery while it's plugged in, but surely there is a way. Would I kind of need to connect the GND of my circuit to the GND wire of the USB before it actually enters the Arduino?

I didn't post the code as it's basically just the swipe demo from the website, and because it works when on battery only.

Regards

  [1]: https://www.parallax.com/sites/default/files/downloads/900-00005-Standard-Servo-Product-Documentation-v2.2.pdf
  [2]: https://cdn-learn.adafruit.com/downloads/pdf/adafruit-powerboost-1000c-load-share-usb-charge-boost.pdf
  [3]: https://arduino.stackexchange.com/questions/21061/two-arduinos-one-power-source

body: Beginner error: As stated in the diagram, I connected the external source of power to the 5V pin, while it should have been connected to the Vin pin. /ashame


message:
Arduino SDFat Libray overwrites last value

I'm trying to create a comma delimited file using this [SDFat library](https://github.com/greiman/SdFat)

Calling this code creates my file

    const char Header[24]="Desired RPM,Output RPM\n";
    ...
    foo()
    {
      SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
      SpeedCache.write(Header);
      SpeedCache.sync();
    }
    ...

After running, I have a file containing
>Desired RPM,Output RPM'\n'

When I call the following function, I want it to add `int target` and `int reference` to the bottom of the file.

    bool SDClass::SetLine(SdFile Cache,int target, int reference)
    {
      bool good = false;
      char NewLine[32];
      Cache.seekEnd();
      sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
      Serial.println(good=Cache.write(NewLine));
      Cache.sync();
      return good;
    }

 On the first call, this works so for an input of `SpeedCache,50,100` I get
>Desired RPM,Output RPM'\n'
>
>50,100'\n'

However, if I then write an input of `SpeedCache,5,10` I get
>Desired RPM,Output RPM'\n'
>
>5,10'\n'

How do I adjust my function so that I will get:
>Desired RPM,Output RPM'\n'
>
>50,100'\n'
>
>5,10'\n'

body:
You just need to open the file in APPEND mode:

    SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

> O_APPEND
>
> The  file  is  opened  in append mode.  Before each write, the file offset is positioned at the end of  the  file,  as  if  with               lseek.

You should also pass your file around by *reference* so it doesn't keep creating new copies of the internal structure:

    bool SDClass::SetLine(SdFile &Cache,int target, int reference)


body:
How do you pass the file by reference?

```
SdFat sd;
SdFile DataFile;

isSD = DataFile.open(FileName, O_WRITE | O_CREAT | O_AT_END);
```


message:
Transfer serial data to struct variable in Arduino

I have declared a struct with some variables that right now are fixed, but one of the variables on the struct needs to be what the Arduino's serial port reads.

    struct testing_var
    {
        const char *name;
        byte key[32];
        byte pt[16];
    };

    static testing_var const test1 = {
        .name        = "Speck-128-ECB",
        .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                        0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
        .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                        0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    };

As you can see for how I have declared it, I'm trying to get a plaintext from the serial port and the Arduino should encrypt that. I have a function that does this encryption, but I can't quite figure out how to pass what the serial port reads to the struct.

    void loop() {

      if (Serial.available()>0) {
        var1 = Serial.read();
    }

I need to pass this *var1* as the variable *pt* in the struct. Any clues? I'm maybe missing something very obvious, but I don't usually work with structs.

**EDIT:**
I'm trying to assign the value read by the serial port to the struct by creating another function that goes like this:

    void setPlain(struct PlainText *myPlain, const char* thePlain){
        myPlain -> plaintext = the Plain;
       }
Then, in the *loop*, I use:

      if (Serial.available()>0) {
        var1 = Serial.read();
        setPlain(&PlainText, var1)
    }

I'm getting an error using this function, I guess that it has something to do with the type of variable I'm trying to assign, these values are in HEX, not in char. But I'm not really sure it that's it or what other workaround should I use.

body:
You read the serial port one char at time, and assign it to *test1.pt[i]*, where i is an index varying from 0 to 15.

And `test1` cannot be `const`, because you are going to modify it with the serial data.

Here is a test code showing how to do it.

    struct testing_var
    {
        const char *name;
        byte key[32];
        byte pt[16];
    };

    //  test1 cannot be 'const'
    static testing_var test1 = {
        .name        = "Speck-128-ECB",
        .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                        0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
        .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                        0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    };

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

    void loop() {
      Serial.println("Enter 16 chars:");
      //  Read 16 chars from Serial
      for (int i=0; i < 16;) {
        if (Serial.available()) {
          test1.pt[i++] = Serial.read();
        }
      }
      // Do something with the data, like print it.
      for (int i = 0; i < 16; i++) {
        Serial.print(char((test1.pt[i])));
      }
      Serial.println();
    }


message:
Changing Text Arduino inkShield

I have just received inkshield purchased from [Nerd Creation Labs][1], I stacked inkshield on my Arduino Mega and uploaded [THIS CODE][2] provided by the creator of inkshield,and it works pretty well.
I can print text ;)

Questions :

1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

Please help

Thank you

  [1]: http://nicholasclewis.com/projects/inkshield/
  [2]: https://github.com/NicholasCLewis/InkShield/blob/master/ArduinoLibraries/InkShieldMega/examples/SerialTextInkShieldMega/SerialTextInkShieldMega.pde

body:
> 1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

Sure you can.

> 2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

The top 700-odd lines of the code are the font. You just need to find a way of creating the same kind of data from your own chosen font.


body:
The fonts are the little bitmaps starting at line 50. Each 16 bit value is 1 column of the letter to be printed. There are 10 columns of pixels per character (the `rowsPerChar` value). The least significant bit is the bottom row.

So to change the font all you need to do is change those bitmaps.


message:
Alternative code for pinMode()?

In my code I need to set five pins to output mode. I have the pinMode() statements in my setup.

I am trying to make my Arduino code run a bit faster, and I came across a tutorial which swaps digitalWrite() for PORTB &= _BV(PB6) (high), and makes it run ~25 times faster.

I'm wondering if there's a similar type of substitution I can do for pinMode(), that will make it run faster as well? Or is pinMode() already a fast command, so I shouldn't worry about it?

Thanks

body:
The Arduino reference manual has all you need to know:

* https://www.arduino.cc/en/Reference/PortManipulation

The register you need is the `DDRx` register (Data DiRection X). Set a bit to 1 for output and 0 for input.


body:
yeah. the corresponding registers are DDRx.

with a little bit of coding, you can easily convert pinMode() to your own, say, mypinMode() that operates on the DDRx directly.

the datasheet is your best friend, as always.


body:
It isn't worth it for something done once, if you only do it in `setup`. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) *on a Mega* you can do this to set **output** mode:

      DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
      DDRG |= bit(PG5); // D4
      DDRH |= bit(PH3); // D6

For **input** mode you have to "and" in the ones-complement of the bits like this:

      DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
      DDRG &= ~(bit(PG5)); // D4
      DDRH &= ~(bit(PH3)); // D6

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from [the Arduino site](https://store.arduino.cc/usa/arduino-mega-2560-rev3)). The relevant part is this:

[![Mega pins D0 to D7][1]][1]

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).

The `bit` macro works similarly to the `_BV` one you mentioned in your question. It shifts `1` left the required number of bit positions to be in the right place.

---

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:

https://github.com/NicksonYap/digitalWriteFast

This uses various compiler tricks to detect if you are using a constant for `pinMode` and `digitalWrite` and converts them into the appropriate register manipulation. You just install the library and add `Fast` to the function names, eg.

    pinModeFast (2, OUTPUT);
    digitalWriteFast (2, HIGH);

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


message:
Why is CLK_FLASH separate from CLK_CPU?

The ATmega328P has a separate clock signal for Flash and EEPROM (CLKFLASH) than it has for the RAM (CLKCPU). Why is this?

body: It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.


message:
STM8 Development Board with Arduino IDE

I got one of these cheap STM8 boards from China and was hoping to find a way to use this with arduino code.
[![STM8 development board][1]][1]
Does anyone know of an arduino boot loader and board package that works with them ?

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

body:
There is a bootloader on those chips to slow serial programming. A much easier way to to get a stlink debugger.

There are also some packages that allow Arduino styled programming on those chips. I wrote one myself that runs on iar and I think at least one on sdcc.

Those chips are really nice.


body:
Start the Arduino-IDE. In File->Preferences, Settings tab, enter

https://github.com/tenbaht/sduino/raw/master/package_sduino_stm8_index.json

Open Tools->Board:...->Boards Manager

Find Sduino by typing 'sd' into the search line

Click on the list entry

Click on Install.

This link is more comprehensive

https://tenbaht.github.io/sduino/


message:
Is it possible to configure FRAM memory for use as stack and heap?

I'm using the Adafruit I2C FRAM breakout board with my Nano and it works as advertised, but every time I write a variable to this thing I have to use library function calls with addressing. This makes it run slower than I want it to, especially since I'm using the memory to keep camera pixel information and I need to process it quickly.

As user Majenko put it:

>A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
>
>A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
>
>So for a read and write it's 38+48 = 86 bits.
>
>Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
>
>At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
>
>If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

It's much faster to write entire arrays at a time, but I need to write the data int-by-int as the data is encountered, since my whole reason for using the breakout board was to avoid needing local buffer space.

So is it possible to somehow configure this so that my I2C bus writes to the FRAM memory autonomously just like it does with the stack/heap in the onboard SRAM memory? Because then I could just declare my arrays as normal and let the processor take care of it, and then I would be so happy.

body:
I don't have experience with FRAM, but below are some results with SRAM: 23LC1024 (128 KB SRAM with SPI). Tests have been performed with an Arduino Uno.

(I had to use an answer instead of a comment because of the (screenshot) table alignment.

As you can see, write/read of a page (32 bytes) is faster than other types, but it depends on the amount of bytes you have to write to use pages.

(Because I want to use reasonable complex structures, I decided to go for a microcontroller with more RAM because stack and heap space cannot be used from external SRAM).

[![Speed tests][1]][1]

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


body:
Yes it is possible to have c variables use external RAM. The [Atmel AVR FAQ][1] discusses this. It's also possible to have the heap and stack (not recommended but possible), use external RAM.

Bear in mind that having this dealt with autonomously is still going to take roughly the same amount of time as it's going to have to execute similar functions to the ones you list above, albeit without having to code the transactions.

Have you considered a mega, and cache 1-6k of data then transfer that all at once. Using SPI would be faster, even more so with 1-6k. You can have an SPI LCD and RAM off the same pins, they just need an additional digital pin for the second device.

  [1]: http://www.atmel.com/webdoc/avrlibcreferencemanual/FAQ_1faq_ext_ram.html


body:
**No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers**, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).

Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.

Finally, Arduino is not a  good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.


message:
Combining 2 IF statements, getting nowhere and pulling hair out! ;)

I`m new here so just wanted to say hi!

I have been messing about with Arduino now for about 2 weeks, picking and trying different sketches for a greenhouse project I need.

Trying all sorts with LCD, temperature etc.

But what I actualy wanted was just a simple multiple timer say setting for every hour 9-6 activate for 2 mins to turn on a misting system for my plants, and that is now what I present in the following sketch, simple enough and it works, I have just removed some of the timings to keep the code compact on here.

Now the tricky bit, I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold, thats where I`m running into issues.

If anyone can look over the code and advise me where to put "if(h < humLowTrigger){"

I have tried before the times, included it in each line of the times and after the times and still not working.

So all help and knowledge greatly appreciated.

Cheers for now Alan

    #include <Wire.h>
    #include "RTClib.h"
    #include "DHT.h"

    #define humLowTrigger 70
    #define DHTPIN 7
    #define DHTTYPE DHT22

    DHT dht(DHTPIN, DHTTYPE);

    RTC_DS1307 rtc;

    void setup () {

    Serial.begin(9600);
    dht.begin();
    Wire.begin();
    rtc.begin();

    pinMode( A2, OUTPUT);
    digitalWrite(A2, LOW);
    }

    void loop () {

    float h = dht.readHumidity();
    float t = dht.readTemperature();

    DateTime now = rtc.now();

    if (now.hour() == 15 && now.minute() == 5) {
    digitalWrite(A2, HIGH);
    }
    if (now.hour() == 15 && now.minute() == 8) {
    digitalWrite(A2, LOW);
    }
    if (now.hour() == 15 && now.minute() == 10) {
    digitalWrite(A2, HIGH);
    }
    if (now.hour() == 15 && now.minute() == 12) {
    digitalWrite(A2, LOW);
    }

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %");
    Serial.println();
    Serial.println();
    delay(2000);

    }

body:
If you want to do something when two or more conditions meets , use an *and* operator (&&), like this:

    if (h < humLowTrigger && now.hour() == 15 && now.minute() == 5) {
    ... do something ...
    }

If you have a lot of conditional statements, you can simplify:

    if (h < humLowTrigger) {
       if (... other conditions 1 ...) {
         do something 1
         }
       ...
      if (... other condition n ...) {
         do something n.
         }
    }

 In your specific case:

    if(h < humLowTrigger) {
      if (now.hour() == 15 && now.minute() == 5) {
        digitalWrite(A2, HIGH);
      }
      if (now.hour() == 15 && now.minute() == 8) {
        digitalWrite(A2, LOW);
      }
      if (now.hour() == 15 && now.minute() == 10) {
        digitalWrite(A2, HIGH);
      }
      if (now.hour() == 15 && now.minute() == 12) {
        digitalWrite(A2, LOW);
      }
    }

**Better version**

But there is a problem with the previous code, beacuse the mister **must** turn off no matter what the humidity level is.

    // Turn on only if humidity below threshold.
    if (h < humLowTrigger && now.hour() == 15 && (now.minute() == 5 || now.minute() == 10)) {
        digitalWrite(A2, HIGH);
      }
    }
    // Turn off always.
    if (now.hour() == 15 && (now.minute() == 8 || now.minute() == 12) {
        digitalWrite(A2, LOW);
       }


body:
In addition to LookAlterno's answer (which I upvoted), the last part can be reduced to:

    if ((h < humLowTrigger) && (now.hour() == 15)) {
      if (now.minute() == 5) {
        digitalWrite(A2, HIGH);
      }
      if (now.minute() == 8) {
        digitalWrite(A2, LOW);
      }
      if (now.minute() == 10) {
        digitalWrite(A2, HIGH);
      }
      if (now.minute() == 12) {
        digitalWrite(A2, LOW);
      }
    }


message:
Sine wave PWM Arduino Micro

I'm trying to generate a sine wave on my Arduino micro.
I used this code.

    int Pin = 9;

    void setup()
    {
     Serial.begin(9600);
     pinMode(Pin, INPUT);
    }

    void loop()
    {
     float something = millis()/10000.0;
     int value = 128.0 + 128 * sin( something * 2.0 * PI  );
     analogWrite(Pin,value);
    }

I have a low pass filter at the output of the pin to smooth the wave. The problem is : I get a nice square wave with a duty cycle from 0 to 100%, but not a sine wave. Ideally, I'd like to set a frequency of 10 Hz.
Can anyone tell me where I made a mistake ? Thanks a lot !!!

body: it is how PWM works. digital pins can do only 1 and 0.


body:
> Can anyone tell me where I made a mistake ?

put a lpf on the pwm output.


message:
How do I program the Arduino Primo Core using the Arduino Primo?

the Arduino Primo Core website (https://store.arduino.cc/usa/arduino-primo-core) says that I can program the Arduino Primo Core using an Arduino Primo.

I have no idea how to do this!

Can you do it through the Arduino IDE? Which pins on the Arduino Primo Core should I connect to which pins on the Arduino Primo?

Thanks for your help!

body:
instructions were on arduino.org. it is turned off now, but you can find them in Web Archive (without downloads)
[Arduino.org pages in web archive][1]

  [1]: https://web.archive.org/web/20170711122201/http://www.arduino.org/learning/getting-started/getting-started-with-arduino-primo-core


body:
Juraj's answer answered my question, however I've gone back since and found the link to be broken. Fortunately I saved the file so I'll summarise here for others:

1. Download the nRF52 platform using the Boards Manager:

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

2. Connect the Arduino Primo Core to the Arduino Primo using a SWD connector (J2 on Arduino Primo Core and J9 on the Arduino Primo):

[![enter image description here][2]][2]

3. Plug the Arduino Primo into the PC using a USB data cable.

4. Select "Arduino Primo Core" from the `Tools > Board` menu:

[![enter image description here][3]][3]

5. Select the corresponding port of the Arduino Primo from the `Tools > Port` menu:

[![enter image description here][4]][4]

6. Select the `Blink` sketch from the `File > Examples > 1. Basics` menu.

7. Upload the sketch. If the light blinks on the Arduino Primo Core it has worked!

  [1]: https://i.stack.imgur.com/ReyCA.png
  [2]: https://i.stack.imgur.com/l7lp5.jpg
  [3]: https://i.stack.imgur.com/rZ64Z.jpg
  [4]: https://i.stack.imgur.com/CRsqQ.jpg


message:
How much power can a proto board handle?

I have been working on a project where I will be powering an Arduino and some LED light strips (2 x 3 Meter strips w/ 30 LEDs per meter). I am powering all of it from a 5v 10amp power supply.

Currently I have split the power cable and have it running to the board and the LED's in separate runs.

As I move from a breadboard to a more permanent proto-board, it would be great to add a barrel connector onto the proto-board and just have a single plugin for power so I can easily disconnect it.

Will this cause any issues if all of the power comes from the proto-board? Thanks!

body:
There is no problem to have your power source coming from your protoboard to supply your arduino since your protoboard can gives to your arduino one of these possibilities explained [here][1].

  [1]: https://arduino.stackexchange.com/questions/39041/powering-an-arduino-with-more-than-5-v/39043#39043


body:
No, it's not practical do to that with protoboard of any form.

There are two reasons for this:

1. Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
2. To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.


body: A common way to solve this is to solder a wire onto the tracks on the proto-board.


message:
Open Parent Class as Child Class (SD Fat Library)

I'm currently using the [SDFat library](https://github.com/greiman/SdFat) and am passing a global `FatFile`

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

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

I if have a function that requires an `SdFile` type and I know that a given instance of `FatFile` is a valid `SdFile` what is the best way to reopen `FatFile F` as `SdFile J`?

Right now I'm doing:

    SdFile ActiveFile;  //Global Active File
    ...
    void SDRun (FatFile &RunFat)
    {
      SdFile RunRoot;
      RunRoot.open("/", O_READ);
      ActiveFile.close();
      ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
      ....

However, this only works when `RunFat` is in the root directory.

body:
If `RunFat` is an instance of `SdFile` you can just cast it:

    SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

`RunRoot` and `RunFat` are now the exact same file in the exact same state (no need to open it or anything) but seen as an `SdFile` not a `FatFile`.


message:
Inkjet Printer Robot Wheels

I'm newbie about Arduino.
Can i build arduino robot wheels using Canon/Epson Cartridge inkjet printer?

The idea is like Drawing Robot
[![enter image description here][1]][1]

but i want to use cartridge printer instead of using a pen.

so after searching, and it look like ZUtAPocketPrinter

[![enter image description here][2]][2]

The Drawing Robot is using Trinket Pro
And ZUtAPocketPrinter is using Arduino (don't know using Uno/Nano/etc)

Can I use Trinket Pro or what types of arduino that i can use (Uno, Nano)?

And what hardware, sensor that require to scan/measure size of the paper?

And if there is tutorial, please share the link.

  [1]: https://i.stack.imgur.com/Catpv.png
  [2]: https://i.stack.imgur.com/8XYKF.jpg

body:
Usually a robot uses 2 identical motors for drive in order to change directions or go straight.  Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head.  And usually they are not identical.  Making it difficult to build a useful robot.  Also, printers usually use [stepping motors][1].  Most people building their first (small) robot usually use [continuous servo motors][2].  This makes for an easy to build first (small) robot as seen in this picture:

[![enter image description here][3]][3]

  [1]: https://learn.adafruit.com/all-about-stepper-motors/what-is-a-stepper-motor
  [2]: https://learn.adafruit.com/adafruit-motor-selection-guide/continuous-rotation-servos
  [3]: https://i.stack.imgur.com/7NKJn.jpg


message:
No serial data from Adafruit GPS (on Arduino 101)

New [Adafruit GPS][1] connected to my Arduino 101 board.

When trying to use the RX/TX hardware serial (on digital pins 0 / 1), with a simple sketch (described by Adafruit) to output a serial response, I'm not seing anything in the serial monitor (9600 baud).

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-arduino -->

    // this sketch will allow you to bypass the Atmega chip
    // and connect the Ultimate GPS directly to the USB/Serial
    // chip converter.

    // Connect VIN to +5V
    // Connect GND to Ground
    // Connect GPS RX (data into GPS) to Digital 0
    // Connect GPS TX (data out from GPS) to Digital 1

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

<!-- end snippet -->

Wires connected as in the sketch, also tried swapping them out in case of faulty wire.

Went on to try TinyGPS++ default example code, across a variety of pins: 3,4 & 8,9 & 0,1.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-arduino -->

    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    /*
       This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). EDITED BELOW.
    */

    static const int RXPin = 8, TXPin = 9;
    static const uint32_t GPSBaud = 9600;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);

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

      Serial.println(F("FullExample.ino"));
      Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
      Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println(F("by Mikal Hart"));
      Serial.println();
      Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
      Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
      Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
    }

    void loop()
    {
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

      printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
      printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
      printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
      printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
      printInt(gps.location.age(), gps.location.isValid(), 5);
      printDateTime(gps.date, gps.time);
      printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
      printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

      unsigned long distanceKmToLondon =
        (unsigned long)TinyGPSPlus::distanceBetween(
          gps.location.lat(),
          gps.location.lng(),
          LONDON_LAT,
          LONDON_LON) / 1000;
      printInt(distanceKmToLondon, gps.location.isValid(), 9);

      double courseToLondon =
        TinyGPSPlus::courseTo(
          gps.location.lat(),
          gps.location.lng(),
          LONDON_LAT,
          LONDON_LON);

      printFloat(courseToLondon, gps.location.isValid(), 7, 2);

      const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

      printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

      printInt(gps.charsProcessed(), true, 6);
      printInt(gps.sentencesWithFix(), true, 10);
      printInt(gps.failedChecksum(), true, 9);
      Serial.println();

      smartDelay(1000);

      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));
    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
    {
      if (!valid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartDelay(0);
    }

    static void printInt(unsigned long val, bool valid, int len)
    {
      char sz[32] = "*****************";
      if (valid)
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay(0);
    }

    static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
    {
      if (!d.isValid())
      {
        Serial.print(F("********** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "d/d/d ", d.month(), d.day(), d.year());
        Serial.print(sz);
      }

      if (!t.isValid())
      {
        Serial.print(F("******** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "d:d:d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
      }

      printInt(d.age(), d.isValid(), 5);
      smartDelay(0);
    }

    static void printStr(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartDelay(0);
    }

<!-- end snippet -->

Serial is spitting out this for every update:

> No GPS data received: check wiring

GPS is on, and can see based on the fix LED that satellite fix has occurred in both tests – no difference in output. Wires checked.

Maybe suboptimal pin solder job, but can't see that it should give no signal?

[![Solder job][2]][2]

EDIT: After suggestions, re-soldered pinheader – still nothing in the serial prompt on hardware serial (pin 0,1), software serial (pin 3,4) and TinyGPS++ throws the same error (pin 3-4 + 8-9). Double-checked RX/TX order.

A colleague found an old [Ublox Neo 6-M GPS][3], I plugged it in and repeated the above with the same empty serial results, not sure what to make of this..

[![enter image description here][4]][4]

  [1]: https://www.adafruit.com/product/746
  [2]: https://i.stack.imgur.com/15y3s.jpg
  [3]: https://www.u-blox.com/en/product/neo-6-series
  [4]: https://i.stack.imgur.com/4OBUl.jpg

body:
Accidentally fixed it when booting up the board tonight – not sure what changed but the serial prompt is on fire.

Wires: 5V - VIN, GND – GND, TX – 8, RX – 9

**Code:**

<!-- language: lang-arduino -->

    #include <SoftwareSerial.h>

    // setup gps serial
    int gpsTxPin = 8;
    int gpsRxPin = 9;
    SoftwareSerial gpsSerial(gpsTxPin, gpsRxPin);

    void setup()
    {
      Serial.begin(9600);  //set monitor to 9600

      gpsSerial.begin(9600); //adjust for GPS unit

      Serial.println("Ready!");
    }

    void loop()
    {
      while(gpsSerial.available())
      {
        char c = gpsSerial.read();
        Serial.print(c);
      }
    }

**Excerpt from serial monitor:**

<!-- language: lang-none -->

    ...

    $GPVTG,248.75,T,,M,0.19,N,0.35,K,A*3F
    $GPGGA,231351.000,,,,,0,05,,,M,,M,,*7A
    $GPGSA,A,1,,,,,,,,,,,,,,,*1E
    $GPGSV,2,1,07,13,65,290,32,30,54,066,36,20,48,286,33,15,31,288,31*75

    ...


message:
Multiple timed functions (timing off)

Desired program:

I have 3 momentary push buttons and a 4-channel relay board with my Arduino Uno. The relays are connected to 2 sinks, a shower, and a pump. Each push button should turn the pump and its respective fixture on for 10 seconds. I used a time buffer to debounce the push buttons.

Problem:

The time in which the function stays on is inconsistent. Sometimes 10 seconds, sometimes 3 seconds. Additionally all the relays turn off at the same time even if they were started at different times. they should all be individually timed and the pump should stay on as long as any of the three other relays are on.

Wiring Diagram:

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

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

Code:

    //initialize and declare variables
    // Pins 10,11,12,13 will be connected to their respected relays
    const int pump = 13;
    const int relay2 = 12;
    const int relay3 = 11;
    const int relay4 = 10;

    //initialize pins 2,3,4 to be connected to the momentary push buttons
    const int buttonPin1 = 2;
    const int buttonPin2 = 3;
    const int buttonPin3 = 4;

    //these variables track the state of the buttons, low if not pressed, high if pressed
    int buttonState1 = LOW;
    int buttonState2 = LOW;
    int buttonState3 = LOW;

    //Initialize pin states for valve check
    int relay2State;
    int relay3State;
    int relay4State;

    long lastDebounceTime = 0; // the last time the output pin was toggled
    long debounceDelay = 100; // the debounce time; increase if the output flickers
    unsigned long previousMillis = 0;
    unsigned long previousMillis2 = 0;
    unsigned long previousMillis3 = 0;
    unsigned long runTime = 10000;

    void setup() {
      //set pins connected to the relays as outputs.
      pinMode(pump, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);

      //set push buttons as inputs
      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);

      //initialize the starting state of the relay pins
      digitalWrite(pump, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
    } // close void setup

    void loop() {
      unsigned long currentMillis = millis();
      unsigned long currentMillis2 = millis();
      unsigned long currentMillis3 = millis();
      //sample the state of the buttons
      buttonState1 = digitalRead(buttonPin1);
      buttonState2 = digitalRead(buttonPin2);
      buttonState3 = digitalRead(buttonPin3);
      //check to see if any valves are open
      relay2State = digitalRead(relay2);
      relay3State = digitalRead(relay3);
      relay4State = digitalRead(relay4);
      //filter out any noise by setting a time buffer
      if ((millis() - lastDebounceTime) > debounceDelay) {
        //sample the state of the buttons
        buttonState1 = digitalRead(buttonPin1);
        buttonState2 = digitalRead(buttonPin2);
        buttonState3 = digitalRead(buttonPin3);
        //check to see if any valves are open
        relay2State = digitalRead(relay2);
        relay3State = digitalRead(relay3);
        relay4State = digitalRead(relay4);
      }

      // if button1 has been pressed, let's toggle the pump and relay2 from off
      //to on for 10 seconds
      if (buttonState1 == HIGH) {
        digitalWrite(relay2, LOW); // turn relay2
        lastDebounceTime = millis(); // set the current time
      }
      if (currentMillis - previousMillis > runTime) {
        digitalWrite(relay2, HIGH); // turn relay2
        previousMillis = currentMillis;
      }
      //if button2 has been pressed, lets toggle the pump and relay3 from off
      //to on for 10 seconds
      if (buttonState2 == HIGH) {
        digitalWrite(relay3, LOW); // turn relay3 on
      }
      if (currentMillis2 - previousMillis2 > runTime) {
        previousMillis2 = currentMillis2;
        digitalWrite(relay3, HIGH); // turn relay3 off
      }
      // if button3 has been pressed, lets toggle the pump and relay4 from off to
      //on for 10 seconds
      if (buttonState3 == HIGH) {
        digitalWrite(relay4, LOW); // turn relay4 on
        lastDebounceTime = millis(); // set the current time
      }
      if (currentMillis3 - previousMillis3 > runTime) {
        previousMillis3 = currentMillis3;
        digitalWrite(relay4, HIGH); // turn relay4 off
      }
      // if any valve is open, turn the pump on
      if(relay2State == LOW || relay3State == LOW || relay4State == LOW) {
        digitalWrite(pump, LOW);
      } else {
        digitalWrite(pump, HIGH);
      }
    } // close void loop

Any help would be greatly appreciated. I think I'm stuck in the time buffer for the debounce and my time checks aren't updating right.

body:
In a program like this it rapidly becomes quite confusing with the variable names all being so similar. Because of this, this is a good candidate for creating a `class` to do the job for you. This is because you have sets of functionality and variables that are duplicated to do the same job with different settings (IO pins).

It would be a trivial matter to create a `class` that turns on an output for a specified amount of time:

    class TimedOutput {
        private:
            uint8_t _pin;
            uint32_t _started;
            uint32_t _runtime;
            bool _running;

        public:
            TimedOutput(uint8_t pin, uint32_t runtime) {
                _pin = pin;
                _runtime = runtime;
                _started = 0;
                _running = false;
            }

            void begin() {
                pinMode(_pin, OUTPUT);
                digitalWrite(_pin, LOW);
            }

            void start() {
                digitalWrite(_pin, HIGH);
                _running = true;
                _started = millis();
            }

            void run() {
                if (!_running) return;
                if (millis() - _started >= _runtime) {
                    digitalWrite(_pin, LOW);
                    _running = false;
                }
            }
    };

    // Create the object
    TimedOutput shower(10, 10000); // Output on pin 10 for 10 seconds
    TimedOutput sink(11, 3000);    // Output on pin 11 for 3 seconds

    void setup() {
        // Configure the pin
        shower.begin();
        sink.begin();
        pinMode(2, INPUT_PULLUP); // Button
        pinMode(3, INPUT_PULLUP); // Button
    }

    void loop() {
        // Start it if the button is pressed:
        if (digitalRead(2) == LOW) {
            shower.start();
        }

        if (digitalRead(3) == LOW) {
            sink.start();
        }

        // Do the checking for if it needs to stop:
        shower.run();
        sink.run();
    }


body:
Take a modular approach to it.

For example, break the functionality intwo two pieces.

Readbutton1() returns 1 if and only if button 1 has been pressed and it passed debouncing. There are tons of ways to do that.

Energizerelay1() is called to energize relay number 1 for 10 seconds. Again, there are tons of ways to do that.

Then you can integrate them all together in your loop.

Fairly easy. The key to any programming is to break down a task into individual modules and then reintegrate those modules together to perform the desired the task.

Coding those individual modules is often simple.


message:
Why don't these sketches produce a similar output?

I compiled the following two sketches with the compiler used by the Arduino IDE and ran them on an Arduino UNO (smd edition).
I'm using:

 - Arduino IDE v. 1.8.0
 - Arduino AVR Boards v. 1.6.20

1.

    void setup() {

      Serial.begin(115200);
      unsigned long a, b;
      //unsigned long c, d;

      a = micros();
      for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      b = micros();
      Serial.println(b - a);

      //c = micros();
      //for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      //d = micros();
      //Serial.println(d - c);

    }

    void loop () {}

2.

    void setup() {

      Serial.begin(115200);
      unsigned long a, b;
      unsigned long c, d;

      a = micros();
      for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      b = micros();
      Serial.println(b - a);

      c = micros();
      for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      d = micros();
      Serial.println(d - c);

    }

    void loop () {}

These were the outputs on the serial monitor:

1. `2452320`

2. `3332640
  3332704`

Why did each of the two `for` loops in the second sketch take roughly 33% more time to execute than the loop in the first one?

body:
The different time implies different (number of) instructions being executed. <s> This is most probably due to the crappy GCC compiler optimizations.

In the former sketch, probably the compiler manages to use only registers, which are very fast. In the second one, the compiler THINKS it needs 8 more bytes, and there are no registers left, so it uses the stack (internal RAM) to store some variables, which is slower. (still, the optimizer should realize that in fact it don't need more bytes, because a and b are not used after the first println()). To access to a SRAM location, you need a LOAD/STORE operation, which takes a longer time, with respect to an operation between registers (beside having to load the memory address to X, Y o Z).
Probably, the compiler is even crappier, because, instead of putting the rarely-used variables a,b,c,d on the stack, it puts i (which is always incremented) or other variables used in digitalRead().

Still, to explain where is the trouble (i.e. where compiler fails in optimizing the register allocation/usage), you should disassemble the object code. Use for instance Atmel Studio, which still uses GCC, but has a good debugger, disassembler and cycle-exact analysis.

Still, this is very strange, perhaps optimizations were not enabled the platform.txt of your arduino? </s>

EDIT:
Using Arduino 1.8.0, I tested the two sketches and analyzed the lss (generated using avr-objdump). The compiler optimizes a lot more the first code. Instead of making a CALL to digitalRead() (as it happens in the second sketch) it probably recognizes that such function is called only once on the code. Therefore it makes a rjmp to it. At the end of that function, there won't be a RET but a branch to the point where i is computerd and checked (actually i is not incremented, actually gets decremented and checked against 0).

In other words, even if the two codes are equal (except that the second sketch runs the same code twice), they are compiled (optimized) differently.


message:
HD44780 Extended non-display DDRAM?

According to page 10 of this PDF https://www.sparkfun.com/datasheets/LCD/HD44780.pdf

The HD44780 has enough DDRAM to operate an 80 character display. A 16x2 display has 32 characters meaning we have 48 characters of free DDRAM. Is there anything in the Arduino's LiquidCrystal library which allows direct access to this DDRAM space? The HD44780 datasheet says it can be used as generalised RAM.

body:
I haven't used that particular library but I have used the ddram and cgram as memory / buffets. So the feasibility is never in question.

The downside with this approach is speed and real estate. Those devices are slow by mcu standard. You then have to provision for the rw pin and the data pins - both read and writes. That's what you should check for in the library.

But it is workable for sure.


message:
Error Compiling to Board Teensy LC

I wrote a simple switch program using a teensy LC and transistors, but the Arduino compiler will not compile for the Teensy LC. And not for just my program, but any program, including the example programs included in the Arduino. I have tried compiling for other boards and they all compile fine. This problem was also replicated on another computer running Windows 10, I am running Windows 7, with the same error message. The error message and associated code is below, for reference.

    int led1 = 0;
    int led2 = 1;
    int led3 = 2;

    int input1 = 5;
    int input2 = 7;
    int input3 = 9;

    int bypass1 = 23; //output 1
    int toneStack1_1 = 22; //output 2
    int toneStack1_2 = 21; //output 3
    int bypass2 = 20; //output 4
    int toneStack2_1 = 19; //output 5
    int toneStack2_2 = 18; //output 6
    int bypass3 = 17; //output 7
    int toneStack3_1 = 16; //output 8
    int toneStack3_2 = 15; //output 9

    boolean bypass = true;        //idicators for which mode is active
    boolean toneStack1 = false;
    boolean toneStack2 = false;
    boolean toneStack3 = false;

    void setup()
    {
      pinMode(input1, INPUT);    //setting inputs
      pinMode(input2, INPUT);
      pinMode(input3, INPUT);

      pinMode(led1, OUTPUT);    //setting outputs
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);

      pinMode(bypass1, OUTPUT);
      pinMode(toneStack1_1, OUTPUT);
      pinMode(toneStack1_2, OUTPUT);
      pinMode(bypass1, OUTPUT);
      pinMode(toneStack2_1, OUTPUT);
      pinMode(toneStack2_2, OUTPUT);
      pinMode(bypass1, OUTPUT);
      pinMode(toneStack3_1, OUTPUT);
      pinMode(toneStack3_1, OUTPUT);

      digitalWrite(bypass1, HIGH);   //sets to bypass mode
      digitalWrite(bypass2, HIGH);
      digitalWrite(bypass3, HIGH);

    }

    void loop()
    {
      input1 = digitalRead(input1);    //reads inputs from pushbuttons
      input2 = digitalRead(input2);
      input3 = digitalRead(input3);

      if(input1 == HIGH && bypass == true) //Bypass to tonestack 1
      {
        digitalWrite(bypass1, LOW);   //turns off bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack1_2, HIGH);

        bypass = false;
        toneStack1 = true;
      }

    if(input2 == HIGH && bypass == true) //Bypass to tonestack 2
      {
        digitalWrite(bypass2, LOW);   //turns off bypass transistors
        digitalWrite(bypass3, LOW);

        digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2

        digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
        digitalWrite(toneStack2_2, HIGH);

        bypass = false;
        toneStack2 = true;
      }

      if(input3 == HIGH && bypass == true) //Bypass to tonestack 3
      {

        digitalWrite(bypass3, LOW); //turns off bypass transistor

        digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2
        digitalWrite(bypass2, HIGH);

        digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 3 transistors
        digitalWrite(toneStack3_2, HIGH);

        bypass = false;
        toneStack3 = true;
      }

      if(input1 == HIGH && toneStack1 == true) //tonestack 1 to bypass
      {
        digitalWrite(bypass1, HIGH);   //turns on bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, HIGH);

        digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
        digitalWrite(toneStack1_2, LOW);

        bypass = true;
        toneStack1 = false;
      }

      if(input2 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 2
      {
        digitalWrite(toneStack2_1, HIGH);   //turns on tone stack 2 transistors
        digitalWrite(toneStack2_2, HIGH);

        digitalWrite(bypass1, HIGH); //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
        digitalWrite(toneStack1_2, LOW);

        toneStack2 = true;
        toneStack1 = false;
      }

      if(input3 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 3
      {
        digitalWrite(toneStack3_1, HIGH);   //turns on tone stack 3 transistors
        digitalWrite(toneStack3_2, HIGH);

        digitalWrite(bypass1, HIGH);    //sets bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
        digitalWrite(toneStack1_2, LOW);

        toneStack3 = true;
        toneStack1 = false;
      }

      if(input2 == HIGH && toneStack2 == true) //tonestack 2 to bypass
      {
        digitalWrite(bypass1, HIGH);   //turns on bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, HIGH);

        digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
        digitalWrite(toneStack2_2, LOW);

        bypass = true;
        toneStack2 = false;
      }

      if(input1 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 1
      {
        digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack1_2, HIGH);

        digitalWrite(bypass1, LOW);   //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
        digitalWrite(toneStack2_2, LOW);

        toneStack1 = true;
        toneStack2 = false;
      }

      if(input3 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 3
      {
        digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack3_2, HIGH);

        digitalWrite(bypass1, HIGH);   //sets bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
        digitalWrite(toneStack2_2, LOW);

        toneStack3 = true;
        toneStack2 = false;
      }

      if(input3 == HIGH && toneStack3 == true) //tonestack 3 to bypass
      {
        digitalWrite(bypass1, HIGH);   //turns on bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, HIGH);

        digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
        digitalWrite(toneStack3_2, LOW);

        bypass = true;
        toneStack3 = false;
      }

      if(input1 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 1
      {
        digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack1_2, HIGH);

        digitalWrite(bypass1, LOW);   //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
        digitalWrite(toneStack3_2, LOW);

        toneStack1 = true;
        toneStack3 = false;
      }

      if(input2 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 2
      {
        digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
        digitalWrite(toneStack2_2, HIGH);

        digitalWrite(bypass1, HIGH);   //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
        digitalWrite(toneStack3_2, LOW);

        toneStack2 = true;
        toneStack3 = false;
      }
    }

And the error message:

    Arduino: 1.8.4 (Windows 7), TD: 1.38, Board: "Teensy LC, Serial, 48 MHz, Smallest Code, US English"

    In file included from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.h:34:0,

                     from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:31:

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp: In member function 'void IntervalTimer::end()':

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:87:20: error: 'IRQ_PIT_CH0' was not declared in this scope

       NVIC_DISABLE_IRQ(IRQ_PIT_CH0 + index);

                        ^

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\kinetis.h:5627:68: note: in definition of macro 'NVIC_DISABLE_IRQ'

     #define NVIC_DISABLE_IRQ(n) (*((volatile uint32_t *)0xE000E180 + ((n) >> 5)) = (1 << ((n) & 31)))

                                                                        ^

    Error compiling for board Teensy LC.

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

I'm at my wits end trying to figure this out. I have reinstalled the Arduino 1.8.4, reinstalled Teensyduino, installed previous version of Arduino, and rebooting my system. Nothing so far has worked. I feel like there is something I am missing with this, as it seems no one else has my problem, from what I could find. Any help would be appreciated.

body: I experienced a similar error.  Upon further research it seems to be a known issue.  I was able to compile using 1.8.2 and Teensyduino 1.36  I accessed 1.36 from downloading the zip file of the pjrc website in the upper right corner.  The Link was download website.  Then the path was pjrc_2017_04_04\teensy\td_136


message:
ADXL345 hangs the micro-controller as vibrations increase

I am using ADXL345 accelerometer with Adafruit_ADXL345 library for vibration measurement.

I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.

When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Values )[![Serial Plot Data][1]][1]

 I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations.
 Here is the code that I’m using.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    /* Assign a unique ID to this sensor at the same time */

    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
    int i=0;
    struct measure
    {
        int timestamp;
        float x;  // ACC in x direction
        float y;  //ACC in y direction
        float z;  //ACC in z direction
    };
    sensors_event_t event;
    struct measure measurements;

    int timestamp = 0;

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

      Serial.println("Accelerometer Test"); Serial.println("");

      /* Initialise the sensor */
      if(!accel.begin())
      {
        /* There was a problem detecting the ADXL345 ... check your connections */
        Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
        while(1);
      }
      accel.setDataRate(ADXL345_DATARATE_3200_HZ);
      accel.setRange(ADXL345_RANGE_16_G);
         pinMode(LED_BUILTIN, OUTPUT);
      delay(2000);
    }

    void loop(){

     accel.getEvent(&event);
       measurements.timestamp = timestamp++;
       measurements.x  = event.acceleration.x;
       measurements.y  = event.acceleration.y;
       measurements.z  = event.acceleration.z;

    if(measurements.timestamp%2==0)
      digitalWrite(LED_BUILTIN, HIGH);
      else
        digitalWrite(LED_BUILTIN, LOW);

      /* Sending the array with data through serial*/

      Serial.print(measurements.timestamp);
     Serial.print(",");
     Serial.print(measurements.x+0.06);
     Serial.print(",");
     Serial.print(measurements.y+0.7);
     Serial.print(",");
     Serial.println(measurements.z-10.10);
    }

Where does problem lie? How to resolve this issue?

Circuit Connections:
[![Circuit][2]][2]

  [1]: https://i.stack.imgur.com/pDamO.png
  [2]: https://i.stack.imgur.com/85KIS.jpg

body:
There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.

You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.

There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:

http://dsscircuits.com/articles/arduino-i2c-master-library

Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

---

Also you might try lower values for the pull-up resistors, like 4.7k.

---

So, my recommendations are:

* Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
* Summarize data rather than sending each reading
* Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.

[Saleae](https://www.saleae.com/) sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.


message:
I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)

I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.

All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups.
The ESP pins used are RX and TX, with 330ohms pull-ups.

Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

----------

Code (modified for readability)

ATmega slave:

    #include <Wire.h>

    const int ADDRESS = 56;

    void receiveEvent() {
     Serial.println(Wire.read());
    }

    void setup() {
     Serial.begin(9600);
     Wire.begin(MY_ADDRESS);
     Wire.onReceive(receiveEvent);
    }

    void loop() {
    }

ESP master:

    #include <Wire.h>

    const int DISPLAY_ADDRESS = 56;
    const int PACKET_SIZE = 1;
    const int SDA_PIN = 1;
    const int SCL_PIN = 3;

    void setup(){
     Wire.begin(SDA_PIN, SCL_PIN);
    }

    void loop() {
     byte packet[PACKET_SIZE];
     packet[0] = 'e';
     Wire.beginTransmission(DISPLAY_ADDRESS);
     Wire.write(packet, PACKET_SIZE);
     Wire.endTransmission();
     delay(2500;)
    }

ATtiny master:

    #include <Wire.h>

    const int DISPLAY_ADDRESS = 56;
    const int PACKET_SIZE = 1;
    // SDA = 0; attiny85 pin 5
    // SCL = 2; attiny85 pin 7

    void setup() {
     Wire.begin();
    }

    void loop() {
     byte packet[PACKET_SIZE];
     packet[0] = 'a';
     Wire.beginTransmission(DISPLAY_ADDRESS);
     Wire.write(packet, PACKET_SIZE);
     Wire.endTransmission();
     delay(1000);
    }

----------

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.

Am I doing something wrong, or is this simply not possible?

Are there any protocol alternatives for this design?
A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.

Thank you for your time!

body:
If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)

One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.


body:
The problem is in your implementation. If you REALLY need 2 masters there should be a way to make it work.

At the moment the problem that I can see is that both masters continually poll the I2C data lines, effectively this means that the data on the lines is all mixed up and scrambled together. What could do is have 2 wires connecting both masters. When one of the masters is writing to the slave pull the line high, the other master should read this line as high, and not write data to the I2C lines. When the line drops low, it should then take its turn to write to the AtMega. This method would ensure only one master is using the data lines at one time. The implementation is pretty rudimentary and fairly crude and I'm aware the ATtiny may not have enough pins for this.

The best way to solve your problem I think is to have the ESP8266 as your single master, with your ATtiny and ATmega as slaves. Make the ESP poll the ATtiny for its data/instructions it wants to pass to the Atmega, and get the ESP to pass on this data or instructions to the ATmega along with its own data and instructions. This should be a robust and reliable fix.


message:
Weird output from chained 74HC595 shift registers

EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.

I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two [74HC595][1] Shift registers.

I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.

Here is the schematic - with the exception that I moved the capacitor off of ST_CP (why would they put that in the tutorial?) to between power and ground:

[![Schematic][2]][2]

Here is my code:

    #define SHIFT_DATA 2
    #define SHIFT_CLK 3
    #define SHIFT_LATCH 4

    void setup() {
      pinMode(SHIFT_DATA, OUTPUT);
      pinMode(SHIFT_CLK, OUTPUT);
      pinMode(SHIFT_LATCH, OUTPUT);

      int address = 0b1111111111111111;  // Case 1
    //int address = 0b0000000000000000;  // Case 2
    //int address = 0b0101010101010101;  // Case 3
    //int address = 0b1010101010101010;  // Case 4
    //int address = 0b0101100110101110;  // Case 5

      shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
      shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

      digitalWrite(SHIFT_LATCH, LOW);
      digitalWrite(SHIFT_LATCH, HIGH);
      digitalWrite(SHIFT_LATCH, LOW);
    }

    void loop() {
      // none
    }

Here is a picture of my breadboard setup with Case 1 loaded:

[![Breadboard setup][3]][3]

And here follows my test cases.

 1. All 1's (1111111111111111). Looks good.
 2. All 0's (0000000000000000). Looks good.
 3. Repeated 01's (0101010101010101). Looks good.
 4. Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
 5. Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.

  [1]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT595.pdf
  [2]: https://i.stack.imgur.com/q7Pok.gif
  [3]: https://i.stack.imgur.com/akqZU.jpg

body:
I have [forum post about the 595 chip](http://www.gammon.com.au/forum/?id=11518) and [a question and answer about SPI](https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino/).

You can use SPI to do the transfer. This is faster and simpler than shiftOut. Also you need to bring the latch low **before** transferring the data.

Simple example sketch:

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

    #include <SPI.h>

    const byte LATCH = 10;

    void setup ()
    {
      SPI.begin ();
    }  // end of setup

    byte c;
    void loop ()
    {
      c++;
      digitalWrite (LATCH, LOW);
      SPI.transfer (c);
      digitalWrite (LATCH, HIGH);
      delay (20);
    }  // end of loop


body:
You should change your capacitors.

You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:

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

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


message:
WiFiSSLClient will not connect to servers with LetsEncrypt certificates

I'm trying to send data from an Arduino program to an app running on Google App Engine but `WiFiSSLClient.connect()` always returns false.

This is despite

 - the server being up and running;
 - the code working when the web app was on a different server.

The only possible explanation I can come up with is that the App Engine app uses a `LetsEncrypt` certificate while the other server was using one by another company.

    WiFiSSLClient client;
    if (client.connect(server, 443)){
        // Connected to server
    } else {
        // Failed to connect
    }

Does anyone have any solutions to this problem? I had a look at `WiFiClientSecure`; it has the ability to set the CA certificate in code but this seems like a bit of a pain.

body:
The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

1. Install the `FirmwareUpdater` sketch, as described on the [Arduino site][1].
2. Select *Tools -> WiFi 101 Firmware Updater*. Click on the *Add domain* button at the bottom, enter your domain and click *Upload Certificates to WiFi module*.
[![Adding a new domain][2]][2]

3. Upload the sketch to your Arduino. It should now connect to the server.

  [1]: https://www.arduino.cc/en/Tutorial/FirmwareUpdater
  [2]: https://i.stack.imgur.com/lF5Jk.png


message:
How do I calculate sampling rate of external ADC?

I am wondering if someone could explain this to me.

I want to calculate sampling rate of external ADC.
I am using [ADS8320][1] which has max sampling rate of 100kHz, with Arduino MEGA 2560.
SPI divider is set to 128, which makes SPI frequency 125kHz.
Baud rate is 115200 (I am not sure if this is important).

Thanks a lot!

  [1]: http://www.ti.com/lit/ds/symlink/ads8320.pdf

body:
Easy.

1. Based on your set up, figure out the spi speed.

2. Take a look at the adc datasheet, figure out it's frame of transmission . Aka how many pulses per frame / sampling.

3. The product of the numbers in 1 and 2 gives you the minimum time per frame. The inverse of it is the maximum transmission in your application. That speed is cap by the devices own max sampling rate (100ksps).

4. Your actual sampling rate will depend on your specific application but it should not go above the number obtained in 3.

5. You may need to factor in other timing requirements as well so read the datasheet carefully. But the gist is the same.


body:
To get an idea of the sampling rate write a loop that takes 10,000 measurements and time how long it takes. You have your sample rate, not perfect but gives you some idea.

    long start = millis();
    // the loop

    Serial.print( 10000000/(millis() - start) );
    Serial.println(" samples per second");