message:
Arduino to Beaglebone black

I have an Arduino uno3 which gets data from a digital caliper and shows the data in serial monitor. Now I should make a connection between this Arduino and my Beaglebone black through SPI to get the data sent from caliper in Beaglebone black. and I don't know what to do and how to create codes related to this purpose.

body:
Have a look at the first several links from googling for [*Arduino and my Beaglebone black through SPI*](https://www.google.com/search?num=50&site=&source=hp&q=+Arduino+and+my+Beaglebone+black+through+SPI+&oq=+Arduino+and+my+Beaglebone+black+through+SPI+&gs_l=hp.3...599.599.0.2291.2.2.0.0.0.0.179.326.0j2.2.0....0...1c..64.hp..0.0.0.0.aQHbtmYrhk4).  Here are a few comments on those first few links:

• [SPI - Beaglebone Black Master Arduino Uno Slave (forum.arduino.cc topic 446924.0)](http://forum.arduino.cc/index.php?topic=446924.0) – This page asks your question in more detail, and includes Beaglebone master code and Arduino Slave code.  However, the poster makes an egregious error in the Arduino code by saying `Serial.println("SPI");` within the SPI interrupt service routine.

• [Communicate Beaglebone Black and Arduino via SPI
(ulasdikme.com)](http://ulasdikme.com/projects/arduino/BBB_Arduino_SPI.php) – This page addresses your question in rather more detail, and apparently shows working code.  It also explains how to enable SPI in the Beaglebone device tree.  Note, this poster too makes an egregious error in the Arduino code by saying `Serial.println(c);` within the SPI interrupt service routine.

• [SPI communication: BeagleBone Black (as Master) to 4 Arduinos (as Slaves) (adurthi.com)](http://www.nagavenkat.adurthi.com/?p=479) – This page covers level shifting and device tree setup and provides ok code.  It seems to cover BeagleBone concerns nicely, and has ok Arduino code as well.

One or two of the above also make reference to Nick Gammon's excellent SPI pages:

• [SPI - Serial Peripheral Interface - for Arduino (gammon.com.au forum id=10892)](http://www.gammon.com.au/forum/?id=10892) – This page is where you should start if you have questions about how SPI works.  After you are familiar with SPI basics, scroll down to the “How to make an SPI slave” heading, and set up the master-slave example with two Arduinos.  When you have that working, you can substitute or add a BeagleBone as master.  Other code examples further down the page include  “How to get a response from a slave”, slave SS pin interrupt examples, SPI via USART, speed settings, SPI on ATtinys, sending data structures, and (under the heading “SPI under IDE 1.6.0 and later”), exegesis of SPI library methods.

• [Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329)](http://www.gammon.com.au/forum/?id=11329) – This page illustrates master-slave communication between two Arduinos, using one as a slave to forward information sent from a system being debugged.  Also illustrates use of I2C for similar purpose.  Note, [Debugging The Arduino With The SPI Interface Instead Of Serial.println() (utopiamechanicus.com)](http://www.utopiamechanicus.com/article/spi-debug/) is a follow-on article, by another author, about this debugging technique.


sender: user

message:
From Exploring Arduino Text

I am working thru the Exploring Arduino text mostly with success up until chapter 4. I have most of the parts required but for Figure 4-3 I used the following:

100nF Capacitor, (In place of 1uF Capacitor)

1N4007 Diode Rectifier, (In place of 1N4004 Diode)

S8050 NPN Transistor, (In place of PN2222 NPN)

DC Motor rated for 3V with a Reference Current of 0.35 to .4 Amps (Text lists "DC Motor")

Im aware that the Capacitor was undersized, Diode was a 4 series (so I assumed it was compatible), and the Transistor also the same but of a different manufacturer. Im also aware that the motor is underrated compared to the 9v input, but I didnt think this would cause a problem for a small time period.

My problem is that after about 10 seconds of running (both with the motor free spinning as intended, and sometimes just staying put but making a high pitched noise) the bread board started smoking. So, I disconnected everything and gave up for the day.

What was it that caused the breadboard to start smoking? Do you think I damaged my Arduino?

Link to companion site with diagrams: http://www.exploringarduino.com/content/ch4/

sender: assistant

body: If you used the 9 V battery as described in the diagram, but with a 3 V rated motor, then the motor starts smoking and you might damage it. Use e.g. 2 AA batteries with 1.5 V instead of the 9 V battery, then it should work without smoke and your motor will survive much longer.


message:
ColorPal Sensor

First off let me preface this my explaining my background. I am a mechanical engineering student and have some programming knowledge but it's limited. I'm trying to make a skittle sorter and I right now I'm working on the color identification part. I bought a ColorPal sensor for the project but I'm having trouble using it. I modified the demo a bit and it sort of works but not as well as I would like. Can someone please help me with my code or perhaps suggest an easier color sensor to use. Also I hope I paste my code correctly.

    #include <SoftwareSerial.h>

    #define sio      6           // ColorPAL connected to pin 6
    #define unused   255         // Non-existant pin # for SoftwareSerial
    #define sioBaud  4800

    // Received RGB values from ColorPAL
    int red;
    int grn;
    int blu;

    // Set up two software serials on the same pin.
    SoftwareSerial serin(sio, unused);
    SoftwareSerial serout(unused, sio);

    void setup() {

      delay(2000);

      Serial.begin(9600);
      reset();                    // Send reset to ColorPal
      serout.begin(sioBaud);
      pinMode(sio, OUTPUT);
      serout.print("=(00 $ m)!"); // Loop print values, see ColorPAL documentation
      serout.end();               // Discontinue serial port for transmitting
      pinMode(sio, INPUT);
      serin.begin(sioBaud);       // Set up serial port for receiving
    }

    void loop() {
      readData();
    }

    // Reset ColorPAL; see ColorPAL documentation for sequence
    void reset() {
      delay(200);
      pinMode(sio, OUTPUT);
      digitalWrite(sio, LOW);
      pinMode(sio, INPUT);
      while (digitalRead(sio) != HIGH);
      pinMode(sio, OUTPUT);
      digitalWrite(sio, LOW);
      delay(80);
      pinMode(sio, INPUT);
      delay(200);
    }

    void readData() {
      char buffer[32];

      if (serin.available() > 0) {
        // Wait for a $ character, then read three 3 digit hex numbers
        buffer[0] = serin.read();
        if (buffer[0] == '$') {
          for (int i = 0; i < 9; i++) {
            while (serin.available() == 0);     // Wait for next input character
            buffer[i] = serin.read();
            //Serial.print(buffer[i]);
            if (buffer[i] == '$')               // Return early if $ character encountered
              return;
          }
          //Serial.println("");
          parseAndPrint(buffer);
          delay(10);
        }
      }
    }

    // Parse the hex data into integers
    void parseAndPrint(char * data) {
      sscanf (data, "%3x%3x%3x", &red, &grn, &blu);  // Pull the R, G, and B values from the data string

      char buffer[48];                               // create a buffer
      //sprintf(buffer, "r = %4.4d    g = %4.4d    b = %4.4d", red, grn, blu);   //print the values into a buffer as formatted integers
      int sum = red + grn + blu;
      //Serial.println(sum);
      if (sum >= 120 && sum < 126) {
        Serial.println("Purple");
      }
      if (sum >=  238 && sum < 248) {
        Serial.println("Green");
      }
      if (sum >= 230 && sum < 235) {
        Serial.println("Red");
      }
      if (sum >=  330 && sum < 340) {
        Serial.println("Orange");
      }
      if (sum >=  420 && sum < 430) {
        Serial.println("Yellow");
      }
    }

body:
In `parseAndPrint`

You need to check the return value of `sscanf` to see if the function read the data.

The problem you are having is the difference between + and &.  The sensor is providing 3, 3 digit hex values (which should be sprintfed with x not %4.4d).  Adding these together isn't going to give you the write answer.  For instance $001001001 should give you a colour of r=1, g=1 and b=1.  If you add those together you get 3, but you really want 0x001 0x001 0x001.

You need to recalibrate you system and keep the three values separate and represent each colour by a minimum and max of those three colours and then check the value 3 values you receive are within the 3 ranges you have.

    // Define a structure (could be a class) to hold the data
    struct ColourData
    {
        int redMin;
        int redMax;
        int grnMin;
        int grnMax;
        int bluMin;
        int bluMax;
        char Name[30];
        ColourData (int rm, int rx, int gm, int gx, int bm, int bx, char* name)
          : redMin(rm), redMax(rx)
          , grnMin(rm), grnMax(rx)
          , bluMin(bm), bluMax(bx)
        {
            sprint(Name, "%s", name);
        }
    };

    // Define an array containing the data
    ColourData colours[MaxColours] = {ColourData(150, 200, 0, 20, 150, 200, "Purple")
                             , // Add some more

    // The code to check the colours
    for (int index = 0; index < MaxColours; ++index)
    {
        if (  red >= colours[index].redMin && red <= colours[index].redMax
           && grn >= colours[index].grnMin && grn <= colours[index].grnMax
           && blu >= colours[index].bluMin && blu <= colours[index].bluMax)
        {
           Serial.println(colours[index].Name)
        }
    }


message:
What is difference between analog and digital input and output, and when should i use anlog or digital (input or output)?

How should i determine whether to use input as analog or digital and same for output too?

body:
You will use digital pin modes when dealing with signals that are either "on" or "off", such as an LED, a switch, or another digital IC.

Analog inputs are used when you want to read the voltage potential of something. This is typically used to read analog sensors. Analog outputs are not really analog at all on the Arduino. Instead, the Arduino uses [something called PWM][1] to create a pseudo-analog signal.

You can read more about analog and digital here:
[https://learn.sparkfun.com/tutorials/analog-vs-digital][2]

  [1]: https://learn.sparkfun.com/tutorials/pulse-width-modulation
  [2]: https://learn.sparkfun.com/tutorials/analog-vs-digital


message:
MISO pin issue in SPI

I have interfaced sd card and ADS1262 (ADC module) with Arduino mega board and sharing the SPI control pin i.e. SCK, MISO and MOSI.
I have found that sd card is not initialized and ADS1262 is giving garbage value.
Now if I remove the MISO pin of sd card then ADS1262 is giving right (although SD card is not initialized.)
Vice-versa, if I remove the MISO pin of ADS1262, sd card is initialized and working perfectly (although ADS1262 is giving garbage value.)

Certainly, there is issue of MISO pin. How can I share MISO pin with both slaves so that both can work properly.

Any comments please.

I am using shifter - TXS0108E.

For SPI interfacing, I have tested two slaves with Mega board and found the below result when MISO is connected with both slaves and MISO pin is removing one by one from slaves.

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

From Above result, I thing it may be the problem of MISO pin.

I am not getting the idea, how to solve the problem in SPI interfacing in multiple slaves.

Schematic:

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

  [1]: https://i.stack.imgur.com/8KG1n.jpg
  [2]: https://i.stack.imgur.com/lDjxk.jpg

body: You probably want to use two SPI busses. If you absolutely need to use one bus, attach a digital out pin to each of the CS pins, one on the 1262 and one on the SD card. When you need to talk to one of the deviced, pull its CS line low to enable it.


body:
Some sd card modules which use 5v-3.3v logic level shifters may not have a proper circuit wich is very well explained in this guys blog

http://www.vishnumaiea.in/projects/hardware/interfacing-catalex-micro-sd-card-module

so until you don't make some changes in the sd card module you wont be able to have multiple slaves on your spi bus.


message:
Autolock transistor for powering Arduino

I have a portable project where I want to take care about batteries getting discharged.

Usually I just put a switch at the very beginning of my circuit that completely cuts off the electricity when switched off. The problem with this approach is that if you forget to switch it off your batteries will discharge.

So I was thinking about an approach that after some inactivity time cuts off the circuit (I want to completely cut off the electricity to minimize power consumption, so I'm not interested in sleeping modes or similar approaches).

So my approach consist in changing a switch for a regular push button that   enables the circuit when pushed, and then one of the arduino pins is used to lock the transistor until a function times out and the pin gets to a low voltage (see image)

In the arduino code I can just test a simple program that keeps the circuit closed for 10 seconds and then switches it off.

    setup() {
        pinMode(3,OUTPUT);
        digitalWrite(3,HIGH);
        delay(10000);
        digitalWrite(3,LOW);
    }

    loop() {
    }

For the transistor part I'm not sure what to use. I was thinking about using an motor driver L298 (which should work and also accepts some load for other electronics that I might have in the project)

However this looks like something that should already exist (either in a shield or maybe integrated in some Arduino variant).

Does anybody have experience with such an approach or a suggestion on any standalone transistor that would also do the job?

Any help is appreciated :)

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

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

body:
Here is a mock-up of what I usually do.

<!-- 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/7v8r0.png)

<!-- End schematic -->

Keep in mind that the resistors are just an example value: you'll have to make some calculations.

Now, M1 is a PMOS, while M2 is an NMOS. Both MOSFETs should be able to turn on and off with the voltages you can supply them (so look at their Vgs curves). Moreover the M1 mos will be the one where all the supply current will run, so you'll have to choose it wisely. The M2 mos will only have to supply a small current, so the smallest one is fine. Beware that if the Vin voltage is greater than the maximum Vgs voltage of M1 you'll have to add a resistor between M1 gate and M2 drain to form a voltage divider with R1.

The R4 and D1 are used if you want to detect a SW1 push (for instance to turn off the device). If you don't need this feature, remove them both.

The circuit works this way: when you push the button, a voltage (for instance 5V - 0.6V of D1) will come to the arduino Vcc. The arduino then should immediately bring up the pin. This will turn on M2, which in turn switches on the M1 transistor, thus bypassing the switch. When you remove it, the arduino stays powered.

When the arduino decides that it should turn off (either because you pressed the button again, or because it timed out, or who knows) it executes two instructions: one to pull down the pin and the other is `while(1)`. This prevents it to continue executing the program. The M2 transistor shuts down, the M1 gate floats to Vin and so it shuts down too.

You can find the transistor as discrete componetns (sometimes also in the same SOIC-8 package. Usually I use big pMOS (e.g. IRF9310 in SOIC8) and smaller nMOS (usually in SOT-23 case). I do this because I can easily solder them also on perfboards (SOIC8 single transistors have a lot of redundancy for pins, while SOT-23 ones can be mounted easily on 3 pads).


body:
If you would like an out-of-the-box solution, the [Pololu Pushbutton Power Switch](https://www.pololu.com/product/2808) is a lovely piece of hardware that lets the device turn itself off :)

Update: Adafruit also released a ["Low Power Timer Breakout"](https://blog.adafruit.com/2017/03/09/new-product-adafruit-tpl5110-low-power-timer-breakout/) that allows a device to be turned on automatically from 1s-2hr intervals, and then disable the power supply from the device once each run is done.

If you need less often than 2 hr intervals, you could increment a number in EEPROM in `setup()` each run and immediately re-enter sleep if the number doesn't match your desired value.


message:
Smooth breathing led

I am trying to make a simple breathing led circuit in which the intensity of the led varies between 0 and 255. I followed the [Fade tutorial on the Arduino site][1], which gives me what I want, but I notice that the change in brightness is much more noticeable when the intensity is at 0.

In other words, the brightness seems to be bouncing back from 0, rather than slowly gliding back up.

I tried mapping the value of the delay to brightness: `del = map(brightness, 0, 255, 10, 1);` but that did not do the job.

The mapping seems to work better when I use 30 instead of 10 as longest delay time:  `del = map(brightness, 0, 255, 30, 1);` but I think what I really need is to implement some sort of sinusoidal function to make transitions smoother, but I am really struggling with the math... Any suggestions?

Here is the code:

    int led = 9;           // the PWM pin the LED is attached to
    int brightness = 0;    // how bright the LED is
    int fadeAmount = 1;    // how many points to fade the LED by
    int del;

    // the setup routine runs once when you press reset:
    void setup() {
      // declare pin 9 to be an output:
      pinMode(led, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // set the brightness of pin 9:
      analogWrite(led, brightness);

      // change the brightness for next time through the loop:
      brightness = brightness + fadeAmount;

      // reverse the direction of the fading at the ends of the fade:
      if (brightness <= 0 || brightness >= 255) {
        fadeAmount = -fadeAmount;
      }

      // here I map the delay to brightness
      del = map(brightness, 0, 255, 10, 1);

      delay(del);
    }

  [1]: https://www.arduino.cc/en/Tutorial/Fade

body:
I'm not sure that it will work with a normal led. Some 20mA leds are still bright with only 1mA. The programmable RGB 5050 leds (for example the NeoPixels) are easier for a smooth visual brightness change.

The human eye is logarithmic for light brightness. Therefor a 10-based exponent or a less steep natural-based exponent can be used.

This will give a smooth brightness change:

    y = a * exp (-b * x * x);
    // x is incrementing in time.

If you really need a very smooth brightness change for a normal led, you might need an extra output with a higher resistor value to the same led, for a higher resolution at low brightness.


body:
There's two ways you could algorithmically do what you want, both with different results.

The first is with a sinewave:

    for (int i = 0; i < 360; i++) {
        analogWrite(5, (sin(i * 0.0174533) + 1) * 127));
        delay(3);
    }

Basically you work your way 360 degrees around a circle and take one axis (e.g., the vertical one), offset it so that the values are all positive (`sin` gives a value between -1 and +1), then multiply it to fit the full brightness.

This is the smoothest way of fading an LED, but it doesn't respect the different sensitivities your eye has to the different brightnesses (you see more brightness variation when it's dim compared to when it's bright).

The other method is much cruder but does respect those differences in sensitivities. This specific method only gives you 8 brightnesses as opposed to 256, but they are on a *log2* curve:

    for (int i = 0; i < 9; i++) {
        int v = (1 < 0; i--) {
        int v = (1 << i) - 1;
        analogWrite(5, v);
        delay(100);
    }

The theory of this one is it uses bit-shifting to gradually fill a byte with 1 from the least significant bit upwards.

When `i` is 0, this formula:

    int v = (i << i) - 1;

gives:

    1 << 0 == 0b00000001
    0b00000001 - 1 = 0b00000000

If `i` is 4, you get:

    1 << 4 == 0b00010000
    0b00010000 - 1 = 0b00001111

So you effectively end up with a set of values:

    0: 0
    1: 1
    2: 3
    3: 7
    4: 15
    5: 31
    6: 63
    7: 127
    8: 255


body:
1. Use a timer interrupt and in thee Isr change a pwm generator duty cycle. Or

2. Use a timer and set up two compare channels with a fixed offset. In the compare Isr, advance the math points forward and then flip an output pin. You will see the brightness goes up and down, whose speed depends on the offset.

No need for gamma correction.

edit: to demonstrate how the 2nd approach might work, here is a quick example.

It runs off of TIMER0, Output Compare Ch A and Ch B.

TIMER0 is set with a 256x prescaler, free running. Ch A is set to interrupt every LED_PR ticks, and Ch B is set to interrupt every LED_PR + LED_OFFSET ticks. they run the same user interrupt handler -> to flip a pin attached on LED_PORT / LED pin.

 tmr0_init(TMR0_PS256x);     //initialize tmr0 with a prescaler
 tmr0a_setpr(LED_PR);     //set up output compare ch a period
 tmr0a_act(led_flp);      //install user handler for ch a
 tmr0b_setpr(LED_PR + LED_OFFSET);  //set up output compare ch b period, with offset
 tmr0b_act(led_flp);      //install user handler for ch b
 ei();

and here is how it works in simulation:

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

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

the DC will go up then down, then up and then down, ....


body:
The three 255 values for RGB colour space  (255^3) is 16,581,375 colours. These include for brightness level.  The reason you're experiencing brightness issues is not to due with your arduino board but, with the RGB color space.  And by breathing, and i'm guessing here, that you are trying to transition thru RGB:

    void colorLoop() {

        static int Col1;
        static int Col2;
        static int Col3;

        static int C1;
        static int C2;
        static int C3;

      if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

      C1 = random(1, 3);
      C2 = random(1, 3);
      C3 = random(1, 3);
      }

      if (((C1 == 1) && (Col1 != 0))) {
          Col1 = (Col1 - 10);
      }
      if (((C2 == 1) && (Col2 != 0))) {
          Col2 = (Col2 - 10);
      }
      if (((C3 == 1) && (Col3 != 0))) {
          Col3 = (Col3 - 10);
      }

      if (((C1 == 2) && (Col1 != 250))) {
          Col1 = (Col1 + 10);
      }
      if (((C2 == 2) && (Col2 != 250))) {
          Col2 = (Col2 + 10);
      }
      if (((C3 == 2) && (Col3 != 250))) {
          Col3 = (Col3 + 10);
      }

    if (((Col1 <= 90) && ((Col2 <= 90) && (Col3 <= 90)))) {  //avoid black
       C1 = 2;
       C2 = 2;
       C3 = 2;
     }

        for (uint8_t i = 0; i < LED_COUNT; i++) {
         leds[i] = CRGB(Col1, Col2, Col3);
        }
        delay(100);
        LEDS.show();
      }

You may have more success or find it easier to use a HSL or HSV colour space. HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:

[https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors][1]

here is a similar effect using the HSV color spectrum:

    void rainbow_fade() {

     int ihue = 0; //some microcontrollers use HSV from 0-255 vs the normal 0-360
        ihue++;
        if (ihue > 255) {ihue = 0;}
        for(int i = 0 ; i < LED_COUNT; i++ ) {
         leds[i] = CHSV(ihue, 255, 255);
        }
          LEDS.show();
          delay(100);
      }

  [1]: https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors


body:
I thought about making a regular fade, with a logarithmic delay:
for an example:

    val=30*(1-((sqrt(brightness))/(sqrt(255))));
    delay(val);


body:
Just recently I published a blog post about this very topic at https://thingpulse.com/breathing-leds-cracking-the-algorithm-behind-our-breathing-pattern/

Turns out you get very pleasing results if you use `f(x) = e^sin(x)`. If you bring this down to 0 and have an amplitude of 255 the formula becomes [`f(x) = (e^sin(x) - 1/e) * (255/(e - 1/e))`][1]. Finally, you stretch `x` so you get a frequency of 12-20 breaths per minute: `x * PI/2`.

```lang-c++
#include <math.h>

void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  float val = (exp(sin(millis()/2000.0 * PI)) - 0.368) * 108.0;
  analogWrite(9, val);
}
```

  [1]: https://www.wolframalpha.com/input/?i=(e^sin(x) - 1/e) * (255/(e - 1/e))


message:
Build error on a phantom file that is not in my sketch, but somehow created in AppData/Local/Temp\build

on attempt to build  I get the following error

    C:\Users\gmyer\AppData\Local\Temp\build5d24776aeb7b2efec3566cec737c36d8.tmp\sketch\trash\bootloader.c:1:1: error: unknown type name 'This'

     This modules tests receiving vacuum data from the

     ^

The problem is that I have no file of that name, and no text that exactly matches that any where in my sketch.  and my sketch is located in C:\Software

I have tried rebooting, deleting the Temp directory, reverting to known working code.  but it keeps regenerating.

body: I found the offending file in a sub directory of the C:\Software sketch directory.  I had a subdirectory called trash, and the Arduino build found it from there, and put it in AppData then referenced the error from there.


message:
Using Air Quality Sensors like MQ135 to sense dust particles

**Using MQ135 (or similar) to sense dust particles in PM**

I was building a Air-purifier system. So, I need to monitor dust particles present in the air. Is it possible to use a gas sensor like the MQ135 to sense dust particles? Since, It can sense very small gas particles. Would it be possible to sense dust particles with it(MQ135 {Cheaper to buy}) or I need to buy a special optical dust sensor {Costly!}

body:
The MQ sensors can not be used to sense dust particles. They are [Electrochemical gas sensors][1] which are sensitive for certain gasses. They are not sensitive for dust particles. [Dust][2] is not a gas, but tiny solid particles.

  [1]: https://en.wikipedia.org/wiki/Electrochemical_gas_sensor
  [2]: https://en.wikipedia.org/wiki/Dust


message:
exit status 1 'mcpButtonState' cannot be used as a function

I keep getting this error and I don't know why.

mcpButtonState is an array, and I would like to change one of its values using a line like this:

    mcpButtonState(thisPin) = 0;
(it's inside of a for loop looping trough all my pins).
This is my complete code:

    #include "Arduino.h"
    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h
    #include <Wire.h>
    #include "Adafruit_MCP23017.h"
    SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
    DFRobotDFPlayerMini myDFPlayer;
    void printDetail(uint8_t type, int value);
    Adafruit_MCP23017 mcp;

    int mcpButtonPins[] = {0,1,2,3,4};
    int mcpButtonCount = 5;
    int mcpButtonState[5];

    int analogButtonPins[] = {0};
    int analogButtonCount = 1;
    int analogButtonState[1];

    int potiPin = A2;
    int soundVolume = 15;

    void setup() {
      mySoftwareSerial.begin(9600);
      //Serial.begin(115200);
      mcp.begin();
      for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
      {
        mcp.pinMode(thisPin, INPUT);
        mcp.pullUp(thisPin, HIGH);
        mcpButtonState(thisPin) = 0;
      }
      //ANALOG BUTTON SETUP
    }

    void loop() {
      int potiValue = analogRead(potiPin);
      int newVolume = (potiValue / 1023 * 30);
      if(newVolume != soundVolume)
      {
        soundVolume = newVolume;
        myDFPlayer.volume(soundVolume);
      }
      for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
      {
         if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 0)
         {
          mcpButtonState(thisPin) = 1;
          myDFPlayer.play((thisPin + 1));
         }
         else if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 1){}
         else {
          mcpButtonState(thisPin) = 0;
          }
      }
      //ANALOG BUTTON PLAYING
    }

body:
Use `[]` not `()`:

     if((mcp.digitalRead(thisPin) == 0) && (mcpButtonState[thisPin] == 0))

Note the use of `&&` instead of the word `and`.


message:
3D printer Arduino sketch

I'm building an automatic warehouse system using 3 nema17 stepper motor. My problem is to move the motors with precision, since I do not have any kind of encoder on the motor and so I cannot know the position of the axes. I tought that the system could be similar to a 3d printer, since neither 3d printers have encoder on the motor. Where can I find a sketch for Arduino of a 3d printer, to understand how they work? How do they move with such precision without any kind of sensor?

body:
With stepper motors you don't need any form of encoder. Only a limit switch.

A stepper moves in steps - you tell it how many steps to move. As long as you know where you started from (which is what the limit switch is for) then you can always know exactly where you are.

If you told the stepper to move 10 steps clockwise you know the stepper has moved 10 steps clockwise. If you then move 10 steps anti-clockwise, you will be back where you were.

All you need to do is count.


message:
DS18B20 - Thermometer and Sensor discrepancy (varying)

This is a follow-up question from [this other question][1]

I followed of the user Jot (get the sensor away from the sun and use a delay in arduino program)

But the results are still varying.

I recorded the temperature measured in the sensor, the temperature measured using a mercury thermometer and calculated the difference. The data was collected within 8 days

Here's the data (sorted):

    SENSOR THERM DIFF
    32.69 31.25 1.44
    32.00 30.25 1.75
    31.94 30.50 1.44
    31.87 30.50 1.37
    31.44 29.50 1.94
    31.00 29.00 2.00
    30.75 29.00 1.75
    30.50 29.00 1.50
    30.44 28.80 1.64
    30.31 28.90 1.41
    30.25 28.75 1.50
    29.87 28.00 1.87
    29.81 28.00 1.81
    29.81 28.00 1.81
    29.81 28.25 1.56
    29.75 28.20 1.55
    29.69 28.00 1.69
    29.56 27.00 2.56
    28.75 27.25 1.50
    28.69 27.00 1.69
    28.56 27.00 1.56
    28.44 27.00 1.44
    28.25 26.80 1.45
    28.00 26.50 1.50
    28.00 25.50 2.50
    28.00 25.00 3.00
    27.75 25.50 2.25

The average difference is around **+1.76°C** but that's not linear, and as you can see there are fluctuation in the same sensor value, 28.00 has three associated temperatures(25.0, 25.5, 26.5).

I'm not sure what to do, if the difference was regular I could simply subtract that from the sensor readings, but it seems that it varies a lot(Min: 1.37°C, Max: 3.00°C)

Any ideas?

  [1]: https://arduino.stackexchange.com/questions/35318/ds18b20-temperature-a-bit-off

body:
Can you buy a few more from other (more reliable) sellers ? Perhaps it is damaged. Did you accidently connect it wrong and it got very hot ?

There has been counterfeit DS18B20 sensors, but they were transistors that were re-labeled as DS18B20. Those didn't work at all.

You have not convinced me that you are only measuring the air temperature. Maybe there is still something nearby that causes it to get warmer. The 3 degrees difference is a lot. There must be a good reason for that, or else the DS18B20 is broken. How accurate is that mercury thermometer ?

I wrote before: "*To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water)*". That is what I did, out of curiosity. It turned out to be accurate.


body:
This isn't so much an Arduino question, but you are asking how to do better than a simple offset.  The next level of complexity is to do an offset and scale.

If this is the best data you can get from your setup, a better calibration than just an offset would be finding the best **offset** and **scale**.  You can do this with your data in R with:

    > x<- read.table(header=TRUE,text="SENSOR  THERM   DIFF
     32.69   31.25   1.44
     32.00   30.25   1.75
     31.94   30.50   1.44
     31.87   30.50   1.37
     31.44   29.50   1.94
     31.00   29.00   2.00
     30.75   29.00   1.75
     30.50   29.00   1.50
     30.44   28.80   1.64
     30.31   28.90   1.41
     30.25   28.75   1.50
     29.87   28.00   1.87
     29.81   28.00   1.81
     29.81   28.00   1.81
     29.81   28.25   1.56
     29.75   28.20   1.55
     29.69   28.00   1.69
     29.56   27.00   2.56
     28.75   27.25   1.50
     28.69   27.00   1.69
     28.56   27.00   1.56
     28.44   27.00   1.44
     28.25   26.80   1.45
     28.00   26.50   1.50
     28.00   25.50   2.50
     28.00   25.00   3.00
     27.75   25.50   2.25
     ")

    summary(lm(THERM ~ SENSOR,x))

... to get:

    Call:
    lm(formula = THERM ~ SENSOR, data = x)

    Residuals:
         Min       1Q   Median       3Q      Max
    -1.05217 -0.16263  0.08482  0.21809  0.47224

    Coefficients:
                Estimate Std. Error t value Pr(>|t|)
    (Intercept) -4.81422    1.60425  -3.001  0.00602 **
    SENSOR       1.10237    0.05369  20.533  < 2e-16 ***
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

    Residual standard error: 0.3816 on 25 degrees of freedom
    Multiple R-squared:  0.944, Adjusted R-squared:  0.9418
    F-statistic: 421.6 on 1 and 25 DF,  p-value: < 2.2e-16

... from which you can use the intercept and SENSOR parameters as an intercept and scale like:

    therm_estimate = -4.81422 + 1.10237 * sensor;

You could plot the data in R like:

    library(ggplot2)
    ggplot(x,aes(x=SENSOR,y=THERM))+geom_point() +geom_smooth(method='lm')

[![Plot of THERM vs SENSOR with best-fit line][1]][1]

Looking at the graph and data, your mercury thermometer is reading sometimes to the nearest 0.1th, and sometime to the 0.25th, and that is causing patterns in your data.  Maybe use a better, high-accuracy, calibrated lab thermometer if you want to be sure you aren't calibrating against something unreliable.

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


message:
Serial Monitor (user input)

I'm trying figure out how to make the serial monitor printing specific content based on the user input. For instance if the user has typed '1' it should constantly print ("Hello") and when user has typed '2' it should print ("Bye") and vice versa. I'm new to programming, so I would be grateful if any can help me with this.

      String readString;

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

           void loop()
           {

             if(Serial.available()>0)

             {
                char c = Serial.read();
                readString +=c;
                delay(2);

                       if (c == '1')
                        {
                         delay(1000);
                         Serial.println("Hello");
                         c = "";
                        }

                                     if (c == '2')
                                      {
                                        delay(1000);
                                        Serial.println("Bye");
                                        c = "";
                                      }
                 else
                {
                 readString= "";
                }
              }
            }

body:
You have most of what is needed but you have it structured incorrectly.

Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.

The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.

The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.

This code is untested:

    char cMode;

    void loop()
    {
      if(Serial.available())
      {
        char c = Serial.read();

        if (c == '1' || c == '2')
          cMode = c;
      }

      if (cMode == '1')
        Serial.println("Hello");
      else if (cMode == '2')
        Serial.println("Bye");

      delay(1000); // to slow down the loop?
    }


body:
Try out this code. It will helpful for you.

    char serialData;

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

    void loop()
    {
      if(Serial.available())
      {
        serialData = Serial.read();

        if(serialData == '1')
        {
          Serial.println("Hello");
        }
        else if(serialData == '2')
        {
          Serial.println("Bye");
        }
      }
    }


message:
Deprecated Conversion error

I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming
How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino: In function 'void updateState(byte)':

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

body:
> I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

    C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

To give a detailed answer the full prototype for DisplayInfo() is needed. The issue is that the literal strings are `const char*` and the function parameters are declared as `char*`.

The correct way to fix this would be to update DisplayInfo() so that the parameter types are `const char*`. The dirty fix is to cast the parameters in the call.

       DisplayInfo((char*) "RFID Scanner", (char*) "Starting up", HIGH, HIGH);

But I would not recommend that.

Cheers!


message:
How fast is a SD page read from a file?

For a project I would like to do, I asked a question about whether to use SD or EEPROM (see [Question][1]

I checked how much memory I would need without any restrictions which is like 2 MB (or more) so a SD card seems the best solution.

However, I'm a bit worried about the speed. In one of the answer comments is mentioned that 20 ms is an eternity for a microcontroller. However, I might need to do the following within 20 ms:

1. Parse a MIDI event (CPU power only, does not take long)
2. Read one or two SD pages (1/2 times block of 512 bytes)
3. Change/add/remove the MIDI event (CPU power only, negligible)
4. Send out MIDI data (barely no time, mostly hardware)

In worst case I can get like 10-20 MIDI events I need to handle within 20 ms. Especially for step 2 I don't know how much time it will.
My plan is to create a big file with a PC program to be stored on the SD card. Than I can let the Arduino read pages of 512 bytes from predefined places (with seek in a file).

I'm intending to keep the file open at all times and use seeks to go to the right place and read 512 bytes every time (assuming it doesn't matter to read 1 or 512 bytes since the page size is 512 bytes anyway).

So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

(btw, I want to try first on an Uno, but probably I will later go to a Mega (or add more SRAM to store temporary data).

  [1]: https://arduino.stackexchange.com/questions/34971/question-about-configuration-eeprom-or-flash

body:
> So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

Let us do the numbers: 50 * 512 = 25 Kbyte in 20 ms is 1.25 Mbyte/s. As the max speed for SPI is 1 Mbyte/s (on Arduino AVR, 16 MHz) we do not have to go any further. The answer is: No.

Cheers!


body:
Just for reference for others:

I received my micro card reader (from Catalex, v1.0, 11/01/2013) today and used a 1GB micrSD card.

The times measured ar at 4 addresses (2000, 120000, 40000 and 12000) again and are a seek to the address, and the reading of the bytes mentioned before the colon and the time after the colon in micros.

Result: Seek is 25..2500 micros depending on the file position, reading below 256 bytes is approx. 2-3 ms, reading 256 bytes 4-6 and 512 bytes 7-8  ms.

    Initializing SD card...card initialized.
    ---------
    Address: 2000
    seek    : 24
    read   1: 2276
    read   2: 2308
    read   4: 2344
    read  10: 2380
    read 256: 4780
    read 512: 7328
    -----------
    Address: 120000
    seek    : 2536
    read   1: 5008
    read   2: 5040
    read   4: 5084
    read  10: 5120
    read 256: 5312
    read 512: 7888
    ---------
    Address: 40000
    seek    : 2468
    read   1: 4940
    read   2: 4972
    read   4: 5016
    read  10: 5052
    read 256: 5252
    read 512: 7828
    ---------
    Address: 120000
    seek    : 2504
    read   1: 4992
    read   2: 5024
    read   4: 5060
    read  10: 5104
    read 256: 5296
    read 512: 7864


message:
How i can have one code for multi sensors

am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

body:
> am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

This could be considered a general question: Is it possible to merge several sketches and if so how?

The first step is to check pin conflicts: Are any of the sketches using the same pins (or resources)? If that is the case this needs to be resolved.

The next step is to check timing. Is is sufficient to run each loop() after each other or does the timing behavior also require changes.

The idea is then to simply "merge" the different setup() and loop() functions to a single setup() and loop().

In most cases, the timing behavior will leave no other choice than to rewrite the code.

There are a few tools (such as a [Scheduler][1]) that can be used but they require additional understanding of programming and nothing for the novice.

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler


body:
You have to keep some points in your mind:

(1) You have to ensure that pins must be not conflicting with each other. If you merge all sensor codes in one code then pins must be conflict. So you have to change pin number.

(2) If all sensors have separate working then make the function for all that sensors. It will very helpful for understanding and debugging the entire code.

(3) Don't try to merge all codes same time. Add one by one and also change pin number during that.


message:
How much current does an Arduino Mega draw from a LiPo battery (5,000 mAh)?

I went through Sparkfun's website on how to power a project because I wanted to calculate how much battery capacity I needed for my project. I saw an ATmega 328 micro-controller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me, I am new to this.

body:
You may be right that AtMega chip will draw relatively small amount of energy. But there are other components in the Arduino that will draw much more. (Voltage regulator as a best example.) In the end, the current drawn can (and will) be 10x larger.

And there is another problem, you have to know how much power will connected sensors draw.

What you can do is build your own 'less greedy' Arduino and use sleep abilities of AtMega chips.

Here are some links to go through:

https://openhomeautomation.net/arduino-battery/

https://circuits.io/circuits/1717500-power-rail-blocking-with-an-arduino/

http://www.gammon.com.au/power


body:
>  I saw an ATmega 328 microcontroller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

the datasheet provides the best guidance on that. typically 10ma - 20ma is fairly standard for 8-bit mcus. other components on the board, like opamps, or regulators, leds, may consume a little bit more so I would say 20ma - 30ma total is a good estimate for the board.

> So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me I am a newbie to this.

the datasheet showed 20ma typical so I would put the board to 30ma total. 5000mah/30ma = ...


body:
The important thing to realize here is that the capacity of the battery does not affect the amount of current drawn. Your Mega will draw the same whether it is connected to a 1000 mAh battery or a 5000 mAh battery. The larger battery will just last longer.

Tests on my Mega2560 Arduino show that (with no peripherals connected) it draws about 70 mA from a 7V supply, and slightly more (72 mA) from a 12V supply (the voltage regulator has to throw away some of the extra voltage as heat). *(However, see below)*

The exact amount it would draw in practice would be strongly correlated to what things you have connected. For example, LEDs, motors, shields, other devices.

I have a [page about power saving](http://www.gammon.com.au/power) that you might find useful if your objective is to minimize power usage.

---

## Edited to add more about power consumption

It appears that my initial claim that the current consumption goes up with an increase in voltage was wrong. With Majenko's help I made up a detailed set of automated tests, increasing the Mega2560 power input by increments of 200 mV, taking a reading from both the power supply and my multimeter, averaging each one over ten readings, and plotting the results. This is what I got:

[![Current vs Voltage plot][1]][1]

The two measurements seem to be consistently different by 0.2 mA. What this shows is that at 7V, the current consumption is 65.3 mA, and at 12 it is 64.1 mA, about a milliamp less.

I do, however, stick by my original assertion that the capacity of the battery will not affect consumption, and a larger battery will just last longer.

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


message:
How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement)

I want to get acceleration data from a [ADXL355][1] sensor.
[![enter image description here][2]][3]
[![enter image description here][3]][3]

My code:

    void readFIFO (){
    long data[3];
    byte data2 [9];

    digitalWrite(chipSelectPin, LOW);
    SPI.transfer( (FIFO<<1) | 1);
    for (int i = 0 ; i < 9; i++){
        data2[i] = SPI.transfer(0x00);
    }
    digitalWrite(chipSelectPin, HIGH);

    Serial.println("Byte data in hex and binary");
     for (int j = 0 ; j < 9 ; j++){
        Serial.print("element "+String(j) +": ");
         Serial.print(data2[j],HEX);
         Serial.print(" ");
         Serial.println(data2[j],BIN);
     }
     for (int z = 0 ; z < 3; z++){
        data[z] = ((data2[z*3]<<12) | (data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
     }
     Serial.println("concatenated values: ");
     for (int i = 0 ; i < 3 ; i++){
        Serial.println(data[i]);
     }
    }

Sample output:

    Byte data in hex and binary
    element 0: F9 11111001
    element 1: 1B 11011
    element 2: 51 1010001
    element 3: 0 0
    element 4: FD 11111101
    element 5: 90 10010000
    element 6: C3 11000011
    element 7: 2A 101010
    element 8: 20 100000
    concatenated values:
    -28235
    4057
    12962

The values are two's complement. Are these the correct values? If not what am I doing wrong?

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL354_355.pdf
  [2]: https://i.stack.imgur.com/Y6BSY.png
  [3]: https://i.stack.imgur.com/IJbdw.png

body: Since you've had no response to this I'll add my experiences with this chip. I'm not sure why you are reading the FIFO buffer. The chip provides three registers for each of the three axes. I simply read those in a loop. You can find my (still very crude) Python to read these at https://github.com/markrad/ADXL355. I hope it's some help to you.


body:
You need to sign extend the results.

e.g.
If the value is -1 your 3 byte values will be: 0xff ff f0 <br>
Combining these in to a single 32 bit value as you do gives you: 0x00 0f ff ff

Which is not -1.

What you need to do is check the most significant bit of the value and if it is set then set the top 12 bits.

    for (int z = 0 ; z < 3; z++){
      data[z] = (((long)data2[z*3]<<12) | ((long)data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
      if (data2[z*3] & 0x80)
        data[z] |= 0xfff00000;
    }


message:
How to create TCP server on Arduino UNO WiFi?

I'm currently trying to make my Arduino UNO WiFi work as a TCP host, so I can send him a TCP message and it sends a response.

I had no problem doing this on the Arduino Galileo Gen 2 using the EthernetServer, but since this one is using WiFi, EthernetServer isn't an option.

I can, however, run a web server, but that's not what I want.

So how do I make the Arduino receive, handle and respond to sent TCP/IP messages?

body:
For Arduino UNO Wifi, you have to use library "UnoWiFi-Developer-Edition-Lib". You can directly download and install it through library manager or can get it offline through the following link "https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib".

Hope this can help you.


message:
what is the use of Serial.begin(9600)

I mean what it does, why it is needed, what if we don't use it, similarly   for Serial.println(sensorValue).

body:
`Serial.begin(9600);` configures the UART interface and sets it to the right baud rate. If you don't to that you can't use the UART interface.

`Serial.println(sensorValue);` outputs the sensor value to the UART. If you don't use that you won't see the value of the sensor on the UART.

If you don't want to use the UART then don't use it. If you do want to use the UART then you must use the commands that control the UART.


body:
As the name suggests, `serial.begin(9600)` is a command you give to the Arduino to begin serial communication. I'm assuming you're a beginner. Anyway, as you might've seen on the IDE, there's a serial monitor. It outputs data that you configure it to output. It won't work unless you begin the serial communication using. The `serial.begin(x);` command. X is a variable baudrate, and I highly suggest going with 9600.
Okay, also, `serial.println(sensorValue)` is a command that the program gives to the Arduino to print the variable `sensorValue` to the serial monitor. Keep in mind that you can also print this through a Bluetooth module by connecting the tx to the rx and the rx to the tx pins. Hope this helped! :)


message:
Problems powering standalone arduino with USB powerbank

I've successfully migrated and ATMEL328P-UP microcontroller from the Arduino Uno Board to a breaboard, following these instructions: <https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard>. Everything is OK, the bootloader worked and code is already uploaded an running.

The ATMEL is connected to a pair of sensors, and all the system works using 3.3V. And here comes the problem: I'm using a 5V USB power bank to power up everything. When I make this connection:

*USB Power Bank @ 5V -> Arduino Uno board (without the microcontroller) -> 3.3 V Output from the board -> ATMEL/Sensors on the breadboard*

everything works just fine! Now I decided to replace the Arduino uno board with an LM317 voltage regulator which gives me the 3.3V needed. The connection is this:

*USB Power Bank @ 5V -> LM317 with 3.3 V output -> ATMEL/Sensors on the breadboard*

and nothing happens! Is as if there wasn't enough current to feed the ATMEL nor the sensors. I've checked the Vcc/GND pins of the sensors and the ATMEL and they're all getting the required 3.3 V, but for some reason the system seems to be OFF.

What could be happening? I'm sure the USB power bank is at full charge, so it should be able to supply enough current. Any suggestions?

Thanks guys!

body:
According to [the datasheet](http://www.ti.com/lit/ds/symlink/lm317.pdf), the LM317 needs an input voltage 3v higher than the output. Since 6.3<5, there's not enough margin for the LM317.

You can use an AMS117 LDO @3.3, which only needs an input of 3.9v to operate. I find [these modules](http://www.ebay.com/itm/181847233524) very handy. If the MCU has some tolerances, you can likely get away with using a diode or two in series with the 5v rail to drop it down; the actual forward voltage fluctuates slightly on load, but it will likely stay in the acceptable range for your MCU.

you can also use a switch-mode regulator, commonly sold as "buck converters" on ebay, to more efficiently reduce the voltage. This is the way to go over linear regulator like the 317 if you power your project from batteries or have concerns about heat. I go through a lot of [these style converters](http://www.ebay.com/itm/142147326064), and they seem to work very well.


message:
Arduino UNO WiFi "wifi shield not present"

I currently use the Arduino UNO WiFi, but when I try to use the [WifiChatServer][1] example, I keep getting the same error: `wifi shield not present`.

What am I doing wrong?

  [1]: https://www.arduino.cc/en/Tutorial/WiFiChatServer

body:
That example, and the library it comes with, are for the Arduino WiFi Shield. Not the Arduino Uno WiFi, which is an Arduino Uno with an ESP8266 strapped on the side through an I2C->UART converter chip.

You can't use that library, nor the examples that come with it. Instead you need to use the Uno WiFi library as stated in the FAQ for the board:

> If you are using the Arduino 1.7.x then you need to use the ArduinoWiFi.h library that it is already included in the IDE.
Instead you are using the Arduino 1.8.x then you need to download the UNOWiFiDev.Edition library from Library Manager.


message:
How to execute three functions at the same time?

How to implement **three functions**, which can **execute in the same time** (function of input random variables)?

body:
No single processor can do more than one thing at a time. The best you can hope for is that each function runs for a short time only and gives the processor to the next one, giving the illusion that there is more than one thing happening at once. This is called **multi-tasking** or **multi-threading**.

There are some libraries that will do this for the Arduino (search "RTOS Arduino" or "Arduino multitasking"), or you can write each functions using the principles of **Finite State Machine** programming to achieve the same effect.


body: You can implement three functions but you can't able to execute them same time.


body:
> How to implement three functions, which can execute in the same time (function of input random variables)?

Micro-controllers such as the AVR used on Arduino boards have only one processing core but there are many hardware modules (ADC, UART, SPI, TWI, Timers, etc). Using these it is possible to achieve several "functions" at the same time, i.e. pure concurrency.

Some examples, while waiting for ...

 1. ADC (analogRead) there are over 100 cycles
 2. SPI (spi.transfer) there are 16 cycles
 3. UART (Serial) is actually already concurrent with buffering and ISR's.
 4. The same goes for I2C (twi).

These cycles can be used to interleave different functions or improve performance (e.g. pre-fetching, pipe-lining).

Another example; using direct port read it is possible to read the state of several pins at the same time.

With simple collaborative multi-tasking it is possible to context switch between several functions (tasks) on delay or yield. This can be done with a [scheduler][1].

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler


body:
> How to implement three functions, which can execute in the same time (function of input random variables)?

have three executors / arduinos, one for each function.


body:
If the result of each function can be expressed as a single byte (i.e. an integer between 0 and 255) then you could:

- Connect 3 shift registers (e.g. 74595 ic) to 3 pins on your Arduino
- Assign one pin to each function
- Use the shiftOut function to output the result of each function one bit at a time on its relevant pin
- Use a 4th pin connected to all 3 shift registers as a common latch - when this pin is set HIGH the outputs from the 3 shift registers will all change at the same time.


message:
Is there any way to use a JTAG programmer with the Arduino IDE?

I am doing a lot of work with custom boards I've designed with the ATSAMD21G. I'd like to get away from using USB to program my boards since the USB port takes up space on the PCB and consumes extra pins. Is there any recommended way to configure the Arduino IDE to simply dump out the compiled program into a JLink debugger, much like the Atmel Studio IDE can?

body: The IDE makes a .hex file which you can then program onto your chip with a suitable programmer.


body: For a one-click upload, you can make a custom [hardware definition](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification) that calls any executable of your choosing.


message:
Blink 2 LEDs one at a time every x seconds

Newbie here - literally opened my Arduino about 3 hours ago. I have been able to code 2 LEDs to blink randomly, but what I want to do is have one of the two blink every 10 seconds.

My current code:

    void setup() {
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
    }

    void loop() {
      // set 2 random on/off values
      byte on4 = random(2); //returns a random choice of 0 or 1
      byte on5 = random(2);

      //Write the value of each variable to the pins.
      digitalWrite(4,on4);
      digitalWrite(5,on5);
      delay(500);
    }

I know I have to do something to the loops, I just can't figure out what.

body:
Choose if you want to keep pin 4 or 5.
Remove every reference to the other.

Move the declaration of the remaining pin outside of the loop, before the setup function. Ex: byte on4;

inside setup, assign a value (1 or 0) to the surviving pin. Ex: on4 = 0;

inside the loop, change the value of the pin. EX: on4 = !on4;

digitalWrite changes the state of the pins driving the LEDs.
Remove the one you do not want.

delay expresses how long the system waits, in milliseconds.
Change accordingly.

    byte on4;

    void setup() {
      on4 = 0;
      pinMode(4, OUTPUT);
    }

    void loop() {;
      on4 = !on4;
      digitalWrite(4,on4);
      delay(10000);
    }

This should work, but I have not tested it.


body:
Try out this code. It will helpful.

    const int kPinLed = 4;      // LED at pin 4

    void setup()
    {
      pinMode(kPinLed, OUTPUT); // LED as OUTPUT
    }

    void loop()
    {
      digitalWrite(kPinLed, HIGH); // LED ON
      delay(10000);                // 10 Sec delay
      digitalWrite(kPinLed, LOW);  // LED OFF
      delay(10000);                // 10 Sec delay
    }


body:
You need to split the logic into 2 parts. One part will select the pin that you want to blink and the other will blink the pin.
I'll show how you do this using delay() but, clearly, it would be better to use the BlinkWithoutDelay methods of counting time so the processor can do something else. This code is untested and is set up so that you can just add pins to the ledPin array with no other changes and it will always work properly.

    uint8_t ledPin[] = { 4, 5 };  // Arduino pins with the LEDs

    #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

    void BlinkOne(uint8_t pin)
    {
      digitalWrite(pin, HIGH);
      delay(5000);
      digitalWrite(pin, LOW);
      delay(5000);
    }

    void setup(void)
    {
      for (uint8_t i=0; i<ARRAY_SIZE(ledPin); i++)
        setMode(ledPin[i], OUTPUT);
    }

    void loop(void)
    {
      uint8_t thisPin = ledPin[random(ARRAY_SIZE(ledPin))];  // select which pin

      BlinkOne(thisPin);  // blink that pin
    }


message:
Char transmission using Virtualwire RF signal

This is a really basic problem, but I haven't been able to resolve it myself and would really appreciate the help.  So I've been struggling for a few weeks now to set up RF communication between two arduino uno chips.  I have the transmitter and receiver hooked up to 5V supply, with the data pins connected to digital pin 4.  My code looks like this:

Transmitter code:

    #define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
    #define ledPin 13        //Onboard LED = digital pin 13

    unsigned int data = 0;  // variable used to store transmission data

    void setup(){
      pinMode(rfTransmitPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600);
    }

    void loop(){
      digitalWrite (rfTransmitPin, HIGH);
      data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
      Serial.println(data);
      digitalWrite (ledPin, HIGH);
      delay(2000);

      digitalWrite (rfTransmitPin, LOW);
      data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
      Serial.println(data);
      digitalWrite (ledPin, LOW);
      delay(2000);
      }

Receiver code:

    #define rfReceivePin 4  //RF Receiver pin = digital pin 4
    #define ledPin 13        //Onboard LED = digital pin 13

    unsigned int data = 0;   // variable used to store received data

    void setup(){
      pinMode(ledPin, OUTPUT);
      pinMode(rfReceivePin, INPUT);
      Serial.begin(9600);
    }

    void loop(){
      data=digitalRead(rfReceivePin);    //listen for data on Digital Pin 4

       if(data = HIGH){
        digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
        Serial.println(data);
      }

      if(data = LOW){
        digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
        Serial.println(data);
      }
    }

This should be really simple, but for some reason I'm reading a continual HIGH signal from the receiver module.  I'm trying to sort out the basic functionality of the RF tx-rx pair before developing code to send a char using the Virtual Wire library, but I can't even get it to function at this level.  Since my code is so basic I'm convinced it must be a hardware issue and I'm not sure what I'm doing wrong.  Any suggestions?

body:
VIf you using Virutalwire try exemple in the library.
You can't send simple digitata data with Rf.
Best Regards Mikael

[link Virutalwire][1]

  [1]: http://www.airspayce.com/mikem/arduino/VirtualWire/index.html


message:
SSD1306Ascii Library

Is there any way to add Inverse Text color function into SSD1306Ascii library like which is available in ssd1306 adafruit library ?

body:
Yes, you can edit the library yourself, or copy its functions to your sketch and modify them.

You can also use another library, like u8g2.


message:
Run exe or apk on Arduino

how to run exe file or apk file on Arduino UNO?

Please suggest me any way to execute both file. Thank you.

body: You cannot.  An APK is an Android package, and an EXE is a Windows executable.  Neither can run on an Arduino,


message:
Why is my circuit working only when I touch it?

I have connected digital pin 2 of arduino to the circuit as shown:
[![pin 2 to 1kOhm resistor to base of 2N222 transistor. Emitter to -ve of 9v battery. Collector to -ve of LED, +ve of LED to 330Ohm resistor, resistor to +9v][1]][1]
The problem is that the LED is not turning on normally its only turning on when I touch anything on collector side of circuit. What seems to be the reason? Seems like grounding problem as its turning off when I don't touch my legs to ground.
[![turns on when I touch it][2]][2]

Thank you in advance.

  [1]: https://i.stack.imgur.com/SbENc.jpg
  [2]: https://i.stack.imgur.com/DL3Fw.jpg

body:
Sounds like you have guessed it: although it's very hard to say from those photos, it doesn't look like you have the circuit grounded.

Connect a ground from the Arduino to the black wire from the battery.


message:
How to convert macros for Arduino code?

I have a piece of code I'd like to make Arduino editor friendly. The code is written in C and contains macros the Arduino IDE can't deal with. Is it a good idea to turn those macros into functions?

    #define AN221_EXECUTE_Low cbi(PORTA, PIN0)  //drive EXECUTE low
    #define AN221_PORb_High  sbi(PORTA, PIN1)  //drive PORb high
    #define AN221_ACTIVATE  bit_is_set(PINA, PIN2)  //sense ACTIVATE high
    #define AN221_NO_ERROR  bit_is_set(PINA, PIN3)  //sense ERRb high i.e. no rror
    #define AN221_ERRb_Input outp(0xEB, DDRA)  //make uP drive ERRb
    #define AN221_ERRb_Output outp(0xE3, DDRA)  //make uP sense ERRb

body:
> Is it a good idea to turn those macros into functions?

it depends.

macros are fast, but lack type checking.

functions offer type checking but incur overhead.

whether one is better than the other depends on your priorities.


message:
I have a problem uploading blink

I am uncertain what a serial monitor does when I try uploading blink.  I get:

    problem uploading to board avrdude stk500_recv910 programmer is not responding

body: You have probably not chosen the right COM port. Try picking a different COM port, if using USB cable.


message:
How to run TCP socket server on Arduino Uno WiFi?

## 2017-03-23 update

I still don't know why it works so well on Yún. Maybe it has a better antenna? Anyway, I've returned Uno WiFi and got a SparkFun ESP32 Thing. Unfortunately, it has the same problem as Uno WiFi. To fix it I've switched from TCP to UDP. It made a world of difference: servos are very responsive now. UDP is OK for my use case: I can send the state of the whole system in each message and lost messages or messages arriving out of order are not a big problem.

## Original question

I want to control servos over WiFi with high precision and low latency. I managed to achieve this using TCP socket communication with Arduino Yún. I want to repeat this with Arduino Uno WiFi, but I can't find example code for socket communication. I connected to the board using telnet but servo output is jerky — as if there was a `delay` after each `servo.write` call.

How can I run a TCP socket server on Arduino Uno WiFi in a way that
allows for fast low latency communication?

## Longer description

I experimented with controlling servos over WiFi using an Arduino Yún board that I borrowed from a friend. I connected a MG92B servo to pin 9, 5V, and GND. I start a TCP socket server on the Arduino and send angle values from a Python script dozens of times per second. It works smoothly.

Encouraged by this experiment I bought my own Arduino. I chose Arduino Uno WiFi (developer edition) because, unlike Yún, it's compatible with shields. Unfortunately I can't find example code for socket communication. I found [an example that uses telnet](https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib/blob/master/examples/Tools/Wifi2Serial/Wifi2Serial.ino), so I adapted it and used it with my Python script. Sadly, the servo movement is jerky — as if there was a `delay` after each `servo.write` call.

Below is a video showing both boards running two sketches: "no network movement" and "network movement".

## Video

[![](https://img.youtube.com/vi/HXAbfGvKWJM/0.jpg)](https://www.youtube.com/watch?v=HXAbfGvKWJM)

## Code

I attach all code I used.

### Arduino oscillation test with no remote control

I use this code to test that the servo is working correctly.  It works on both Arduino Yún and Arduino Uno WiFi.

    #include <Servo.h>

    const int servoPin = 9;
    Servo servo;

    void setup() {
        servo.attach(servoPin);
    }

    void loop() {
        // configure movement
        int angleMin = 15;
        int angleMax = 165;
        int interval = 30;

        // oscillate between `angle_min` and `angle_max`
        int angle = angleMin;
        for (int i = 0; i < 2; i = (i + 1) % 2) {
            int sign = pow(-1, i);
            for (int j = 0; j < angleMax - angleMin; j += 1) {
                angle += sign;
                servo.write(angle);
                delay(interval);
            }
        }
    }

### Arduino Uno WiFi reading from telnet

This is jerky.

    #include <Servo.h>
    #include <UnoWiFiDevEd.h>

    const int servoPin = 9;
    Servo servo;

    void setup() {
        Wifi.begin();
        servo.attach(servoPin);
    }

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

### Arduino Yún reading from socket

This is smooth.

    #include <Bridge.h>
    #include <Servo.h>
    #include <YunClient.h>
    #include <YunServer.h>

    // configure
    const int port = 5555;
    const int servoPin = 9;

    // listen on given port
    Servo servo;
    YunServer server(port);

    void setup() {
        // set up servo
        servo.attach(servoPin);

        // start server
        Bridge.begin();
        server.noListenOnLocalhost();
        server.begin();
    }

    void loop() {
        YunClient client = server.accept();
        byte angle;

        if (client) {
            while (client.connected()) {
                angle = client.read();
                if (angle != 255) {
                    servo.write(angle);
                }
            }

            client.stop();
        }

        Serial.println("waiting for client");
        delay(1000);
    }

### Python writing to socket

This is the network equivalent of the Arduino oscillation test.  Works both with Yún (port 5555) and Uno (port 23).

    import socket
    from time import sleep

    # connect
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('192.168.240.1', 5555))  # use 5555 for Yun and 23 for Uno

    # configure movement
    angle_min = 15
    angle_max = 165
    interval = 30 / 1e3

    # oscillate between `angle_min` and `angle_max`
    while True:
        angle = angle_min
        for sign in [1, -1]:
            for _ in range(angle_max - angle_min):
                angle += sign
                client.send(bytearray([angle]))
                sleep(interval)

body:
I *suspect* these delays are caused by TCP buffering.

For some theory on this sort of thing, perhaps read about [Nagle's Algorithm][1] which covers some of the issues with small packet buffering.  It seems reasonable to me that lower-power and/or lower-speed (or even "just different") boards would use more aggressive buffering.

TCP uses all manner of buffering and checks to ensure guaranteed delivery of data (or reported error), whereas UDP does not.

If UDP is working for you, perhaps you may want to include some of your own error tracking in the comms protocol, unless missing the odd packet is not an issue to your control system.

  [1]: https://en.wikipedia.org/wiki/Nagle's_algorithm


message:
My HM-10 Bluetooth module only returns OK after any AT command

I bought an HM-10 Bluetooth module (BLE 4.0) to use in my school project. Every command that I send to it, it always returns "OK". Can you guys help me?

Here's the code that I am using in my Arduino Uno.

    #include <SoftwareSerial.h>

    SoftwareSerial BT(10, 11); // RX, TX
    String command = ""; // Stores response of bluetooth device

    void setup() {
      BT.begin(9600); // HC-06's usual default baud-rate
      Serial.begin(9600);
      Serial.println("Type AT commands!");
    }

    void loop() {
      if (BT.available()) {
        // Read device output if available.
        while(BT.available()) {
          // While there is more to be read, keep reading.
          delay(10); //Delay added to make thing stable
          char c = BT.read(); //Conduct a serial read
          command += c; //build the string.
        }
        Serial.println(command);
        command = ""; // No repeats
      }
      if (Serial.available()) {
        delay(10);
        BT.write(Serial.read());
      }
    }

body:
On the command write you read only one character to send to bluetooth.

Make same than for bluetooth to serial part above:

    void loop()
    {
    if (BT.available()) // Read device output if available.
    {
      while(BT.available()) // While there is more to be read, keep reading.
     {
       delay(10); //Delay added to make thing stable
       char c = BT.read(); //Conduct a serial read
       command += c; //build the string.
      }
      Serial.println(command);
      command = ""; // No repeats
    }

    if (Serial.available())
    {
      while(Serial.available())
      {
         delay(10);
         char d = Serial.read(); //Conduct a serial read
         command += d; //build the string.
      }
      BT.write(command);
      command = "";
     }
    }


message:
Bredboard board in new release

I had installed the old release (1.0.5) but for some reasons arduino stops working and I upgraded to new version 1.8.2, all works fine but I would like to use the **bredboard 8Mhz** version in the new release, but the **boards** system is not compatible with new version. The **boards.txt** is this:

    ##############################################################

    atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

    atmega328bb.upload.protocol=stk500
    atmega328bb.upload.maximum_size=30720
    atmega328bb.upload.speed=57600

    atmega328bb.bootloader.low_fuses=0xE2
    atmega328bb.bootloader.high_fuses=0xDA
    atmega328bb.bootloader.extended_fuses=0x05
    atmega328bb.bootloader.path=arduino:atmega
    atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
    atmega328bb.bootloader.unlock_bits=0x3F
    atmega328bb.bootloader.lock_bits=0x0F

    atmega328bb.build.mcu=atmega328p
    atmega328bb.build.f_cpu=8000000L
    atmega328bb.build.core=arduino:arduino
    atmega328bb.build.variant=arduino:standard

How to build it to be compatible with news version? Thank you

body:
I found a solution in this video:

[https://www.youtube.com/watch?v=cebMSJrNntI][1]

Adding:

    ##############################################################

    atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

    atmega328bb.upload.protocol=arduino
    atmega328bb.upload.maximum_size=30720
    atmega328bb.upload.speed=57600

    atmega328bb.bootloader.low_fuses=0xE2
    atmega328bb.bootloader.high_fuses=0xDA
    atmega328bb.bootloader.extended_fuses=0x05

    atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
    atmega328bb.bootloader.unlock_bits=0x3F
    atmega328bb.bootloader.lock_bits=0x0F

    atmega328bb.build.mcu=atmega328p
    atmega328bb.build.board=AVR_ATMEGA328BB
    atmega328bb.build.f_cpu=8000000L
    atmega328bb.build.core=arduino:arduino
    atmega328bb.build.variant=arduino:standard

    atmega328bb.bootloader.tool=arduino:avrdude
    atmega328bb.upload.tool=arduino:avrdude

to **/hardware/arduino/avr/boards.txt**

  [1]: https://www.youtube.com/watch?v=cebMSJrNntI


message:
(Beginner) Blinking led call function

I'm completely new to this world, so probably my question would sound noobish, but here it is:

I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".

The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?

    int ledred = 3;
    int count = 5;

    void setup() {
      digitalWrite(ledred, LOW);
      pinMode(ledred, OUTPUT);

    }

    void loop() {

        blinkingred(ledred, count);
        Serial.println("let's start over")

    }

    void blinkingred(int ledred, int count)
    {
      for(byte i=0; i == count; i++)
      {
            digitalWrite(ledred, HIGH);
            delay(1000);
            digitalWrite(ledred, LOW);
            delay(1000);
            Serial.println("Cycle done !");
      }
    }

body:
There's two things wrong with your sketch - one fatal and one that is more confusing for humans.

First the fatal problem:

    for(byte i=0; i == count; i++)

That `for` loop is never going to do anything.  The way it is written it will loop only while `i` is equal to `count` (`0 == 5`) which it never will. Instead you need to loop while `i` is *less* than `count`:

    for(byte i=0; i < count; i++)

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.


message:
I think I have a bad batch of TPIC6B595

I want drive a large number of LEDS from an Arduino Pro Mini using a number of TPIC6B595. I purchased these on ebay, perhaps a mistake.

Initially I connected two TPIC6B595 as I would connect 74HC595 (with the exception of taking account of how the open drain outputs work) to the SPI pins of an Arduino Mega (my test bench system) and tried sending an alternating bit pattern to the LEDs. No alternating LEDs. I checked SRCLR was Vcc and OE (G) was Gnd. I poked about with my scope (Rigol DS1102D)  and SRCK, RCK and SERIN looked as expected. Suspiciously SEROUT (pin 18) of the first chip was permanently LOW. Note that this is all on a breadboard.

I have used the 74HC595 now many times and from time to time I have made stupid mistakes in wiring/software. These usually stand out on the scope like a sore toe. Not this time.

So I decided to simplify it all and clock some data into a single TPIC6B595 using a simple non-SPI sketch and see if anything comes out of the SEROUT.

Here are the connections to the TPIC6B595 and to the Mega:

    1 Not connected,  20  Not connected,
    2 Vcc             19  Ground,
    3 Arduino pin 12  18  Not connected (except to scope when tested),
    4 Not connected   17  Not connected,
    5 Not connected   16  Not connected,
    6 Not connected   15  Not connected,
    7 Not connected   14  Not connected,
    8 Vcc             13  Arduino pin 11,
    9 Ground          12 Ground (See note 1),
    10 Ground         11  Ground.

The chip is bypassed by a 1uF electro across pins 2 and 10. Not ideal but the clock rates are low and it isn't unreliable, it just doesn't work at all.
Note 1: I am not trying to test the transfer between the Shift Register and the output D flip-flops so RCK should be irrelevant. I just want to see data going in to SER IN , coming out on SER OUT.

Here's the Arduino code. It generates a slow clock and an alternating data bit every few clock cycles:

    const int ser_clk = 11; // blue
    const int ser_in  = 12; // white
    byte data, count;

    void setup()
    {
      pinMode(ser_clk, OUTPUT);
      pinMode(ser_in,OUTPUT);

      digitalWrite(ser_clk, LOW);
      digitalWrite(ser_in, LOW);

      count = data = 0;
    }

    void loop()
    {
      digitalWrite(ser_clk, HIGH);
      delay(1);
      digitalWrite(ser_clk, LOW);
      delay(1);

      count++;
      if (count >= 3)
         {
           count = 0;
           if (data == 0)
              {
                data = 1;
                digitalWrite(ser_in, HIGH);
              }
           else
              {
                data = 0;
                digitalWrite(ser_in, LOW);
              }
         }
    }

Here's a screenshot of the wave-forms (photo of scope - sorry can't make UltraScope work):

[![Screenshot from Scope][1]][1]

The cyan trace is the "clock" from pin 11 of the Arduino feeding pin 13 (SRCLK) of the TPIC6B595. The yellow trace is the data from pin 12 of the Arduino feeding pin3 (SER IN) of the TPIC6B595. I am only looking to get the same data pattern out of SEROUT, pin 18 of the TPIC6B595 and this should do it. The clock is as slow as a wet week (see cursor) and even if I have bad set up and hold times and the wrong transitions the data is held for enough cycles for something to make it through surely?? Pin 18 is persistently and forever low. No screenshot - seems to be no point.

I bought several of these TPIC6B595. Tried 3 so far. All the same. Now I might have killed them with static. I am not using wrist straps, but I also don't believe I could have killed 3 of them.

As improbable as that is I think they are dead or duds, or is there something else wrong that is so obvious I cannot see it?

Regards, Fred.

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

body:
Thanks to all those who responded. I have a double embarrassment here as I have the answer. Firstly if you can answer your own question there is an argument it should never have been posted, more thought needed first. Sorry everyone. Secondly when the cause is ignoring well known good practice then it is even worse.

So when tying a pin to Vcc (in this case SRCLR) it is known bad practice to hard couple it to Vcc. A pull-up resistor is a much better method. In this case suitable pull-ups were in the next room and I could not be bothered so I just jumpered SRCLR to Vcc. After I had written the post I was staring at the breadboard and thought - I should not have really done that replaced the jumper with a 10K pullup to Vcc. Instantly the SEROUT pin of the TPIC6B595 came to life as it should have. Now I have taken this short-cut before and gotten away with it. But it seems not this time.

Subsequently I have a one chip version of the alternating LEDS running with the SPI interface.

As to the suggestion by dannyf about the datasheet, there is no doubt the datasheet is a good place place to go. **Prior** to developing my test sketch as per my original post I consulted the datasheet and if you look in Section 8, page 11 of the TI datasheet revised June 2015 there is a Functional Block Diagram. This block diagram clearly shows that the RCK signal is concerned only with the C2 column of D flip-flops which take the output from the shift register and latch it to the output FET through the output enable logic. RCK is independent of the process to clock data through the shift register, controlled by SRCLK. You will note my test did not exercise the transfer function it was just interested in getting data into the shift register and out again.

I stand by my assertion that for the serial shift register function and checking SEROUT, RCK is not relevant. Once you want to start data transfers from the shift register to the output register then it is different matter. No disagreement there. Having that timing wrong will lead to a mess of corrupted data.

Thanks again to all. This is solved and is a lesson to abide by good practice always.

Regards, Fred.


message:
GSM 900A modem not responding to AT commands

I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:

    /*

     This example tests to see if the modem of the
     GSM shield is working correctly. You do not need
     a SIM card for this example.

     Circuit:
     * GSM shield attached

     Created 12 Jun 2012
     by David del Peral
     modified 21 Nov 2012
     by Tom Igoe

     http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

     This sample code is part of the public domain

     */

    // libraries
    #include <GSM.h>

    // modem verification object
    GSMModem modem;

    // IMEI variable
    String IMEI = "";

    void setup() {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start modem test (reset and check response)
      Serial.print("Starting modem test...");
      if (modem.begin()) {
        Serial.println("modem.begin() succeeded");
      } else {
        Serial.println("ERROR, no modem answer.");
      }
    }

    void loop() {
      // get modem IMEI
      Serial.print("Checking IMEI...");
      IMEI = modem.getIMEI();

      // check IMEI response
      if (IMEI != NULL) {
        // show IMEI in serial monitor
        Serial.println("Modem's IMEI: " + IMEI);
        // reset modem to check booting:
        Serial.print("Resetting modem...");
        modem.begin();
        // get and check IMEI one more time
        if (modem.getIMEI() != NULL) {
          Serial.println("Modem is functoning properly");
        } else {
          Serial.println("Error: getIMEI() failed after modem.begin()");
        }
      } else {
        Serial.println("Error: Could not get IMEI");
      }
      // do nothing:
      while (true);
    }

I am getting this output on Serial Monitor for 9600 baud rate:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Resetting modem...Modem is functioning properly

body: The modem library does not communicate on pins 0 and 1. Check the reference library and tutorial. It should be pins 2 (RX) and 3 (TX). Reset is pin 7. The configuration may be found in GSM3IO.h. https://github.com/arduino/Arduino/blob/master/libraries/GSM/src/GSM3IO.h. See also https://www.arduino.cc/en/Main/ArduinoGSMShield


body:
If you connect a GSM modem to the Arduino's Hardware Serial pins (1/0) then you *cannot* also use those pins to communicate with a host PC.

Your question is tagged "Arduino Uno" therefore the status reporting messages to the PC will be sent over these pins, and become hopellesly confused with the traffic to the GSM modem.

You must place the modem on pins distinct from the PC interface - either using a software serial interface on different pins of an Uno, using a Leonardo-type board where the PC interface does not involve the hardware UART pins, or by using a board with multiple hardware UARTs.


body: This answer may be totally misleading because I can't find a "GSM 900A" but I can find lots of "SIM900A GSM" results.  One thing I did notice is they require a 1A+ supply to cater for transmissions so I think running of an Arduino may mean you are not giving it enough power, you should use a 1.5A supply and make sure the grounds are connected.


message:
Not showing output when using pins other than 10 and 11 with SoftwareSerial library on Arduino Mega

I am  trying to run below code on Arduino Mega using GPS module(skg13 bl). It is working fine with pins 10, 11 as rx, tx in the SoftwareSerial but it is not showing output when other pins such as 4, 5 are used.

I further have to send this data through RF module using virtual wire library.

Code is as follows:
<!-- language: lang-cpp -->

    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>
    TinyGPSPlus gps;

    SoftwareSerial mySerial(10, 11);

    void setup() {
      mySerial.begin(9600);
      Serial.begin(9600);
      Serial.println("GPS start");
    }

    void loop() {
      while (mySerial.available()) {
        gps.encode(mySerial.read());
      }

      if (gps.location.isUpdated()) {
        double a = gps.location.lat();
        Serial.println(a);
        Serial.println(gps.location.lat(), 6);
        double b = gps.location.lng();
        Serial.println(gps.location.lng(), 6);
      }
    }

Thanks in advance!!

body:
From https://www.arduino.cc/en/Reference/softwareSerial:

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

So you will need to use one of the pins from that list for RX, pin 4 or 5 will not work.


message:
Errors when compiling the GSM SMS receive example from the Arduino IDE

I want to receive SMS and check whether the character is 'y' or 'n'. If it is 'y', set a pin to high so that a light glows. I thought I could use the example code given in the Arduino IDE for receiving SMS, but when I compile (without connecting the board, using ctrl+r) it shows the following errors:

    Arduino: 1.8.1 (Windows 7), Board: "Arduino/Genuino Uno"

    In file included from F:\Arduino\libraries\GSM\src/GSM.h:46:0,
                     from F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:21:
    F:\Arduino\libraries\GSM\src/GSM3ShieldV1BandManagement.h:49:125: warning: 'typedef' was ignored in this declaration
     typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE};
                                                                                ^
    F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino: In function 'void setup()':
    F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:47:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
         if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
                                      ^
    Sketch uses 13322 bytes (41%) of program storage space. Maximum is 32256 bytes.
    Global variables use 996 bytes (48%) of dynamic memory, leaving 1052 bytes for local variables. Maximum is 2048 bytes.
    An error occurred while uploading the sketch
    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Please help me rectify the error.

I use a SIM900 GSM board. I connect the tx and rx of the GSM board to the Arduino's tx and rx.

body: Those are warnings, not errors.  The code should have compiled and be able to flash.


body:
Yes they are just warning, but don't assume all warnings should be ignored.  In this case they can be ignored, but you may as well fix them to stop them cluttering the output.

The first one can be fixed by removing the word `typedef`.

The second one needs you to add `.c_str()` on the end of the `string` variable.  Sometimes 'string' classes don't store the data in the same way as a char array.


message:
Error while updating ThingSpeak using SIM808

im trying to update ThingSpeak from a SIM808 but I'm getting a network error. Please check below and let me know if there is anything wrong in my methodology.

I'm using terminal.exe to send commands via RS232.

    AT
    OK
    AT+CREG?
    +CREG: 0,5 //connected in roaming
    AT+SAPBR=3,1,"Contype","GPRS"
    OK
    AT+SAPBR=3,1,"APN","www" //VODAFONE INDIA "www" is APN (as per the operator)
    OK
    AT+SAPBR=3,1,"USER","" //blank (as per the operator)
    OK
    AT+SAPBR=3,1,"PWD","" //blank  (as per the operator)
    AT+SAPBR=1,1
    OK
    AT+HTTPINIT
    OK
    AT+HTTPPARA="CID","1"
    OK
    AT+HTTPARA="URL","https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE"
    OK
    AT+HTTPACTION=0
    +HTTPACTION: 0,603,0

Note: while I'm typing in the browser url box, https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE, I can update my field. I can make calls, send SMS. I have an internet pack.

Please help.

body: It worked with changing AT+HTTPARA="URL","http://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE" (from https:// to http://)


body: You have to send this command: AT+HTTPSSL=1


message:
Arduino Uno not including two header files at the same time

I have an Arduino Uno and I am trying to control a stepper motor with it. I also have an RF transmitter and receiver (433MHZ). I need to transmit data about motor status.

For RF I am following this [page](http://randomnerdtutorials.com/rf-433mhz-transmitter-receiver-module-with-arduino/). Individually both are working great. I am able to send data from one Arduino (TX) to another (RX). And also I am able to control the motor. But when I am merging these projects, their header files are giving an error.

For RF, I need to include `#include <RH_ASK.h>` and for the motor I need include `#include <Servo.h>`. When I am including these headers files, they are giving me this error:

    Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

    libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin): In function `RH_ASK::maxMessageLength()':

    (.text+0x0): multiple definition of `__vector_11'

    libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

I do not know what's wrong here. Can anyone please help me?

body:
First of all, that page has a link to an old version of the RadioHead library.
This is a link to RadioHead: [www.airspayce.com/mikem/arduino/RadioHead][1]. You will find the newest library on that page.

The Servo library uses TIMER1.
The RadioHead in RH_ASK mode uses TIMER1.
Both use the same interrupt of TIMER1. That is what the compiler is trying to tell you with: "*multiple definition of _vector_11*".

You could move one of them to TIMER2.
There are alternative Servo libraries that use TIMER2.
The RadioHead can set a define for TIMER2. The explanation is in the library files in RH_ASK.h, you have to set "#define RH_ASK_ARDUINO_USE_TIMER2" in RH_ASK.cpp.

Why are you using the Servo library for a stepper motor ?

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/


body: It is telling you that interrupt vector 11 is being defined multiple times. Such definitions should be done in the source file, not in the header file.


message:
Using Youtube API with ESP8266 = redirection problems

I am using ESP8266 programmed from Arduino to get data from the Google Youtube API. API, of course, works great in a browser using URL:

    https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

The problem is that "gooogleapis.com" is not the location where from I would receive the answer to my HTTPS request, it comes from a different location. When above URL is entered, it is being redirected and request answer comes from another location.

So what happens on ESP8266 when I try to open that address(of course, with added proper channel ID and google key) is following:

    HTTP/1.1 404 Not Found
    Content-Type: text/html; charset=UTF-8
    Content-Length: 1580
    Date: Sun, 12 Mar 2017 14:40:18 GMT
    Alt-Svc: quic=":443"; ma=2592000; v="36,35,34"
    Connection: close

    <!DOCTYPE html>

      <meta charset=utf-8>
      <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
      <title>Error 404 (Not Found)!!1</title>

404. That’s an error.

The requested URL /youtube/v3/channels was not found on this server.  That���s all we know.
    Done.

Which is the Google error page(you seen it!). This is my Arduino code:

    #include "ESP8266WiFi.h"
    #include <WiFiClientSecure.h>

    const char* ssid     = "SSID";  // WiFi network name
    const char* password = "pass"; // WiFi pass

    const char* host = "googleapis.com"; // page I am trying to load
    const char* fingerprint = "22 37 4D 58 43 F4 A1 24 12 71 2B 74 7A FC 36 FC 24 A0 F0 9D";

    String ch_id = "CHANNEL ID";
    String api_key = "API KEY";

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

      WiFi.begin(ssid, password);

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

      Serial.println("Connected to WiFi! Local IP address is: ");
      Serial.println(WiFi.localIP());

      WiFiClientSecure client;
      if (!client.connect(host, 443))
      {
        Serial.println("I am unable to connect to that page.");
        return;
      }

      if (client.verify(fingerprint, host)) {
        Serial.println("certificate OK");
      } else {
        Serial.println("certificate NOT OK");
      }

      String url = "/youtube/v3/channels?part=statistics&id=" + ch_id + "&key=" + api_key;

      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");
      delay(10);

      while (client.available()) {
        String linija = client.readStringUntil('\r');
        Serial.print(linija);
      }

      Serial.println("Done.");
    }

    void loop() {
    }

* How to find out to which site I am redirected?
* How to read that from ESP8266 and redirect the same data to new site?

body:
In your browser you used `www.googleapis.com`, but in your code you used `googleapis.com`.

    https://googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

returns a 404 page.

Add `www.` to your host in code.