body:
I'm compiling my code in Arduino IDE. I have an array that I want to 0-initialize. I know `memset` works on Arduino, but I'm used to this way from my desktop C++ programming practice:

    int array[100] = {0};

I couldn't find any info on whether or not this construct works on Arduino. I think it should since it uses GCC compiler. Even though it may be modified, I still expect it to remain C and C++-compliant. Still, can you confirm for me that this standard-compliant C/C++ construct works on Arduino?

title: Does int array[100] = {0} construct work on Arduino?

Answers: 3

body:
> I'm used to this way from my desktop C++ programming practice:
>
>     int array[100] = {0};
>
> I couldn't find any info on whether or not this construct works on Arduino.

The `= {0}` has no actual effect. It is the same as:

    int array[100];

Uninitialized static / global variables, and variables explicitly initialized to 0, are placed in the [.bss](https://en.wikipedia.org/wiki/.bss) section of memory.

This section is initialized to 0 by the CRT ([C Runtime]()) code (the startup code for the system).

The compiler is responsible for placing these variables in the .bss, but it is the job of the startup (CRT) code to initialize it to zero.

This is standard C operation and is not likely to ever change since it would break all sorts of things.

Note: this does NOT apply to local variables allocated on the stack. These *must* be initialized to 0 if you want them to start as 0.

body:
The GNU cross compilers for Arduino use C/C++ front-ends and meet some version the language specs. (Although that is a moving target, you can expect a recent IDE version will be compliant with a reasonably recent language spec.)

"Arduino language" is a misnomer. The Arduino IDE will try to assist new programmers by, for example, automagically discovering library references and inserting the required #includes for you, but the resulting code is C++ and will be presented to a C++ compiler. The IDE provides a `main()` function that calls `setup()` and `loop()` (and `serialEventRun()` if you provide one) thereby reminding the programmer to initialize whatever needs to be initialized before expecting things to work right. However you can write proper C++ and get what you've come to expect. You'd have to go 'behind the IDE's back' as it were, to suppress the automatically-supplied `main()` function, but the toolchain doesn't care, as long as there is one and only one, `main()`.

I tested this this trivial program:
```
    int array[100];

    void setup() {
      // put your setup code here, to run once:
       for(uint8_t i = 0; i < sizeof(array); ++i)
          array[i] = i;
    }

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

    }
```

with both the Arduino IDE and Sloeber - Eclipse with the EclipseArduino plugin, which routinely provides a basic memory map after compilation - and with and without the initialization expression `= {0}`. I found no difference in the size of the output in either environment, with or without the initialization. In all four cases, the .bss was 209 bytes, 200 bytes larger than without the global array.

body:
This construct does work in Arduino IDE. In fact, `= { 0 }` is one of the iconic idioms of C language. It can be used to zero-initialize an object of *any* type in C. In C++ things are a bit more complicated. It will work for an `int [100]` array, but in general case you might be better off with `= {}` initializer to achieve the same effect where applicable.

It is not clear why the accepted answer claims that this construct "has no actual effect" though. This is, of course, incorrect. More precisely, this initializer is *redundant* ("has no effect") on variables with static storage duration, since such variables are default-initialized anyway (zero-initialized for `int [100]`), even if you don't request it explicitly. But for a *local* variable declaration the effect of `= { 0 }` is undeniable and obvious: it will zero-initialize the array (which wouldn't've been initialized without it).

Note that even though the `0` in the `= { 0 }` initializes the first element of the array, this initializer ultimately triggers zero-initialization if the *entire* array.


body:
I have an Arduino Mega 2560 and a BLE Shield v 2.1 from RedBearLab. When I try to connect it through Bluetooth from my laptop to 'BLE Shield', it says 'Connected!'. When I try from a Windows phone, it also says 'Connected'.

But when I try to connect from an Android device, it gives me an error: 'pairing rejected by BLE shield' or 'couldn't pair with BLE Shield because of an incorrect PIN or passkey'.

What seems to be the problem?

title: BLE Shield v2.1

Answers: 1

body:
I would guess that the problem is an incorrect PIN or passkey.

I've read from manuals for some gadgets that some devices/phones automatically try the PIN 0000 and some don't.  I have never seen my Windows phone ask for a PIN when the device hasn't got one set, so I'm guessing that Windows automatically tries 0000 and Android doesn't.  Is there a  setting on Android that will let you enter the pin (which is probably 0000) ?


body:
Does anybody know if the following MIDI DIN connectors will fit in a breadboard?

(or in general with 'generic' electrical components?)

[MIDI DIN][1]

And the same for:

[Diodes][3] to be used for MIDI in.

  [1]: https://www.aliexpress.com/item/10Pcs-PCB-Panel-Mount-MIDI-Female-DIN5-DIN-5-Pin-Jack-D501/32791217703.html?spm=2114.01020208.3.1.t95Qxz&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10037_10000179_10000083_10000042_10000135_10000080_10078_10079_10077_10000039_10073_10000140_10070_10000036_10122_10123_10126_10124_10000187,searchweb201603_9,afswitch_1,ppcSwitch_5_ppcChannel,single_sort_1_price_asc&btsid=0146bbcb-0e04-4366-8430-cef31841f51c&algo_expid=0023200f-8a8b-4111-894e-cfac21bf8947-0&algo_pvid=0023200f-8a8b-4111-894e-cfac21bf8947
  [2]: https://nl.aliexpress.com/item/6-pcs-5-Pin-DIN-PCB-Mounting-Female-Sockets-Audio-ADAPTER-CONNECTOR-for-PC-Keyboard/32667718184.html?spm=2114.010208.3.64.IprWw0&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10037_10000179_10000083_10000042_10000135_10000080_10078_10079_10077_10000039_10073_10000140_10070_10000036_10122_10123_10126_10124_10000187-normal#cfs,searchweb201603_9,afswitch_1,ppcSwitch_5,single_sort_1_default&btsid=1f53af6f-43b3-40cd-9eb1-9d99a6817a4c&algo_expid=2b87c29d-a3b7-4676-91e0-3d1743e326fd-6&algo_pvid=2b87c29d-a3b7-4676-91e0-3d1743e326fd
  [3]: https://nl.aliexpress.com/item/50-Stks-1N914-DO-35-Hoge-Conductance-Fast-Diode/32678059771.html?spm=2114.010208.3.46.AwZwQl&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10037_10000179_10033_10000083_10000042_10000135_10000080_10078_10079_10077_10000039_10073_10000140_10070_10000036_10122_10123_10126_10124_10000187,searchweb201603_9,afswitch_1,ppcSwitch_5,single_sort_1_price_asc&btsid=a0290d56-802c-4022-b235-4d24ee48ea5f&algo_expid=062424e5-c965-4a5c-9520-0b488feafecd-5&algo_pvid=062424e5-c965-4a5c-9520-0b488feafecd

title: MIDI connectors / Diodes

Answers: 1

body:
Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:
![MIDI jack PCB footprint](https://i.stack.imgur.com/P6C0F.png)

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard.
You might need to file them off.

Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

![panel-mount MIDI jack](https://i.stack.imgur.com/pO8DM.jpg)
(search for "5 pin DIN female jack")

---

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

---

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.


body:
I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer.
Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens. <br>I have tried with different example sketches but it seems code was not uploaded.

My Board manager configuration

- Board: Generic ESP8266 Module
- Flash mode: QIO
- Flash frequency: 40 MHz
- CPU frequency: 80 MHz
- Flash size: 1M (128K SPIFFS)
- Debug port: Serial
- Debug level: none
- Reset method: ck (tried nodemcu too without success)
- Upload speed: 115200
- USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v09f0c112
    ~ld
    e:
     ets Jan  8 2013,rst cause:3, boot mode:(3,7)

    ets_main.c

and here's the IDE console window output:

    sptool.py v1.3
    Connecting..........
    Auto-detected Flash size: 8m
    Running Cesanta flasher stub...
    Flash params set to 0x0020
    Writing 229376 @ 0x0... 0 (0 %)1024 [...]
    Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
    Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
    Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
    Leaving...

The sketch I am using

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                        // but actually the LED is on; this is because
                                        // it is acive low on the ESP-01)
      delay(1000);                      // Wait for a second
      digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
      delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
    }

title: ESP01 unsuccessful code execution

Answers: 1

body:
If you are using an ESP01 I don't think you should be using GPIO1 as the output pin, its my understanding that they don't have GPIO1.

I think they have GPIO0 and GPIO2, so you should have attached the LED to GPIO2 and use `digitalWrite(2, HIGH);` in you code.

Have a look at this page and see if what its on about is what you are trying to do.

http://iot-playground.com/blog/2-uncategorised/38-esp8266-and-arduino-ide-blink-example


body:
I've been out of the loop with Arduino for several years.  I [heard][1] about [the split][2] (another [link][3]), but didn't really understand, nor keep up with it, nor the details of the fallout.

Today, I decided to jump back in and make something, and a [DDG search][4] led me to [Arduino.cc][5] to get the software.  But is that what I need?

How do I know if that's the right software IDE?  Is there another location?  Does it matter?  Does it depend on more variables?  Is this [split][6] akin to the [OpenOffice][7] and [LibreOffice][8] split, where one is more better (technical term!) supported than the other?

I'm working on an Arduino Uno I got from [Microcenter][9].

  [1]: http://makezine.com/2015/03/06/arduino-vs-arduino/
  [2]: https://news.slashdot.org/story/16/10/01/1926242/the-arduino-split-is-over-new-non-profit-formed
  [3]: https://olimex.wordpress.com/2015/03/20/arduino-split-in-court-revail-how-the-project-started-and-developed/
  [4]: https://duckduckgo.com/
  [5]: https://www.arduino.cc/en/Main/Software
  [6]: https://www.howtogeek.com/187663/openoffice-vs.-libreoffice-whats-the-difference-and-which-should-you-use/
  [7]: https://www.reddit.com/r/software/comments/2tmu4l/openoffice_vs_libreoffice/
  [8]: http://www.techrepublic.com/article/whats-the-difference-between-libreoffice-and-openoffice/
  [9]: http://www.microcenter.com/product/431997/Uno_R3_MainBoard

title: Post-split, where do I download the Arduino IDE?

Answers: 2

body:
The split is already over. They are working on merging everything that happened during the split, if they haven't already.

I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).

body:
Both sites contain the same version of the IDE. .Org dropped their 1.7.x branch (actually 1.0.x renumbered) and both now have the 1.6.x branch version-bumped up to 1.8.x.

As Gerben noted, the split is over, https://arduino.meta.stackexchange.com/q/2380/4143.


body:
 I want to do is BEEP! to show that the program is running.

    #define SPKR 4 //this is the digital pin that you plugged the red       wire into

    void setup()
    {
       pinMode(SPKR, OUTPUT); //set the speaker as output
    }

    void loop() //do this over and over
    {
       digitalWrite(SPKR, HIGH); //turn the speaker on
       delay(500);                     //wait for half a second
       digitalWrite(SPKR, LOW); //turn the speaker off
       delay(500);                    //wait for half a second
    }

With out this any other way
I mean without repeating the code HIGH / LOW
during this beep I want do same things else

title: How I can make alarm on off?

Answers: 1

body:
The code you show will toggle the `SPKR` pin at a 1 Hz rate.  If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.

To generate a tone, use [`tone(pin, frequency)`](https://www.arduino.cc/en/Reference/Tone) calls, or `tone(pin, frequency, duration)` calls.

For example:

    void loop() {
       tone(SPKR, 400, 500); // 400 Hz tone for half second
       delay(500);           // no tone for half second
    }

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc.  You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions.  AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.


body:
I have built an arduino quad-copter and I am using an MPU6050 to read the rotational position and velocity of the aircraft. The problem is that I cannot get the thing to stabilize. Watch this video [here][1] to get an idea of what I mean.

So as you can see from the footage (and you did watch it, right?), I'm not even getting steady oscillations, it's just random. What I don't understand is how people get their quad-copters to oscillate very quickly (maybe 10 times per second) and then trim up their PID gains to smooth it out, whereas if I raise my p-gain high enough for it to adjust that quickly, the quad-copter just goes berserk and tries to kill me.

And, speaking of p-gains, here's the PID I wrote:

    float KrP = 0.002000;
    float KrI = 0.000001;
    float KrD = 0.200000;

    void adjustRoll(float currentRoll, int newRoll) {
      if (thrust <= 1200){
        inAutoRoll = false;
        NWPower = thrust;
        NEPower = thrust;        //PID not ready to turn on yet? Just set motor powers
        SWPower = thrust;        //equal to the throttle.
        SEPower = thrust;

        I_roll = 0;              // Reset the integral.
        return;                  // Don't do anything else
      }

      float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
                                                                           // adjust, based on the error.

      if (newRate > 50)newRate = 50;        // Don't adjust too fast!
      else if (newRate < -50)newRate = -50;

      float offset = newRate - rollRate;

      I_roll += KrI * offset;

      if(!inAutoRoll) {        // Is the PID just now turning on? (Throttle requirement met).
        lastRollRateOffset = offset;  //Smooth transition.
        inAutoRoll = true;
      }

      float adjust = (KrP * offset) + (KrI * I_roll) + (KrD * (offset - lastRollRateOffset));

      NWPower += adjust;
      NEPower -= adjust;
      SWPower += adjust;
      SEPower -= adjust;

      if (NWPower > maxOut) NWPower = maxOut;
       else if (NWPower < minOut) NWPower = minOut;

      if (NEPower > maxOut) NEPower = maxOut;
       else if (NEPower < minOut) NEPower = minOut;

      if (SWPower > maxOut) SWPower = maxOut;
       else if (SWPower < minOut) SWPower = minOut;

      if (SEPower > maxOut) SEPower = maxOut;
       else if (SEPower < minOut) SEPower = minOut;

      lastRollRateOffset = offset;
    }

And in case you were wondering... yes, I do know about integral windup. The reason I have not dealt with that in my code is because the quadcopter is no where near stable, so I'm not worrying about perfection just yet. Also, I have my I-gain set to 0.000001, so it doesn't matter. The reason I have done this is because (as far as I know) a quadcopter can fly with only P and D, and with the way mine is behaving, I think a larger I-gain would only make things worse.

More detail about my PID: The PID corrects for the rotational velocity of the quad-copter, which, as I understand it, is the best way to control a quadcopter. The correction-rotation-rate is determined by multiplying the error (in degrees) by two. Why two? I dunno. I experimented with some other multipliers and two seems to be okay. Its also a prime number, so, yeah...

So anyways! **What do I need to do to make the quad-copter stable?** I have seen amazingly perfect quad-copters using the same arduino and the same MPU6050, but mine just tilts all over the place.

Some possible problems off the top of my head:

 1. Bad algorithm for calculating the needed rotational velocity based on error.
 2. Bad PID algorithm.
 3. Bad PID gains.
 4. I didn't balance my props, but seriously, would a couple of pieces of electrical tape stuck to the props really fix this? It doesn't seem like it would.

Thanks for any help you have to offer!

  [1]: https://youtu.be/0zaPF644_Io

title: How can an Arduino-Quadcopter be stabilized?

Answers: 3

body:
For stability and tuning you need to make the adjustment cycle time compatible with the physical system.  How fast does this adjustment code get called relative to how fast the physical system oscillates?  Without that under control, tuning the gains will be difficult, particularly for krI and krD.

For instance, if you are updating every millisecond, and it takes a 1/10th of a second to physically flop over from -90 to 0 at the current roll_thrust setting, there's only enough kP to adjust the roll_thrust `kP*(RollDelta/2)*DT/dt=0.002*(90/2)*0.1/0.001=9`  Is that a sane adjustment for a thrust/motorPower of 1200+?  If you sample fast enough to make it capable of a full-throttle (+/-800?) adjustment with this particular kP, you might need to sample 88x faster (1ms/(800/9)=0.01125ms).  From the other direction, I'd figure out how fast you can sample, then choose a krP that could get you a full-bias adjustment in reasonable time.

Maybe think of `adjust` as `roll_thrust` state variable measured in units of ESC_microseconds, and krP is the conversion factor from whatever error you are measuring.  Is it roll angle error? roll rate error? Absolute roll rate error?  It looks like this bit:

    float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
    if (newRoll - currentRoll < 0) {             // adjust, based on the error.
       newRate = 0 - newRate;
    }

is essentially:

    float newRate = 2 * abs(newRoll - currentRoll);

which might make control discontinuous.  If currentRoll is a positional roll angle setpoint, it won't be able to tell if it is on one side or the other.

If you want a roll angle of -90deg to make full throttle one way and 90deg to full throttle the other, then krP should be on the order of 900us/90deg=10us/degree.   And krI=krD=0 to start with.

I'd code up separate PIDs for `thrust`, `roll_thrust`, `pitch_thrust`, `yaw_thrust` control variables and then sum them together to get the  `{NE,NW,SE,SW}Power` outputs.  Then you could monitor and control in {thrust,roll_angle,pitch_angle,yaw_rate} space and the coding will be more straightforward and interpretable.

body:
To help solve this problem, I wrote a program in *Processing* that graphs all the data from the quadcopter, including roll rate, roll angle, thrust, etc... After doing so I realized that the problem was not in the PID, but in how I handled the data coming out of MPU6050. You can read all about it in this question I posted [here][1] before I had discovered the full solution.

The quadcopter is now capable of taking off, though sadly it is not very stable. This could be from bad PID gains, but I suspect it is from vibration in the roll-rate values from the MPU6050. The reason I think this is because I don't see steady oscillations, but rather random movement. Anyway, If I find a more complete solution I will update this answer.

  [1]: https://arduino.stackexchange.com/questions/35440/mpu6050-sending-bad-values-for-angular-velocity

body:
To be sure the receiver gets the right signal from the emitter it is mandatory to scrutinize the signal on the receiver for a while.
Once the signal on the receiver is checked good it is possible to go ahead step by step.
The first step is to drive the 4 ESC/motors with the same signal coming from the throttle.
Once the behavior of the 4 motors complies with changes on the throttle coming from the emitter it is time to go to the next step.
The next step stems from a mix with pitch/roll/yaw coming from the emitter.
The mix is added/removed to/from the throttle addressing each motor.
The behavior of the 4 motors must show exactly the mix that comes from the emitter.
An "acceptable" mix is something like (in the same unit, degres or microseconds):

Something like this:

```c++
int throttle_gaz;
int roll_length, pitch_length, yaw_length;

throttle_gaz=pulse_duration[throttle_chanel];
if ( abs(throttle_gaz-1500) <= 50 )
{
 throttle_gaz=1500;
}
roll_length=pulse_duration[roll_chanel]-1500;            //ROLL
if (abs (roll_length) <=100 )
{
roll_length=0;
}
roll_length/=3;

pitch_length=pulse_duration[pitch_chanel]-1500;           //PITCH
if (abs (pitch_length) <= 100 )
{
  pitch_length=0;
}
pitch_length/=3;

yaw_length=pulse_duration[yaw_chanel]-1500;             //YAW
if (abs (yaw_length) <=100 )
{
  yaw_length=0;
}
yaw_length/=3;

//add/soustract from THROTTLE (pulse_duration[throttle_chanel])
//change the sign (+ / -) acc
pulse_length_esc1=throttle_gaz + roll_length + pitch_length - yaw_length;
pulse_length_esc2=throttle_gaz - roll_length +  pitch_length +  yaw_length;
pulse_length_esc3=throttle_gaz + roll_length - pitch_length  + yaw_length;
pulse_length_esc4=throttle_gaz - roll_length -  pitch_length  -  yaw_length;
```


body:
Just read a post about timers and there was a timers cheat sheet posted there. It has been very helpful and I wonder if there is one for interrupts as well?

The post with the nice timer cheatsheet was this one https://arduino.stackexchange.com/questions/16698/arduino-constant-clock-output

title: Cheat Sheet for interruption

Answers: 1

body:
Perhaps something like this (for the Arduino Uno based MPU): [![enter image description here][1]][1]

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


body:
    #define LED 13
    #define BAUDRATE 9600
    #define DEBUGOUTPUT 0
    #define LED 13
    #define powercontrol 10

    // checksum variables
    byte generatedChecksum = 0;
    byte checksum = 0;
    int payloadLength = 0;
    byte payloadData[64] = {0};
    byte poorQuality = 0;
    byte attention = 0;
    byte meditation = 0;

    // system variables
    long lastReceivedPacket = 0;
    boolean bigPacket = false;

    //////////////////////////
    // Microprocessor Setup //
    //////////////////////////
    void setup() {
      pinMode(LED, OUTPUT);
      Serial.begin(BAUDRATE); // USB
    }

    ////////////////////////////////
    // Read data from Serial UART //
    ////////////////////////////////
    byte ReadOneByte() {
      int ByteRead;
      while(!Serial.available());
      ByteRead = Serial.read();
      #if DEBUGOUTPUT
      Serial.print((char)ByteRead);
      // echo the same byte out the USB serial (for debug purposes)
      #endif
      return ByteRead;
    }

    /////////////
    //MAIN LOOP//
    /////////////
    void loop() {
      // Look for sync bytes
      if(ReadOneByte() == 170) {
        if(ReadOneByte() == 170) {
          payloadLength = ReadOneByte();
          if(payloadLength > 169)
          //Payload length can not be greater than 169
            return;
          generatedChecksum = 0;
          for(int i = 0; i < payloadLength; i++) {
            payloadData[i] = ReadOneByte();
            //Read payload into memory
            generatedChecksum += payloadData[i];
          }
          checksum = ReadOneByte();
          //Read checksum byte from stream
          generatedChecksum = 255 - generatedChecksum;
          //Take one's complement of generated checksum
          if(checksum == generatedChecksum) {
            poorQuality = 200;
            attention = 0;
            meditation = 0;
            for(int i = 0; i < payloadLength; i++) {
              // Parse the payload
              switch (payloadData[i]) {
                case 2:
                  i++;
                  poorQuality = payloadData[i];
                  bigPacket = true;
                  break;
                case 4:
                  i++;
                  attention = payloadData[i];
                  break;
                case 5:
                  i++;
                  meditation = payloadData[i];
                  break;
                case 0x80:
                  i = i + 3;
                  break;
                case 0x83:
                  i = i + 25;
                  break;
                default:
                  break;
              } // switch
            } // for loop

            #if !DEBUGOUTPUT
            // *** Add your code here ***
            if(bigPacket) {
              if(poorQuality == 0) digitalWrite(LED, HIGH);
              else digitalWrite(LED, LOW);
              Serial.print("PoorQuality: ");
              Serial.print(poorQuality, DEC);
              Serial.print(" Attention: ");
              Serial.print(attention, DEC);
              Serial.print(" Time since last packet: ");
              Serial.print(millis() - lastReceivedPacket, DEC);
              lastReceivedPacket = millis();
              Serial.print("\n");
              switch(attention / 10) {
                digitalWrite(LED, HIGH);
                digitalWrite(LED, LOW);
              }
            }
            #endif
            bigPacket = false;
          } else {
            // Checksum Error
          } // end if else for checksum
        } // end if read 0xAA byte
      } // end if read 0xAA byte
    }

title: Why does the serial monitor output show some unidentified symbols?

Answers: 2

body:
It time to start stroking our crystal balls, what symbols?

Actually it doesn't really matter, `ReadOneByte()` is the cause, you are printing `ByteRead` without checking that it is printable.  Character greater than 127 will look strange when you print them out, only 32-126 are printable (127 is backspace) see http://www.asciitable.com/ for more details.  In this case I would print the value as a hex number, `Serial.println(ByteRead, HEX);`

If you are still getting symbols after changing that there may be other prints that have the same problem

body: select the same serial **Baudrate** in the select which is in the bellow of the serial monitor window as you have put in the code.


body: I want to use a mini usb jack to power my device off board, but I want to make sure that the usb power coming in is not any higher than the 5V. I've read a bit about polyfuses but I am unsure if they would be useful for this scenario. Thanks!

title: 5V usb surge protection for circuit board?

Answers: 2

body:
A polyfuse will limit **current** not voltage.

There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.

You should NOT need any of this if you use a reasonable power supply.

body:
I second Milliways answer:

> You should NOT need any of this if you use a reasonable power supply.

Anyway, if you really have a crappy power supply you can use one of the modules you find on ebay (for instance [this](http://www.ebay.com/itm/142230430507) is the first result I came across). Be sure to look for "buck boost" modules (step up/down), because they can both raise and lower the voltage.

This will do the job your power supply is not able to do, so to give you a stable voltage. You can then also vary the voltage without worrying (they usually are able to handle 4V (e.g. lithium batteries), 7.2V (e.g. 2 lithium batteries), 12V, ...

If you want also reverse protection, I suggest you to simply put a diode in series with THE INPUT (anode on the positive of your power supply, cathode on the IN+ terminal of this regulator). This way the voltage drop will be absorbed by the regulator. You can use a cheap 1N4007 or even a Schottky diode (which have less drop -> better power consumption).

I discourage you from using a full wave rectifier, since the diodes on the ground will change the ground reference (and so if you connect something else you may experience problems).

You can find a lot of "buck/boost" modules out there, just check that the input and output voltages and currents are suitable for your project.

But again, unless your power supply is really crappy you won't need this. If you just need an inversion protection, you can also use a circuit I found on a PC : put a fuse (they used a real fuse, you can use a polyfuse) between the power positive input and the circuit positive, then add a diode with the anode to ground and the cathode to the circuit positive. If you attach it correctly the diode will be reverse polarized and the circuit will work correctly, if you attach it in reverse the diode will conduct and so will create a large current which will trip the fuse.


body:
My code:

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    int led = 13;
    const int buttonPin = 2;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
    }

    // the loop routine runs over and over again forever:
    void loop()
    {
      bool buttonState = digitalRead(buttonPin);
      while (buttonState == LOW)
      {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
       }
     if (buttonState == HIGH){
       digitalWrite(led, LOW);}
      }

The last line of code:

    if (buttonState == HIGH){
       digitalWrite(led, LOW);}
Is what I tried using to turn the led off from its continuous blinking state. So the point of this project is to make the led's blink with a button, then turn them off with the same button. This has been bugging me for hours and I've done all the work but can't seem to get this last part done. What is being done wrong here?

**EDITED for clarification:**

The intention is that with each push of the button the LED is toggled between a blinking and a no-blinking state. The state of the LED is not driven by the level (pushed/unpushed) of the button itself, but by the pushing action itself.

title: Stop Led's from blinking

Answers: 5

body:
while (buttonState == LOW)
gets you trapped in an endless loop, once `buttonState == LOW`.

You have to poll `buttonState` **inside** this loop if you ever want to get out of it.

However this is not enough for your purpose. What you really need is a (boolean) variable - let's name it `blinking`, for instance - which changes its value each time you see a falling edge on buttonState.

Then check this variable's value in an if/else clause like this:

    if (blinking == true)
    {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
    }
    else
    {
       digitalWrite(led, LOW);}
    }

But with this you will soon face the next problem: The polling speed for your button is very low, because of the very long delays, which keep you about 2 seconds inside the `if` clause.

Try setting up the blink cycle using a PWM, as described [here][1]

Then use the `if` clause above to set the PWM duty to 50%, and the `else` clause to set it to 0%.

  [1]: http://playground.arduino.cc/Code/Timer1

body:
**EDITED**

The Arduino `loop()` function makes the use of a `while` loop redundant in this case. Even worse: the way you've implemented that `while` loop prevents `buttonState` from being updated, thus getting stuck in the loop.

What you actually need is to use timers to blink the LED, and a 2-state machine driven by HIGH to LOW button transitions.

Try this instead:

    #include "Timer.h"

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    const int led = 13;
    const int buttonPin = 2;

    // declare state variables as global
    bool buttonState = LOW;
    bool buttonState_prev = LOW;
    bool toggleBlinking;
    bool blinkState;

    // declare a Timer object so blinking can be done without loosing button presses
    Timer timer_b;
    int blink_id;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);

      // initial state: toggle led each 1000 ms
      blink_id = timer_b.oscillate(led, 1000, HIGH);
      blinkState = true;
      toggleBlinking = false;
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // Update the timer (required)
      timer_b.update();

      // check if button has been pressed (HIGH to LOW),
      // then debounce it and raise toggle flag
      buttonState = digitalRead(buttonPin);
      if ((buttonState != buttonState_prev) && (buttonState_prev == HIGH)) {
        // simple button debounce (confirm press after some ms)
        delay (50);
        buttonState = digitalRead(buttonPin);
        if (buttonState != buttonState_prev) toggleBlinking = true;
      }

      // keep current LED state unless the button has been pushed
      switch (blinkState) {
        case true:
          // if button has been pushed, stop blinking and change LED state
          if (toggleBlinking == true) {
            timer_b.stop (blink_id);
            blinkState = false;
          }
          break;
        case false:
          digitalWrite(led, LOW);
          // if button has been pushed, start blinking and change LED state
          if (toggleBlinking == true) {
            blink_id = timer_b.oscillate(led, 1000, HIGH);
            blinkState = true;
          }
          break;
      }

      buttonState_prev = buttonState;
      toggleBlinking = false;
    }

**NOTE:** You'll need to install the [Timer.h library][1]. I'VE TESTED MY CODE AND IT WORKS.

  [1]: https://github.com/JChristensen/Timer

body:
As the OP explained in a comment, what he is trying to achieve is to have a button alternate between blink and off, not having the button to be pressed to shut down the led.

This can be done in this way:

    bool prevButtonState;
    bool ledBlinking;

    void loop()
    {
     bool buttonState = digitalRead(buttonPin);

     if (prevButtonState && !buttonState)
     { // Pressing edge: there is a transition between high and low
      ledBlinking = !ledBlinking;
     }
     prevButtonState = buttonState;

     if (ledBlinking)
     {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
     }
     else
     {
      digitalWrite(led, LOW);
     }
    }

This, however, leads to a very long time between successive checks of the button (since there is a 2s delay between cycles). You can solve this using the millis function:

    bool prevButtonState;
    bool ledBlinking;
    unsigned long prevMillis;

    void loop()
    {
     bool buttonState = digitalRead(buttonPin);

     if (prevButtonState && !buttonState)
     { // Pressing edge: there is a transition between high and low
      ledBlinking = !ledBlinking;

      prevMillis = millis() - 1000; // Force a check
     }
     prevButtonState = buttonState;

     if (ledBlinking)
     {
      if ((millis() - prevMillis) >= 1000)
      {
       prevMillis += 1000;
       digitalWrite(led, !digitalRead(led));
      }
     }
     else
     {
      digitalWrite(led, LOW);
     }
    }

Next there is the debounce problem, but this becomes OT. Suggestion: use the Bounce2 library to manage the button if you experience bounces

body:
It makes sense to make switch-testing fairly independent of blink-control.  That's done in the following code, which turns blinking on or off each time a button is pressed.  With this code, between button presses the LED either is off or it blinks at about a 2 Hz rate.

    enum { LED=13, ButtonPin=2, BounceMS=50, BlinkMS=256 };
    unsigned long buttonAt;
    bool blinky, bouncy, buttonState;

    void setup() {
      pinMode(LED, OUTPUT);
      pinMode(ButtonPin, INPUT_PULLUP);
      blinky = bouncy = buttonState = false;
      buttonAt = millis();
    }

    void loop() {
      // Detect button changes
      if (bouncy) {
        if (millis() - buttonAt > BounceMS)
          bouncy = false;  // End of debounce period
      } else {
        if (digitalRead(ButtonPin) != buttonState) {
          buttonState = digitalRead(ButtonPin);
          buttonAt = millis();
          bouncy = true;  // Start debounce period
          if (buttonState) { // Was button just pressed?
            blinky = !blinky; // Toggle blink-state
          }
        }
      }
      // Control light-blinking
      if (blinky) {
        // Turn LED on for BlinkMS ms, then off for same
        digitalWrite(LED, (millis() - buttonAt)%(2*BlinkMS) < BlinkMS);
      } else {
        digitalWrite(LED, LOW);
      }
    }

body:
try this:

    if (key_pressed()) digitalWrite(LED_PIN, (digitalRead(LED_PIN)==ON)?OFF:ON);
    else digitalWrite(LED_PIN, OFF);

define ON/OFF based on your led connection.

Edit.

If you want the button too change the mode of led blinking, try this.

  if (btn_pressed())      //if btn falling edge detected
   btn_status ^= 1;    //flip the last bit. btn_status += 1; works as well
  if (btn_status & 0x01) led1_flp(); //flip led1
  else led1_off();     //otherwise, turn off led1

  //flip led2
  IO_FLP(LED_PORT, LED2);

the logic is fairly simple: if the button is pressed (active low), toggle btn_status. if btn_status is 1, blink the led1.

basically, press the button, led starts to blink; press the button the 2nd time, led stops to blink;

led2 is always blinking, to show concurrency of the code.

here it goes in action.

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

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

the code is written for a pic but basically runs on any mcu.


body:
I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:
[![IR transmitter and receiver][1]][1]
So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. **I want to increase this to at least 5 meters**. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong): [![Range increase with 2N222 transistor][2]][2]
The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. **The devices are placed  up to 1 meter apart and the transmitting range should be at least 5 meters.**<br/>

 - Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

 [![TSOP 1738][3]][3]
Any help is appreciated, thank you.

  [1]: https://i.stack.imgur.com/jeoEh.jpg
  [2]: https://i.stack.imgur.com/R4qTa.jpg
  [3]: https://i.stack.imgur.com/83DTi.jpg

title: Increase IR transmitter directivity and range

Answers: 1

body:
The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).

So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.

But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

---

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html - but basically it can  somehow receive nearly from anywhere on the "diode-like" side.

The back side (flat one) should not be sensitive.

---

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

---

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).

But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".

You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).

In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.

First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and  Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values"  as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).

But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

---

**TLDR:** I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.

Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.


body:
I'm trying to use the following RTC module (PCF8563) with Arduino Uno.[![enter image description here][1]][1]

I am using [this library][2] to set/get time and date from PCF8563. However, whenever I shut down the Arduino, the time/date is lost! Even though, as you can see in the picture, the module is equipped with a 3V battery to keep running when Arduino is unplugged.

Any help would be highly appreciated!

  [1]: https://i.stack.imgur.com/ZaU66.jpg
  [2]: http://playground.arduino.cc/Main/RTC-PCF8563

title: PCF8563 does not remember time when restarting Arduino Uno?

Answers: 1

body:
[SOLVED]

The solution is simply to put a jumper between BAT and VCC positions in the module itself. Many thanks to [Edgar Bonet][1]

  [1]: https://arduino.stackexchange.com/users/7508/edgar-bonet


body:
I am currently trying to get a real-time FFT working for a project on an Arduino 101 which uses the Intel Curie chip. All the FFT libraries (if any) seem to be for the Arduino Uno and architecture dependent (most of them have assembly stuff for optimization).

I was wondering if there is any robust, up do date and most importantly working (with the latest Arduino 101) library. I have tried the PlainFFT library which I read might be compatible with the Arduino 101 (https://forum.arduino.cc/index.php?topic=409791.0).

However this library seems to be out of date, using old extensions of sketch files and old library names in its code (I could not get it to work). Alternatively I wanted to try and tailor a pure C code such as https://github.com/jtfell/c-fft, which seems to have its own Makefile for compilation (this one uses a C99 compiler). I could compile and use this code on a Linux terminal but I am not sure how to go on about making it run inside an Arduino sketch.

title: FFT library for Arduino 101?

Answers: 1

body: I used lightweighted **KissFFT** (Mark Borgerding) at Arduino Mega and seems it is pure C code so should be running anywhere.


body:
We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur.
Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required.
Thanks!

title: Advice needed, commercializing an Arduino Due project

Answers: 2

body:
There's two routes you can take.

First route:

1. Get the Due schematics.
2. Remove the parts you don't need.
3. Add to it the new components for your product.
4. Lay out the PCB design.
5. Get the PCB manufactured.
6. Solder all the components on.
7. Test it and go back to step 2/3 as required.

Second route:

1. Hire a contractor that knows the SAM3X and can do it all for you.

body:
Depends on the kind of project you are doing. If the Due is just minor part (say you are producind 3D printer) and you plan to do like tens of the devices, I would consider using it, but probably would solder it in for good contact reliability. Maybe put it inside a box too, so nothing can short anything on the board. (And then the Due is not in plain sight).

If it is mainly Due with some sensors around and you want to sell thousands of them, then I would make extra PCB for it, containing everything what is possible on one board. (Like @Majenko suggested.)

Anyway I made a lot of PCB in my kitchen (yes, literally) for my "Arduino" projects, even when I made only 1 or 2 devices just for me. Every of them worked just fine. It is not so dificult to do if you are not pushing some limits too hard. Even Due small chip can be soldered by hands and with some basic tools on your eating table.

But if you lack the skills, hiring contractor (or found company, which does that) may be cheaper in terms of your time and number of devices destroyed before getting the skill and customers complaining about devices broken after short time use.


body:
I'm doing a research project that uses three sensors ([DHT22](https://www.adafruit.com/product/385), HTU21D and TMP102) and two screens (a normal 16x2 LCD, and a TFT).

I connected all the sensors and the LCD in my Arduino Uno and everything works fine. However, when I connect the TFT, the TFT simply freezes and does nothing. I ran the example Arduino sketches for TFT and it works fine. I also did a bit of debugging and found that if I don't invoke the [DHT22 sensor reading functions](https://github.com/adafruit/DHT-sensor-library/blob/master/DHT.h) (i.e., dht.readTemperature()), the TFT screen works fine.

I also triple-checked the wiring and it doesn't seems that something is wrong.

Any ideas why this behaviour occurs? Thanks.

title: Weird probled with TFT LCD screen and DHT22 sensor

Answers: 0


body:
To my knowledge the SeeedStudio CAN-Bus shield utilizes D13, and so does the [SD-card module][1] I use. And also Arduino Uno's LED_BUILTIN is 13. **Am I in danger of some sort of collision here?**

I have read [this question][2], but that one describes situation where both modules are on *a single shield.*

Why I am alerted: I can perform following sequence: turn the LED on, open file, write, close file, turn the LED off, no apparent problem here. But when I connect my CAN-Bus shield to merely read messages (i.e. no sending data to the shield, not on purpose) my car behaves funny as if I still somehow managed to send some rogue bytes to the shield. (Right side windows and mirror are dead, infotainment display shows dead splash screen, dashboard complains about "engine malfunction" and airbags...)

I wonder if by writing to the SD-card and possibly turning the LED on I didn't send some bytes to the shield. Do I need to somehow Select Slave?

  [1]: http://ebay.to/2lqdrsL
  [2]: https://electronics.stackexchange.com/questions/67212/how-to-avoid-sd-card-and-w1500-spi-mixup-on-the-ethernet-shield/67214#67214

title: CAN-Bus shield, SD-card module & LED_BUILTIN use D13; possible collision?

Answers: 1

body:
Yes you are in danger of a collision, how much danger I can't say, but the potential is there.

 1. You could stop using the LED on D13?
 2. Could you move the pins of your SD card reader, or get a different one that allows I2C or SPI interfacing?

I guess there is nothing that can be done to the CAN bus device, but if there is it might be a good idea to move its pins.


body:
Using the simplest code possible to test the library:

    #include <Wire.h>

    void setup()
    {

      Wire.begin(); // join i2c bus

      Wire.beginTransmission(44); // transmit to device #44 (0x2c)
                                  // device address is specified in datasheet

      Wire.write(0xA);             // sends value byte
      Wire.write(0xA);             // sends value byte
      Wire.write(0xA);             // sends value byte

      Wire.endTransmission();     // stop transmitting
    }

But my data (three test byte of 0xA) is not getting sent. See image. As you can see, I get start bit, address, and then the stop bit. No data. Where am I going wrong?

[![Scope Trace][1]][1]

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

title: I2C Wire.write function doesn't seem to work

Answers: 3

body:
According to the captured communication `NACK` was received (confirmed in comments) and according to the `Wire` library `twi_stop` will be called (and sent) in this fault scenario.

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

    case TW_MT_SLA_NACK:  // address sent, nack received
      twi_error = TW_MT_SLA_NACK;
      twi_stop();
      break;

body:
It looks like you have code for an I2C master. Sending to a slave involves sending the slave address, and waiting for an ACK from the slave (that is, the addressed slave pulls the data bus low).

You can see that in a graphic from [my page about I2C](http://www.gammon.com.au/i2c):

[![I2C protocol][1]][1]

At the 100 µs mark you can see that the slave pulls SDA low, which is an ACK. Thus the master knows that the addressed slave exists. Without that, the slave is not there, and there is no point in sending any further data.

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

body:
OK, I figured out what was going on...

An example program that I downloaded to test the hardware was sending a "self address" command to the chip, which was causing the address to get set to 0x03 and I didn't notice this. This new address stays in memory. So, when I went back to test the library code, I was sending 0x00 (default from factory) instead of the new address (0x03). The NACK after the address byte should have been a clue, but hey, live and learn.

Thanks for all the responses. Hopefully my pain will help someone else.


body: I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!

title: Open video file if sensor reaches certain threshold value

Answers: 1

body:
What I'm thinking is that you could make a conditional statement. Below is a little a bit of pseudo code on how to possibly open said video from an SD card because there's no way Arduino would be able to store a video on it's own, let alone play good quality videos:

    int dangerLevel = 500 (or however the shield reads the smoke level)

    int smokeDetectorPin = A0

    setup:

    smokeDetected = analogRead(smokeDetectorPin)

    loop:

    if smokeDetected >= dangerLevel:

    open video from SD card directory or computer.

So in order to get a "video" from the SD card, you should check this [website](http://www.instructables.com/id/Streaming-video-from-SD-card-to-Nokia-LCD-with-Ard/step6/Playback-program-sketch-for-the-Arduino/). Like I mentioned before, this is really primitive and it's probably not what you're looking for.

I found something very interest about the Arduino that I never knew you could do before and using composite display from a TV. Interesting and you can find that info [here](http://playground.arduino.cc/Main/TVout).

And lastly, to get a video from your computer or laptop, there's really no easy way. However, I did find two solutions that might be able to do this. First of all, and this may sound ironic since we're on an Arduino Stackexchange, you could use a Raspberry Pi (and this is the easily solution I can think of) though I believe your instructor prefers if you use the Arduino instead. Second, and this took me forever to find on the internet, you could use a third party software called "Gobetwino" and you can check out what that does [here](http://www.mikmo.dk/gobetwino.html). I saw on [YouTube video](https://www.youtube.com/watch?v=zHCnCrifyyY) of a quick little demonstration of what it does. When the button is pressed, the video is played. That's conditional and you can do the same thing but for the smoke detector.


body:
I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:

    int solenoidPin = 4; //connected to Digital 4
    int moisturePin = A0; //connected to Analog A0

    void setup() {
      Serial.begin(9600);
      pinMode(solenoidPin, OUTPUT);
    }
    void loop() {
      int val;
      moisture = analogRead(moisturePin); //connect sensor to Analog A0
      Serial.println(val); //print the value to serial port
      delay(1000); //wait 1 second for next reading

      if (moisture <= 350) //if moisture is less than reading 350 {
      digitalWrite(solenoidPin, HIGH); //switch solenoid ON
      delay(600000) //water for ten minutes
      digitalWrite(solenoidPin, LOW); //switch solenoid OFF
      }
      else {
      digitalWrite(solenoidPin, LOW); //switch solenoid OFF
      }
    }

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the ``if (moisture <= 350)`` while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?

title: Change conditioning in real time

Answers: 1

body:
>       if (moisture <= 350) //if moisture is less than reading 350 {

That is wrong, because you have the brace `{` **after** the comment. You need it **before** the comment, eg.

     if (moisture <= 350) { //if moisture is less than reading 350

Or preferably in my opinion:

    if (moisture <= 350) //if moisture is less than reading 350
      {

---

> I'm just asking if it's possible to change the `if (moisture <= 350)`

Yes, of course. That's what variables are for. You could read a potentiometer, and the value from that could replace `350` in the code. You could use a simple LCD or LED display to show what the current reading is.

---

>    delay(600000) //water for ten minutes

Your problem here is that the sketch will be totally unresponsive (it would not react to your changing the moisture level) during the time you are watering. You might want to read [How to do multiple things at once](http://www.gammon.cm.au/blink) which shows how you can keep doing other things, while waiting for time to elapse.


body:
I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:

    "Vendor-Specific Device:"

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.

    Atmel 1624 tiny85

title: My Digispark board won't show up in Ports tab in Arduino IDE (OSX)

Answers: 1

body:
I don't think it is supposed to. The Digispark briefly connects in "bootloader" mode, which you spotted as "Vendor-Specific Device:".

Then after 5 seconds it runs the loaded sketch. If your sketch doesn't create a USB port (eg. a keyboard) then it will disappear from the USB list.

See:

http://digistump.com/wiki/digispark/tutorials/connecting

You don't select the port, the core files automatically find the Digispark and program it. You have to plug in the Digispark when instructed, to activate the bootloader.


body: I would like to compile my Arduino sketches in SlickEdit.  I have turned on the verbose compile output in the standard IDE and I can see the compile and switches, but it doesn't appear that there is a Makefile in use.  I don't see the "Entering" and "Leaving" messages that I associate with Make anyway.  Is using a third party tool to control the build an Arduino no-no?  Has anyone used Make to build Arduino?

title: Using SlickEdit to compile Arduino files

Answers: 0


body:
My ciruit:
[![enter image description here][1]][1]

My code:

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    int led = 13;
    const int buttonPin = 2;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
    }

    // the loop routine runs over and over again forever:
    void loop()
    {
      bool buttonState = digitalRead(buttonPin);
      while (buttonState == LOW)
      {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
       tone(12,260);
      {
     }
      }
    }
What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the `tone(12,260);` that I added?
  [1]: https://i.stack.imgur.com/NTkHd.jpg

title: Why is the piezo buzzer not making any sound?

Answers: 1

body:
Both the code and the circuit have problems.

In the code:

• If the `while (buttonState == LOW)` loop is ever entered, it will never be left, because `buttonState`, the controlling variable, does not change within the loop.

The simplest fix is to remove the line `bool buttonState = digitalRead(buttonPin);` and replace `while (buttonState == LOW)` with `while (!digitalRead(buttonPin))`, which says to loop while `digitalRead(buttonPin)` is not true; ie, while it is false, or low.

• The empty braces, `{ }` at the end of the `while` loop are superfluous and should be deleted.

In the circuit diagram:

• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound.  Note, `tone(12,260);` tells the Arduino to use pin 12 for tone output.

To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.

• A blue LED in series with a red LED might or might not turn on when supplied with 5 V.  For example, if the [red LED takes 1.8 V and the blue LED takes 3.3 V to turn on](http://www.evilmadscientist.com/2012/resistors-for-leds/), the 5.1 V total is too high to be turned on by 5 V signals.  Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.


body:
HELLO I have already connected with I2C 2 Arduino's all is working with comunication on Bus I2C. My Setup is :
MASTER with LCD I2C , RTC1037
SLAVE some sensor not I2C

I allready put 2 pullup resistor 10Kohm on SDA and SCL

I need to switch off the slave arduino but when i switch off the Slave board the Master Arduino stop working.Why? It's possible to continue working with master board and the slave board switch off? Thank's for help

title: I2C between 2 or more Arduino boards

Answers: 1

body:
You need to isolate the slave device from the I2C bus since it is causing interference with the signals.

Adafruit have published a good [application note](https://cdn-shop.adafruit.com/datasheets/an97055.pdf) about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

> **2.3.4 Isolation of the powered-down “Lower voltage” section.**
>
> An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when
VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s [sic] are switched off because VGS is
below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a
noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must
stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2
may have the same value, e.g. both 3.3V or both 5V.


body:
Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...

The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?

I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()

I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.

LCD version: QAPASS 1602A

Here is an example:

byte Ghost[8] = {
  0b00000,
  0b01110,
  0b01110,
  0b10101,
  0b11111,
  0b11111,
  0b11111,
  0b10101
};

lcd.createChar(0, Ghost);

So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?

title: Arduino LCD Display 2x16 custom char byte limit

Answers: 1

body:
> there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.

Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:

    // Definitions for data in program space
    #include <avr/pgmspace.h>

    // Place the character table in Flash
    byte const Ghost[8] PROGMEM = {
       0b00000,
       0b01110,
       0b01110,
       0b10101,
       0b11111,
       0b11111,
       0b11111,
       0b10101
    };

    // Read a byte of character data
    OneByte = pgm_read_byte(&Seg7_segtbl[index]);

Update:

> LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, [its datasheet][1]says it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).

  [1]: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf


body:
I am trying to establish a communication between a sensor and a M0 -pro using SPI. The code :

        #include <SPI.h>

        unsigned int result  = 0;
        void readAngle();

        void setup() {
          Serial.begin(9600);
          SPI.setBitOrder(MSBFIRST);
          SPI.setClockDivider(SPI_CLOCK_DIV8); //sets the clock speed for data transfer, slowed down 8 times
          SPI.setDataMode (SPI_MODE1);

          digitalWrite(11,HIGH);
          pinMode(11,OUTPUT);

          SPI.begin();
          SerialUSB.println("First Try");
    }

        void loop() {
          readAngle();
          SerialUSB.println(result);
          delay(500);

    }

        void readAngle(){
            digitalWrite(11,LOW); //Turn SS on, start communication
            result = SPI.transfer16(0xFFFF); // the read command and the response received
            result = (result << 2) >> 2; // get rid of the last 2 bits, error(14) + parity(15)
            digitalWrite(11,HIGH); //Turn SS of

    }

The code works perfectly with an UNO, but with M0, it event doesnt print the first `SerialUSB.println("First Try");`. The moment i erase the lines that have SPI commands in it, the serial monitor starts working again. As i said in the titel i am using the ICSP port on M0. I use the native usb port to programm.

I think i am missing something very basic. I checked many different forum posts, but there is no indication of M0 requiring other SPI commands. Any help is much appriciated.

PS: i didnt go into detail with the sensor and its datasheet because since it works fine with uno, the cause of the problem should be it.

title: M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port

Answers: 2

body: Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.

body:
You must declare that the pin as an output before you use it.

Do this by using the [`pinMode()`][1] function, like this:

    pinMode(11, OUTPUT);          // sets the digital pin 11 as output

Add the above line at the beginning of your `setup()` function.

  [1]: https://www.arduino.cc/reference/en/language/functions/digital-io/pinmode/


body:
To keep the question short:

I'm trying to burn a bootloader on my Arduino Uno using an Arduino Uno. Could someone please tell me the pin connections? Thanks.

title: Program Arduino Uno via Nano

Answers: 1

body:
To burn a bootloader from source Nano to target Uno make the following connections:

    Nano.Pin   Uno.Pin

    10         Reset

    11         11

    12         12

    13         13

    GND        GND

See here for more details: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


body:
first of all I'm sorry for my english.

My problem is that I want to use an array of numbers on a function, but I'm getting a weird result inside a for loop. Doing some tests I've seen that it happens even in the simplest sketch so I should be doing something wrong.

I've created a two level int and I want to iterate through the second level using a for loop. Outside the for loop all data gotten from that array is OK, but just inside the loop I'm just getting garbage as if the array was not initialized.

My simple sketch is this:

    const int number_small[][14] PROGMEM = {
      {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
    };

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

      Serial.print(String(number_small[0][0]) + "\n");
      Serial.print(String(number_small[0][1]) + "\n");
      Serial.print(String(number_small[0][2]) + "\n");
      Serial.print(String(number_small[0][3]) + "\n");
      Serial.print(String(number_small[0][4]) + "\n");
      Serial.print(String(number_small[0][5]) + "\n");
      Serial.print(String(number_small[0][6]) + "\n");
      Serial.print(String(number_small[0][7]) + "\n");
      Serial.print(String(number_small[0][8]) + "\n");
      Serial.print(String(number_small[0][9]) + "\n");
      Serial.print(String(number_small[0][10]) + "\n");
      Serial.print(String(number_small[0][11]) + "\n");
      Serial.print(String(number_small[0][12]) + "\n");
      Serial.print(String(number_small[0][13]) + "\n\n\n");

      for (int i = 0; i<14; i++){
        Serial.print("I: " + String(i) + " - " + String(number_small[0][i]) + "\n");
      }
    }

    void loop() {
    }

And the output is:

    124
    124
    387
    387
    399
    399
    443
    443
    483
    483
    387
    387
    124
    124

    I: 0 - 0
    I: 1 - 184
    I: 2 - 0
    I: 3 - 1
    I: 4 - 0
    I: 5 - -18248
    I: 6 - -18248
    I: 7 - -18248
    I: 8 - 0
    I: 9 - 135
    I: 10 - 0
    I: 11 - 0
    I: 12 - 769
    I: 13 - 0

What I'm doing wrong?,

Thanks!!

title: Weird result printing an array using a loop

Answers: 3

body:
Constants like `String(number_small[0][0])` are optimized by compiler during the build (=compile time).

However that's not the case of loop. So you have to use specific functions for reading values from `PROGMEM` in the runtime:

    for (int i = 0; i<14; i++){
      Serial.print("I: ");
      Serial.print(i);
      Serial.print(" - ");
      Serial.println((int)pgm_read_word(number_small[0]+i));
    }

Btw: Don't use string concatenations. These are extremely hungry for the memory. See Majenko's article: [The Evils of Arduino Strings][1]

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

body:
I was sure that I was doing something wrong and yes... Finally I did another test (storing the array on SRAM instead on PROGMEM) and it worked, so I've changed my "research direction" and I've found the solution.

With my initial sketch I was reading the PROGMEM from outside the loop, but from inside the loop what i read is the SDRAM, so I've to use the **pgm_read** functions to force to read from PROGMEM, and now finally is working:
> pgm_read_word(number_small[0] + i)

    const int number_small[][14] PROGMEM = {
      {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
    };

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

      Serial.print(String(number_small[0][0]) + "\n");
      Serial.print(String(number_small[0][1]) + "\n");
      Serial.print(String(number_small[0][2]) + "\n");
      Serial.print(String(number_small[0][3]) + "\n");
      Serial.print(String(number_small[0][4]) + "\n");
      Serial.print(String(number_small[0][5]) + "\n");
      Serial.print(String(number_small[0][6]) + "\n");
      Serial.print(String(number_small[0][7]) + "\n");
      Serial.print(String(number_small[0][8]) + "\n");
      Serial.print(String(number_small[0][9]) + "\n");
      Serial.print(String(number_small[0][10]) + "\n");
      Serial.print(String(number_small[0][11]) + "\n");
      Serial.print(String(number_small[0][12]) + "\n");
      Serial.print(String(number_small[0][13]) + "\n\n\n");

      int i;
      for (i = 0; i<14; i++){
        Serial.print("I: " + String(i) + " - " + String(pgm_read_word(number_small[0] + i)) + "\n");
      }
    }

    void loop() {
    }

Thanks and greetings!!

body:
I refined your own answer:

 - No need to use String to print a numeric value; just print the value.
 - No need to add "\n" add the end of `print`, use `println`instead.
 - No need to concatenate strings for printing; just print them one by one.
 - In a `for` loop, declare the control variable *inside*

Code

    const int ITEMS = 14;
    const int number_small[][ITEMS] PROGMEM = {
      {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
    };

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

      for (int i=0; i < ITEMS; i++) {
        Serial.println(pgm_read_word(number_small[0]+i));
      }
      Serial.println();  Serial.println();
      for (int i = 0; i < ITEMS; i++){
        Serial.print("I: "); Serial.print(i); Serial.print(" - " );
        Serial.println(pgm_read_word(number_small[0] + i));
      }
    }

    void loop() {
    }


body:
I assumed the microcontroller has 3 components as per storing data:
- flash memory for the program
- RAM for variables
- EEPROM for non-volatile user-storage

And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.

I compiled this program:

    #include <EEPROM.h>

    struct SettingsStruct {
      String server;
      String port;
      String user;
      String password;
      String description;
    } gSettings = {
      "192.168.1.6",
      "8080",
      "fci blah vlak",
      "zangazang4",
      "Extra string here"
    };

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

      //saveConfig();

      Serial.print(F("EEPROM size is: "));
      Serial.print(EEPROM.length());
      Serial.print(F(" bytes"));
      Serial.println("");

      loadConfig();
      Serial.print(F("Server: "));
      Serial.print(gSettings.server);
      Serial.println("");
      Serial.print(F("Port: "));
      Serial.print(gSettings.port);
      Serial.println("");
      Serial.print(F("Username: "));
      Serial.print(gSettings.user);
      Serial.println("");
      Serial.print(F("Password: "));
      Serial.print(gSettings.password);
      Serial.println("");
      Serial.print(F("Description: "));
      Serial.print(gSettings.description);
    }

    void loop()
    {
      // nope
    }

    void loadConfig() {
        for (unsigned int t=0; t<sizeof(gSettings); t++)
          *((char*)&gSettings + t) = EEPROM.read(t);
    }

    void saveConfig() {
      for (unsigned int t=0; t<sizeof(gSettings); t++)
        EEPROM.write(t, *((char*)&gSettings + t));
    }

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.

This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.

Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.

title: Is EEPROM's location relocated on sketch compile?

Answers: 1

body:
The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.

You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.


body:
I'm trying to send and receive some data from one Arduino to another Arduino. I'm using an Arduino Uno and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. For transmitting I use the Radiohead library.

I want to send two strings and save them as different strings. My receiver code is:

    #include <RH_ASK.h>
    #include <SPI.h> // Not actualy used but needed to compile

    RH_ASK driver;

    void setup() {
      Serial.begin(9600); // Debugging only
      if (!driver.init())
        Serial.println("init failed");
    }

    void loop() {
      uint8_t buf[200];
      memset(buf, '\0', 200);
      uint8_t buflen = sizeof(buf);
      if (driver.recv(buf, &buflen)) {
        // Non-blocking
        Serial.print("Message: ");
        Serial.println((char*)buf);
      }
    }

First of all, why do I have to use `#include <SPI.h>`? To receive I use:

    if (driver.recv(buf, &buflen)) {
      // Non-blocking
      Serial.print("Message: ");
      Serial.println((char*)buf);
    }

This code saves the output as one output! How can I specify which input is the first one and which is the second one?

title: How can I receive several inputs from wifi and save them?

Answers: 0


body:
I have 2 rows of 12 MAX7219 connected in series with DOUT to DIN (rows are isolated). Now the thing is I am using `LedControl` Library to work with it. The problem is the last 4 Matrices on both the rows don't work. The sequence in my code is like this where `(row, column, matrix)` is used to define the row and column of the matrix and I am talking about a single ROW from two ROWs of 12.

    Sequence in Code      What Happens
    ----------------      -----------------
    (0, 1, 0)             (0, 1, 0)
    (0, 1, 1)             (0, 1, 9)
    (0, 1, 2)             (0, 1, 1)
    (0, 1, 3)             (0, 1, 10)
    (0, 1, 4)             (0, 1, 2)
    (0, 1, 5)             (0, 1, 11)
    (0, 1, 6)             (0, 1, 3)
    .                     .
    .                     .
    .                     .
    (0, 1, 11)            (0, 1, 8)

Now I can understand why does this happens. This code works like this even if the `Device Count` is 8.

Code:

    #include "LedControl.h"
    LedControl row1=LedControl(2,4,3,12);
    LedControl row2=LedControl(5,7,6,12);

    unsigned long delaytime=500;

    void setup() {
      int d_row1 =row1.getDeviceCount();
      for(int address=0;address<d_row1;address++) {
        row1.shutdown(address,false);
        row1.setIntensity(address,15);
        row1.clearDisplay(address);
      }

      int d_row2 =row2.getDeviceCount();
      for(int address=0;address<d_row2;address++) {
        row2.shutdown(address,false);
        row2.setIntensity(address,15);
        row2.clearDisplay(address);
      }
    }

    void loop() {
      int devices=row1.getDeviceCount();
      for (int i = 0; i < devices; i++){
        delay(delaytime);
        row1.setLed(i,0,0,true);
        row2.setLed(i,0,0,true);
        delay(delaytime);
        row1.setLed(i,0,0,false);
        row2.setLed(i,0,0,false);
      }
    }

**EDIT**
I just noticed something, there is no data going to the last 4 matrices. The timings of the blinking of the LEDs on last 4 matrices does not ties correctly (500ms) but it is in fact 250ms (i.e. half time). It means the blinks on last 4 matrices are between pulses of the first 4 matrices.

title: MAX7219 not behaving as expected

Answers: 3

body: Have you checked the wiring between matrices and/or swapped modules in case there is a faulty one in the sequence?

body:
Looking at your library source, it seems the number of devices is clamped at 8. This isn't a hard limit imposed by the chip but rather practical design. SPI, especially at high speeds, can get unreliable when the bus capacitance, related to the cable lengths, gets so high that signals are skewed beyond recognition. Also the buffer in the library used to hold the row data is 64 bytes in size, intended to hold the data for 8 devices with 8 rows each.

You can edit the library to make it support 12 devices though it will require attention to detail like, increasing the buffer to 96 bytes, getting rid of short-circuits within the methods that make sure that no more than 8 devices can be addressed, for-loops, etc.

body:
After fiddling around with various Libraries, I came across this one.

[MD_MAX72XX][1]

It has all the functionalities that I needed with a good Simple Wiki to get you started.

Also it is simple enough that even a noob like me could figure it out.

Regards

  [1]: https://github.com/MajicDesigns/MD_MAX72XX "MD_MAX72XX"


body:
I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads [here][1]. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?

  [1]: https://arduino.stackexchange.com/questions/432/how-can-i-connect-to-an-arduino-using-wifi

title: Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?

Answers: 2

body: NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.

body:
I went through almost the exact same thing you are going through when I was looking at the ESP8266 boards (the NodeMCU is one of those).  I too discovered that the NodeMCU is a micro computer in itself, even more powerful than the Arduino UNO!

You can even code the NodeMCU using the Arduino IDE.  As has been said previously, I'd use your NodeMCU directly to accomplish what you want to do.


body: I'm going to implement home automation using an Arduino Mega with 8*6=48 channels relay in my new home. I have prepared an Android app for an HC-05 Bluetooth controller. How much time can I keep running an Arduino Mega with all the appliances in a home? Can I keep it working 24/7 for a while?

title: What is the worst time case for Arduino Mega?

Answers: 3

body:
Yes.

(For better guidance than that, we'd need to know more.)

body:
I would be wary of going "all in" if the MCU holds+controls the state of all the relays, especially if there's networking happening in the sketch. That creates a single-point of failure for the whole house. I've found that a brief power outage or an MCU freeze/reboot resets the state. That can be frustrating and downright dangerous in a emergency situation.

An obvious solution is to save the relay states in EEPROM or externally on a server. The issue with those is that EEPROM wears out, and your server might not be available soon after a power-cycle when the MCU needs it to resume (router re-connecting, computer rebooting slower than MCU, etc).

The real solution, and the one that preserves life-safety is having local hardware state for each relay. You need the ability to both read state from the Arduino, and change the state from the Arduino. This can be as simple (yet expensive) as physically latching relays, or a capacitor-backed 1-bit state machine like an RS flip-flop. You can build the flip-flop in a variety of circuits, from shift registers, to a 555, to a simple NPN+n-channel MOSFET coupling (my pref).

The big downside is that this needs two pins for each relay. But, with such "smart relays", you can unplug the Arduino and nothing happens around the house. It also allows non-Arduino things (even a simple button/switch) to control the state of a relay, no matter what's happening with the Arduino at the time, but with the ability of the Arduino to react to that change and not over-write or forget the state. The MCU can reboot on a schedule to keep responsive, without anyone noticing the reboot.

Yes, it adds more complexity and cost, but a manageable amount of both, and the satisfaction difference is hard to truly express. In short, any system should work as reliably as lights did 100 years ago: switches work, and never unexpectedly change. If lights are not working or are turning off unexpectedly in a small fire, things can get ugly quick, especially with guests.

body:
> Can I keep it working 24/7 for a while?

yes, if properly designed.


body:
I am reading the period of pulses from a 600ppturn shaft encoder, using the [FreqPeriod library][1], by Martin Nawrath.

This works using counter1 and the comparator on pin6 and pin7 on the Arduino Uno.

[![ Counter and Capture unit][2]][2]

The period duration for 1-2500Hz is being used in a midi musical instrument to give a speed to volume and a note change at a fixed speed.
This has worked well on the Uno but now I want to use a Mega (which does not have both comparator pins).

So I have tried using the Nick Gammon interrupt sketch. This has produced very erratic results returning both positive and many negative numbers (shown by using "volatile long period;" in the monitor.

Can you tell me what is happening and would it be better to use a counter instead of interrupts?

Hope I have given enough information to be getting on with, many thanks.

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

    // Camera shutter speed timer
    // Author: Nick Gammon
    // Date: 15th January 2012

    volatile boolean started;
    volatile unsigned long startTime;
    volatile unsigned long endTime;
    volatile unsigned long period;
    volatile unsigned long lfrq;

    // interrupt service routine
    void isr () {
        if (started)
            endTime = micros ();
        else
            startTime = micros ();
        started = !started;
    } // end of Pulse Width

    void setup () {
        digitalWrite (2, HIGH); // pull-up
        Serial.begin (9600);
        Serial.println (" Pulse Width test = ");
        attachInterrupt (digitalPinToInterrupt (2), isr, CHANGE); //CHANGE RISING
    } // end of setup

    void loop () {
        if (endTime) {
            period = (endTime - startTime) * 32 ; // pulse width?
            Serial.print (" \n  ");
            Serial.print ( " period =  ") ;
            Serial.print (period) ;
            lfrq = 16000000.0 / period;
            Serial.print(" Hz = "); // one rev per sec = 26666 micros period
            Serial.print( lfrq );
            endTime = 0;
        }
    } // end of loop

  [1]: http://interface.khm.de/index.php/lab/interfaces-advanced/frequency-measurement-library/
  [2]: https://i.stack.imgur.com/jNuNi.jpg

title: Nick Gammon "Camera shutter speed timer"

Answers: 3

body:
> Can you tell me what is happening [...]?

Not really, but here is a wild guess: your input signal is bouncy, the
ISR fires too often, your loop cannot keep up with the rate, and you end
up accessing `endTime` in the ISR and loop simultaneously.

If you have a scope, look at your encoder signal. Is it clean?

> would it be better to use a counter instead of interrupts?

Using the input capture feature of a timer will give you the best
possible accuracy, as you will have single-cycle resolution. In
contrast, `micros()` has only 4 µs resolution (64 times worse) and
the ISR may be delayed by up to ≈ 16 µs by the `TIMER0_OVF`
ISR.

You can use the FreqPeriod library you linked to as an inspiration for
writing your own timer-based code, but it will require some changes:

* As pointed out by Nick Gammon in a comment, you don't need the analog
  comparator, nor the conditioning RC network, as the encoder's outputs
  are already digital. Or you may use a low-pass filter if the encoder
  is bouncy.

* You will use the input capture pins of either timer 4 (digital pin 49)
  or timer 5 (digital pin 48). The other input capture pins are not
  available on the Mega's pin headers.

* You will replace `ISR(ANALOG_COMP_vect)` by either `ISR(TIMER4_CAPT)`
  or `ISR(TIMER5_CAPT)` (the relevant “capture event” ISR). No need to
  adjust a comparator threshold in the ISR.

* In the `begin()` method, you will leave the analog comparator alone,
  and you will enable the capture event interrupt.

Obviously you will have to study [the
datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf)
before start coding.

body:
> Could this be so?

because the code is faulty: there is no assurance of atomicity between startTime and endTime. ie. the interrupts could have arrived, multiple times, while the if loop is executing.

two ways to fix it:

1. calculate period in the isr; or

2. clear endTime once the clock starts in the isr.

body:
While you are doing all those things with those volatile variables in the loop function, the interrupt can still be firing.  If it fires in the middle of a read of startTime or endTime then you get might get part of the variable holding old value and part holding new value and when you put it together it makes garbage.

You need to do a cli() at the beginning of loop to turn off interrupts and quickly make local copies of all those variables and then sei() to turn interrupts back on.  Now you can safely work with the copies you made.