body:
I'm using the ATtiny x5 series board, compiling my project (.cpp.ino file).  Whenever I use the **max(*a*,*b*)** macro, I receive this message:

    "C:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.3-arduino2/bin/avr-g++" -c -g -Os  -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=attiny85 -DF_CPU=8000000L -DARDUINO=10609 -DARDUINO_AVR_ATTINYX5 -DARDUINO_ARCH_AVR   "-IC:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\cores\tiny" "-IC:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\variants\tinyX5" "-IC:\Documents and Settings\<user>\My Documents\Arduino\libraries\Pins_xxxxx" "-IC:\Documents and Settings\<user>\My Documents\Arduino\libraries\TinyWireS" "C:\WINDOWS\TEMP\build18f8c74edd63168be814edc24cb0a11a.tmp\sketch\AT85PWM.ino.cpp" -o "C:\WINDOWS\TEMP\build18f8c74edd63168be814edc24cb0a11a.tmp\sketch\AT85PWM.ino.cpp.o"
    C:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\cores\tiny/Arduino.h:54:24: note: in definition of macro 'max'
     #define max(a,b) ((a)>(b)?(a):(b))
                            ^
What does *note: in definition of macro 'max'* mean, do I need to do anything about it, and if so what?

Searching google for the message gives lots of compiler output listings with the message, but the posting is always for *another **different** message* that is causing trouble.  None of the fixes from those posts address the max note: message.

title: GCC msg "note: in definition of macro 'max'" error message

Answers: 2

body:
Note to the future:

(My particular case was a function call with several parameters.  One had the **max(a,b)**, and another parameter had an error.  It used a different macro, which may have pushed the compiler to flag *every* macro in the whole call).

The message seems like a red herring, given that there is no problem with the **max(a,b)** macro definition.  I suspect it is being flagged only because it was tangentially involved with a statement in error.

Since it wasn't part of the problem, the compiler couldn't say anything specific about it or the code it generated.  Therefore the flagging message then ends up saying "in definition of macro" (kind of a default of last resort) since it couldn't say anything more specific.

If you ever get one of these, particularly from a system provided macro, ignore it until you've diagnosed your other problems.

Ignore the fact that the error message is first in the listing, and the statement using the macro doesn't get flagged until after several other statements are flagged.

Again, I suspect that compiler feels obligated to say something about the macro because it was used.  But since it's not part of the problem in the statement where it appears, it doesn't get flagged there.  Instead the compiler puts the message at the top because it has to go somewhere, but the compiler can't/doesn't want to associate it with the statement where it was used.

The solution worked for me, but a language lawyer or compiler developer may say my explanation has no basis.

body:
I can reproduce your message easily enough:

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

    #define max(a,b) ((a)>(b)?(a):(b))

    void setup() {
     int b = 66;
     unsigned int c = 42;
     analogWrite (3, max (b, c));
    }

    void loop() { }

I get these warnings:

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

    /tmp/arduino_modified_sketch_857720/sketch_aug31a.ino: In function 'void setup()':
    /tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:1:25: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     #define max(a,b) ((a)>(b)?(a):(b))
                             ^
    /tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:6:18: note: in expansion of macro 'max'
      analogWrite (3, max (b, c));

The point is that the warning `note: in expansion of macro 'max'` is just telling you where the macro is *defined*, so you can make sense of the *real* warning. The *real* warning <!-- language: lang-c++ -->is: `warning: comparison between signed and unsigned integer expressions`

So, reading them together, you are comparing (in the macro) a signed and unsigned number, and the compiler is warning you about that.

> The message seems like a red herring, given that there is no problem with the max(a,b) macro definition. I suspect it is being flagged only because it was tangentially involved with a statement in error.

That's right. There is no problem in that macro per se. Macros can generate weird error message because they are just text replacements. For example:

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

    max (the quick brown fox, jumps over the lazy dog);

That will generate a slew of errors, including a "note" to where `max` is defined. There is nothing wrong with `max` until you try feeding garbage into it.

---

# Templates

That's one of the reasons I prefer to avoid macros if possible. You can do "max" with a template. For example:

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

    #undef max   // throw away the original macro in the Arduino header file

    template<typename T> T max (T a, T b)
      {
      if (a > b)
        return a;

      return b;
      }

Now you get slightly more reasonable error messages:

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

    /tmp/arduino_modified_sketch_711186/sketch_aug31a.ino: In function 'void setup()':
    sketch_aug31a:14: error: no matching function for call to 'max(int&, unsigned int&)'
       analogWrite (3, max (b, c));
                                ^
    /tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note: candidate is:
    /tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note: template<class T> T max(T, T)
     template<typename T> T max (T a, T b)
                            ^
    /tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note:   template argument deduction/substitution failed:
    /tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note:   deduced conflicting types for parameter 'T' ('int' and 'unsigned int')
       analogWrite (3, max (b, c));
                                ^
    exit status 1
    no matching function for call to 'max(int&, unsigned int&)'

Of course, now you've gone from a warning to an error, because the template wants a single type.

Notice the notes? That's just the compiler trying to be helpful.

---

You could make the template take two types if you are prepared to guess the return type (will it be the first type, or the second type?):

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

    #undef max

    template<typename T1, typename T2> T1 max (T1 a, T2 b)
      {
      if (a > b)
        return a;

      return b;
      }

Now you don't get an error or a warning, however the result will be the first type (T1) which may or may not suit you.


body:
I am looking to purchase the correct hardware to be able to control 5 DC Motors from an Arduino (UNO preferred, MEGA if necessary).

The Specs of the Motors are as follows: 12 V nominal, 3 → 12 V dc, 794 gcm, 100 rpm, 0.394 W

What would be your recommendations for how to set this up? As I am fairly new to circuitry a circuit diagram would be helpful along with the recommendation of what shield or drivers to use. Thank You

title: Controlling 5 DC motors with Arduino

Answers: 2

body: There are currently no expansion boards (shields) for the Arduino platform that are designed to do what you're asking of it. At most you'll find shields that can support up to 2 maybe 3 motors. My recommendation for a beginner would be to experiment with a breakout board like this one: https://www.sparkfun.com/products/9457 It's compact and can easily control 2 of the motors you need, three together and you could control up to 6.

body: I would suggest to use the shield that is directly attachable to the Uno, for example: http://playground.arduino.cc/Main/AdafruitMotorShield. So everything you need is Uno, this shield and motors. No soldering.


body:
I am trying to solder arduino nano onto a perfboard/solderable breadboard using rosin core solder. The connection is only working some of the time, when I check with a multimeter (+) at pin 29 (in image below) I and (-) at pin 17 there is power at the top of the pin sticking out of the via/hole but there is 0 volts if I check at the actual joint (lower portion of the pin). I see a little flux residue around pin 29 that could indicate a little burning around the area could that be causing this, it is only very minor .. anyway I can fix it?

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

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

Also is it normal  to have a little yellow residue left over on the joints? I am new to soldering so not sure if a little flux reside is a bad thing on the joint...

  [1]: https://i.stack.imgur.com/QVrbD.jpg
  [2]: https://i.stack.imgur.com/zdt0J.jpg

title: Soldering issue with arduino

Answers: 2

body:
Fair play, that is a lot of flux residue. I am assuming you are using some quite chunky solder with lots of flux in it.

Flux is non-conductive, so the residue will be forming an insulating layer on the outside of the solder. That doesn't mean the joint is bad, only that you can't get to the joint because the flux residue is in the way.

If there is a conductive path between the tip of the pin and the pad next to it then all is fine. The fact that you can't see the signal through the outside layer of flux is neither here nor there.

If you want to clean it off you can use isopropyl alcohol (AKA PCB cleaner, AKA "rubbing alcohol") and use, for instance, a tooth brush to scrub it off.

body:
“The connection is only working some of the time” does seem to indicate bad solder connections.  (Another possibility is wires in wrong holes.)

To locate problems, clip (rather than hold) one lead of an ohmmeter (or a DVM set to Ohms), to a wire soldered to the beginning of the problematic chain of connections.  Then advance step by step along the chain, looking for an open junction.

To fix problems, obtain a [solder sucker](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1558&bih=809&q=solder+sucker&oq=solder+sucker&gs_l=img.3..0j0i24k1.2220.2220.0.2622.1.1.0.0.0.0.86.86.1.1.0....0...1ac..64.img..0.1.85.7MJKU7cTv-I) and/or [solder wick](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1558&bih=809&q=solder+wick&oq=solder+wick&gs_l=img.3..0j0i30k1j0i5i30k1j0i24k1l7.7138.7138.0.7590.1.1.0.0.0.0.98.98.1.1.0....0...1ac..64.img..0.1.96.W8GDYoimbVs), a hot fine-point [soldering iron](https://www.google.com/search?hl=en&biw=1558&bih=809&site=imghp&tbm=isch&sa=1&q=fine-point+soldering+iron++temperature+controlled&oq=fine-point+soldering+iron++temperature+controlled&gs_l=img.3...5190.5190.0.6163.1.1.0.0.0.0.77.77.1.1.0....0...1c.1.64.img..0.0.0.7Ojx_1olWYA) (preferably temperature controlled), and thin (eg 1-2mm) 60-40 tin-lead rosin-core solder.  Use the solder wick or solder sucker to remove the old solder from the joint.  Apply new solder to make a nice shiny [proper solder joint](https://www.google.com/search?hl=en&biw=1558&bih=809&site=imghp&tbm=isch&sa=1&q=proper+solder+joint&oq=proper+solder&gs_l=img.1.0.0l2j0i8i7i30k1j0i30k1j0i24k1l6.134559.135287.0.137694.6.6.0.0.0.0.119.477.4j1.5.0....0...1c.1.64.img..1.5.473...0i7i30k1j0i7i10i30k1j0i7i5i30k1.kemV59fMwUI).


body:
I want to use my Atmega328P in 8MHz, but I noticed that the internal clock is not as accurate and cause problems in my application. To add an external crystal 8MHz I do like the image below or 22pF capacitors are only necessary when I use a 16MHz crystal?

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

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

title: Arduino running at 8MHz with external crystal

Answers: 1

body:
Yes, you require the capacitors, and the capacitors have to be the right value for your crystal.

The datasheet will specify a *load capacitance* which you use in the following formula:

    C1 = C2 = 2(CL - C_STRAY)

That is, the *load capacitance* of the crystal, minus the stray capacitance from your circuit (as long as your traces are short that is negligible and can be largely ignored unless you have very very tight timing requirements) multiplied by 2.

So for 22pF capacitors it is safe to assume that the crystal that is with them has a load capacitance of 11pF.

So check the datasheet for the load capacitance (it should be very prominent) and select the correct capacitors accordingly.

If you want to do away with the capacitors and your timing requirements aren't that precise you may get away with a ceramic resonator which doesn't require capacitors.

Another option is to use a MEMS® clock chip which generates a stable clock signal at a pre-set frequency. While this doesn't require capacitors for the clock signal it does still require a decoupling capacitor on the power supply for it, but of course that doesn't affect the timing of the clock signal, so precise selection of a specific value isn't needed.


body:
When I use DHCP with `ether.dhcpSetup()` the DNS lookup for NTP `ether.dnsLookup("0.pool.ntp.org")` works fine, but when I use a static setup (because my Android app needs to know the IP address) with `ether.staticSetup(myip);` then this returns false and I don't get an IP address from the NTP pool. How come?

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray.

Full MWE:

    #include <EtherCard.h>      // https://github.com/jcw/ethercard
    #include <Time.h>           // http://www.arduino.cc/playground/Code/Time

    static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
    static byte myip[] = {192, 168, 2, 106};
    const char poolNTP[] PROGMEM = "0.pool.ntp.org"; //pool to get time server from
    uint8_t ntpMyPort = 123; //port for the time server, no idea why needed

    byte Ethernet::buffer[700];

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

     //do not forget to add the extra '10' argument because of this ethernet shield
      if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {
        Serial.println(F("Failed to access Ethernet controller"));
      }

      //static setup
      ether.staticSetup(myip);
      ether.printIp("Address: http://", ether.myip);

     //this works
    //  if (!ether.dhcpSetup())
    //    Serial.println(F("DHCP failed"));

      //Find ip address of a time server from the pool
      if (!ether.dnsLookup(poolNTP)) {
        Serial.println("DNS failed"); //with static setup this line is executed, not so with DHCP
      }
      ether.printIp("Lookup IP   : ", ether.hisip);
    }

    void loop () {}

title: dns lookup only works with DHCP and not with static setup (EtherCard library)

Answers: 2

body:
DHCP does more than just give you your IP address: it also gives you the Net Mask, the Gateway IP address, and the DNS Server IP address. If you don't call `dhcpSetup()`, you'll have to do it yourself.

According to the `EtherCard` documentation, you can do that as follows:

    const static uint8_t ip[] = {192,168,0,100}; // Example
    const static uint8_t gw[] = {192,168,0,254}; // Example
    const static uint8_t dns[] = {192,168,0,1};  // Example

    ...

    if (!ether.staticSetup(ip, gw, dns)
    {
        // handle failure to configure static IP address
        // (current implementation always returns true!)
    }

body:
the documentation of ethercard.h and examples doesn't fit the actual version of *ethercard* very well.

for static ip setup use:

    ether.staticSetup(myip, gwip, dnsip, netmask);

then the dnslookup works. most examples use the old **mymask** name, that is replaced by **netmask**


body:
I'm using an Atmega328p SMD with 32 pins.  I'm trying to get several pins on Port D to function as inputs.  As outputs, they work fine, but for some reason, not as inputs.  Here's a simple example of what I'm dealing with.

    void setup() {

    DDRB |= (1<<PB3);  //Set up an output on PB3 for an LED
    DDRD = B00000000;  //All of Port D set as inputs
    DDRC = B00000000;  //All of Port C set as inputs
    }

    void loop() {

    int Power = (PIND & (1 << PORTD5));  //Read input

      if(Power == 1){
    PORTB |= (1 << PORTB3);      //set high
      }
      else{
      PORTB &= ~(1 << PORTB3);  // set  low
    }
I get no response from my LED like this, no matter which pin on Port D I use as an input.  But when I simply change over to Port C, it works fine.

    int Power = (PINC & (1 << PORTC5));  //Read input
Ideas?

title: Port D isn't Working as Input

Answers: 1

body:
You check if `power` is `1`, but it will never be `1`. Instead it will be `1<<5` or `32`. Better use:

    if(Power != 0){
      PORTB |= (1 << PORTB3);      //set high
    }
    else{
      PORTB &= ~(1 << PORTB3);  // set  low
    }


body:
I have bought MPU-6050 a month ago for a project, I have got a hang I2C protocol and register maps of MPU. I have learnt how to get raw values of accelerometer and gyroscope. What I needed for my project is roll and pitch angles and acceleration in x,y,z axes. I have tried some algorithms as shown below:

 First I saw a code which uses only raw accelerometer values to get roll and pitch. Here is a small snippet of that code:

    x=(AcX)/16384;
    y=(AcY)/16384;
    z=(AcZ)/16384;
    roll = (atan2(y, z)+PI)*57.295779513082320876798154814105;
    pitch = (atan2(x , z)+PI)*57.295779513082320876798154814105;
As you can see this uses principle of angle between two vectors, the angles were pretty accurate. But the problem with this code is that as the sensor moves in a particular direction without changing the roll or pitch they still seemed to change (The roll and pitch values are dependent on accel values).

Next, I saw about using Complementary Filter my code:

    #include<Wire.h>
    const int  MPU_addr=0x68, dt=20;
    float AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
    float xa,ya,za,xg,yg,zg;
    float gan_x = 0 ,gan_y = 0,aan_x = 0,aan_y = 0, anx = 0, any = 0, gain  =0.95;
    int xao = -521 ,yao = 1073 ,zao = 1724 ,xgo = 94 ,ygo =31 ,zgo = 60;                       //offset values
    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x1A);
      Wire.write(0b00000110);
      Wire.endTransmission(true);
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x1B);
      Wire.write(0b00000000);
      Wire.endTransmission(true);
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x1C);
      Wire.write(0b00000000);
      Wire.endTransmission(true);
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);
      Wire.write(0b00000000);
      Wire.endTransmission(true);
    }
    void loop()
    {
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      xa = (AcX-xao)/16384;                                                    //sensitivity adjusting
      ya = (AcY-yao)/16384;
      za = (AcZ-zao)/16384;
      xg = (GyX-xgo)/131;
      yg = (GyY-ygo)/131;
      zg = (GyZ-zgo)/131;
      gan_x = dt * xg + anx;                                                       // integrating
      gan_y = dt * yg + any;
      aan_x = (atan2(ya,za)+PI)*57.295779513082320876798154814105;
      aan_y = (atan2(xa,za)+PI)*57.295779513082320876798154814105;
      anx = (gain) * gan_x + (1-gain) * aan_x;                                     // filtering
      any = (gain) * gan_y + (1-gain) * aan_y;
      //Serial.print(" | GyX = ");
      Serial.print(gan_x);
      Serial.print(" ");
      //Serial.print(" | GyY = ");
      Serial.println(gan_y);
    }
This code gives good gyroscope values in terms of angular velocity but I want it in degrees is there any way to change those gyro values to degrees(like in first case)?

I saw Jeff Rowberg's library and I can't seem understand all of the code. Can anyone please provide any reference material explaining the functions present in i2cdevlib.h (Ex: mpu.dmpInitialize(), mpu.setDMPEnabled() etc) it would be a lot of help.

I also would like to know if there are any other alternative IMUs (Gyro+accel) other than MPU6050 which are more of an open source than 6050 (in terms of accessing DMP which seems to be main drawback for MPU) and easier to work with.

I am using Arduino Nano.

-Thank you in advance

title: Help with MPU-6050

Answers: 1

body:
I finally got this working after one sleepless night

    #include<Wire.h>
    const int MPU = 0x68;
    int t = 0,dt = 1;
    int AcX,AcY,AcZ,GyX,GyY,GyZ,tmp;
    int AcXo,AcYo,AcZo,GyXo,GyYo,GyZo;
    float roll = 0,pitch = 0,rollgy = 0,pitchgy = 0,rollac = 0,pitchac = 0,Ax,Ay,Az,Gx,Gy,Gz,gain = 0.95;
    void MPUconfig(int Addr,int data)
    {
      Wire.beginTransmission(MPU);
      Wire.write(Addr);
      Wire.write(data);
      Wire.endTransmission();
    }
    void MPUread()
      {
        Wire.beginTransmission(MPU);
        Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
        Wire.endTransmission();
        Wire.requestFrom(MPU,14);  // request a total of 14 registers
        AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
        AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
        AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
        tmp=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
        GyX=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
        GyY=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
        GyZ=Wire.read()<<8|Wire.read();
      }
    void offset()
    {
      MPUconfig(0x1A,0b00000000);
      int ax = 0, ay = 0,az = 0,gx = 0,gy = 0,gz = 0,i;
    MPUread();
    MPUread();
    ax = AcX;
    ay = AcY;
    az = AcZ;
    gx = GyX;
    gy = GyY;
    gz = GyZ;
    for(i=0;i<1100;i++)
    {
        MPUread();
        if(i>100)
        {
          ax = (ax+AcX)/2;
          ay = (ay+AcY)/2;
          az = (az+AcZ)/2;
          gx = (gx+GyX)/2;
          gy = (gy+GyY)/2;
          gz = (gz+GyZ)/2;
        }
        delay(2);
     }
    AcXo = ax;
    AcYo = ay;
    AcZo = 16384-az;
    GyXo = gx;
    GyYo = gy;
    GyZo = gz;
    MPUconfig(0x1A,0b00000110);
    }
    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      MPUconfig(0x1A,0b00000110);
      MPUconfig(0x1B,0b00000000);
      MPUconfig(0x1C,0b00000000);
      MPUconfig(0x6B,0b00000000);
      offset();
    }

    void loop()
    {
      t = millis();
      MPUread();
      Ax = (float)(AcX-AcXo)/16384;
      Ay = (float)(AcY-AcYo)/16384;
      Az = (float)(AcZ-AcZo)/16384;
      Gx = (float)(GyX-GyXo)/131;
      Gy = (float)(GyY-GyYo)/131;
      Gz = (float)(GyZ-GyZo)/131;
      pitchgy = (Gy * ((float) dt/1000)) + pitch;
      rollgy = (Gx * ((float) dt/1000)) + roll;
      pitchac = atan2(Ax,Az) * (float)(180/PI);
      rollac =  atan2(Ay,Az) * (float) (180/PI);
      roll = gain * rollgy + (1-gain)* rollac;
      pitch = gain * pitchgy + (1-gain) * pitchac;
      Serial.print(roll);
      Serial.print(" "); Serial.print(pitch);
      Serial.println(" ");
      dt = millis()-t;
    }


body:
How to increase current in O/P port in Arduino uno ?
to make it 200mA How I can do this?
It can in proggraming add more current
Which sample way to increase current ?
To control 2 Dc motor which normally work with 3 AA battery
Thanks

title: How to increase current in Arduino uno?

Answers: 1

body: You add a transistor. Just like when you're controlling a relay, which *needs more current that the Arduino can provide*.


body:
I've got my sim900 module working with arduino by using their software serial library, however, I want to eliminate arduino from the equation and have serial communication directly to sim900 module.

I'm using putty as my terminal emulator. It's serial is configured to `COM1 19200 8 N 1` the same as device manager configuration for this port.

I connect straight from hardware serial on my PCs motherboard into serial-to-ttl interface board which connects to sim900 module. The board has 4 pins - VCC GND TX RX. They're all connected to my sim900 hardware serial as follows: `VCC=5V GND=GND TX=TX RX=RX` (Yes I know that it's always actually TX=RX and RX=TX, but when I connect it that way my interface board doesn't blink any led to indicate a transfer whereas it does when I connect TX=TX and RX=RX). The switch on the module is set to hardware serial pins as well.

So the only thing that happens when I send AT commands such as `AT` or `ATI` and press enter is that puttys cursor comes back to the beginning of command that I typed. No response.

I'm thinking that I'm not doing something that the arduinos software serial port is doing when it sends commands to sim900.

Can anyone help please ? It's literally been days of trying different configurations with no results.

In that time besides getting sim900 working with arduino software serial I verified that the hardware serial port on my motherboard is working correctly and the interface board is working correctly as well.

title: SIM900 module not responding on hardware COM port

Answers: 0


body:
The Arduino Uno manual (from the kit) instructs to connect a resistor to GND when lighting an LED on the breadboard with the 5V (socket?). The red, green, and yellow LEDs don't light up so brightly... actually they are barely bright enough to detect. Is it safe to apply all 5 volts by connecting the cathode to the ground with a *wire*? I tried it for a second and it worked... Just don't try it on the blue, I assume that beyond 5V it will explode, it burnt so bright..

Optional: Why does only the blue LED light visibly?

title: Is applying 5 volts to LED dangerous?

Answers: 4

body:
No, you cannot safely power an LED with 5V without a resistor. The resistor is absolutely 100% required.

The resistor isn't put there purely on a whim, it's required to set the current based on the supply voltage minus the LED forward voltage and the resistance of the resistor.

body:
Ah. I found it. From the manual:

> Without the resistor, the LED would be brighter for a few moments, but quickly burn out.

Since 5V is HIGH on this thing, it looks like 5V would be too much for an LED.

Question 2: You were using the wrong resistor (too much resistance). But even with the incorrect resistor, the blue one shined! Strange.

body:
Different color LEDs are not the same.  The are made with different impurities.  And some colors (blue) were really hard to figure out.  [So much so that the blue LED inventor was awarded the Nobel Prize][1]!

Consequently, it should not be assume all LEDs operate at the same voltage and current.  As such, when driving an LED with a constant voltage source, derive the proper series resistance for each case.

Example 1:

Given a red LED which may have 1.8 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

> V = I * R
>
> 5 - 1.8 = 20mA * R
>
> R = (5 - 1.8) / 0.020
>
> R = 160 ohms

Example 2:

Given a blue LED which may have a 3.3 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

> V = I * R
>
> 5 - 3.3 = 20mA * R
>
> R = (5 - 3.3) / 0.020
>
> R = 85 ohms

Your specific LEDs may have different specifications.  The above are only examples.

Go [here][2] for more about calculating the proper LED series resistance.

In general, LEDs that are over driven will grow dimmer and not recover.

  [1]: https://www.nobelprize.org/nobel_prizes/physics/laureates/2014/press.html
  [2]: https://en.wikipedia.org/wiki/LED_circuit#Series_resistor_calculation

body:
Something else to take into consideration (as if this is not complex enough) is that if you're comparing LEDs visually you're not always going to be able to tell if your math is correct.

The human eye is about 3x more sensitive to blue light (and green light for that matter) than it is to red light.

So, presume that you had 3 absolutely identically manufactured LEDs: 1 Red spectrum, 1 Blue spectrum, and 1 White ("full spectrum"). If they are all hooked up with proper current, the Blue LED will appear to be approximately 3x the brightness of the Red LED (to your human eyeballs) and the White LED will appear to be some large factor brighter than the Red LED as well, and likely some factor brighter than the Blue even as it contains more 'spectrum'.

TL;DR: Check your layouts with a volt meter and math, not with your crummy eyeballs.


body:
The first challenge on the Arduino Uno manual is to make a closed circuit with a button and LED. The voltage is provided by the 5V pin (non IO), connected by wire to (+) on the bus (breadboard). The wire connects to a resistor, which **makes sense since it resists current running from source**. The button connects to the resistor, if pushed, the button closes the circuit and current passes through LED (making it shine) and through a wire to GND.

OK. The second challenge makes no sense. The resistors are connected not to the 5V, but the GND. WHY? Doesn't current dissipate past at ground?? As if the GND is supplying power!? It's like flipping the anode/diode! Here's the challenge: ![](https://s10.postimg.org/tn7huuna1/IMG_0499_1.jpg).What is the logic behind connecting the resistors to GND and WHY DOES IT SUPPLY POWER? I'm not talking about the button, which step two somewhat explains but not why, but the LEDs. Thank you thank you thank you!!

EDIT: Ok, then. I am now being told current flows negative to positive. Fine, then why resistor connected to positive? Also, I was told that GND is there to dissipate the energy flowing from positive because some of that energy was lost. Then, could you explain the circuit and whether flow is perpetual or lost at the end (wherever that is) and if it isn't perpetual in a loop, why have a resistor past the LED when the LED recieved all the volts and the electrical energy it then outputs back on the cycle is reduced by the resistor. Thanks.

Also, I'm changing my question to "Why does resistor on GND ever work on LED" to "Why have resistor at end of circuit cycle if GND dissipates final energy?".

Answers: 3

body:
Roman, As I understand your question you have a resistor, an LED and a switch in "series". It makes no difference in which order these are connected. It may help to think like water flowing through a hose, with a tap being a switch - it can be at either end.

"Current" flows through each in turn. As others have mentioned current conventionally is considered to flow from + to - (even though in most, but not all, cases electrons flow from - to +).

In practical circuits it is usually more convenient to select one configuration over another. An Arduino digital pin can be considered as a switch which is either connected to + or -. You could connect a LED (with a current limiting resistor) to either + or -, either is valid it just changes the logic controlling the switch.

body:
To go further with the water analogy as proposed by @Milliways, consider the water system being closed and made of hard pipe (which cannot expand or contract). All of the water (electrical charge) there is, is contained within the closed system. (We'll use a battery instead of a power supply for clarity but it won't make any difference). Think of a simple loop containing a pump & small reservoir (battery), a small turbine or water motor (the LED or most any other electrical load), and a resistor (a constriction somewhere in pipes).

It won't matter where you put the restriction; it will still reduce the flow in the entire loop and therefore, through the turbine, reducing its mechanical output. Even if the restriction is on the return side. Why? Because the same amount of water has to flow past any point in the system, as flows past any other point. If that were not true - the water flowing toward any point != the water flowing away from that point, then there must be either a leak or a water source (loss or gain of water) at that point. Since we believe there is no leak (short circuit to ground) or source of water (battery), then water flowing in must == water flowing out at any point. So wherever you put the restriction (resistor), it limits the flow (current) through the entire loop, and the turbine will do less work.

Update:

> If say, 3V are lost/used in the circuit one way, then 2V isn't enough
> to power, right?

The difference in voltage at various points in the circuit is like the change in pressure at various points in the hydraulic loop. Energy (which is neither pressure nor voltage) is transferred by the flow of water or electrons from the pump (battery) to the turbine (LED) and the restriction (resistor). But in a closed system, no water (electrons) is/are lost.

body:
Some images may help, other answers so far are quite good. You need to realise the concept that electrons are flowing in a circuit, with series it doesn't matter which order, so in the following schematic, the first 2 are the same and both work in exactly the same way, the 3rd functions the same but obviously uses 2 resistors instead of 1, It is there to help you understand the concept. The resistance of R3+R4 = 1K so the same amount of current flows through D3 the 3rd LED as D1 and D2.

Do you know Ohms law and about voltage drop ?

Also how to calculate resistance in series and parallel ?

There is some fairly simple maths that shows the 3 different legs are all doing the same thing, however it may over complicate things at this stage if it is above your knowledge as you state you are in middle school.

[![][1]][1]

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


body:
There are three Arduinos on a model. Each of them has a DS18B20 Dallas temperature sensor and an nRF24L01 antenna wireless communication. There is also an independent device consisting of an Arduino and an nRF24L01 antenna. Device acts as a receiver. Arduino and antenna play the role of transmitter. The code is:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include <Wire.h>

    int temp1;
    int WindSpeed;
    int temp2;
    int temp3;
    RF24 radio(7, 8);
    const uint64_t pipes[3] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL};
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.setRetries(15, 15);
      radio.setDataRate(RF24_250KBPS);
      radio.openReadingPipe(0, pipes[1]);
      radio.openReadingPipe(1, pipes[2]);
      radio.openReadingPipe(2, pipes[3]);
      radio.startListening();
    }

    void loop() {
      if (radio.available()) {
        radio.read(&temp1, sizeof(temp1));
         Serial.println("Temp1:");
         Serial.println(temp1);
         delay(50);
         radio.read(&WindSpeed, sizeof(WindSpeed));
         Serial.println(" WindSpeed Bf : ");
         Serial.println(WindSpeed);
         delay(50);
         radio.read(&temp2, sizeof(temp2));
         Serial.println("temp2:");
         Serial.println(temp2);
         delay(50);
         radio.read(&temp3, sizeof(temp3));
         Serial.println("temp3:");
         Serial.println(temp3);
         delay(50);
      } else {
        Serial.println("No radio Data avaliable");
      }
      delay(3000);
    }

The problem is that the code sends some values but the correspondence isn't right in `AnalogRead`. How can I watch each pipe with the antenna of corresponding Arduino in order to have the right results, and each Arduino sends to the receiver through its own antenna the value of its sensor?

Thanks all for your time!

title: Multiple transmitters and problem with ref

Answers: 2

body:
You want to send data from 3 (or 4?) different Arduino transmitters to one Arduino receiver and you want to be able to distinguish the packets sent by each transmitter as they are received. The most straightforward way is to create a struct for your data and attach a unique header and trailer that can be used to identify the sender.

    typedef struct {
      uint8_t header = 0x01;
      int temp1;
      uint8_t trailer = 0x10;
    } PACKET;

Something like this should be present in each transmitter but with unique header and trailer for each one. Then the receiver should have the header and trailer bytes for all the transmitters and, whenever it receives data, it checks the first received byte against the list of header bytes to know who sent the data before it continues. Finally, it checks the last byte to know if it's the correct trailer byte for the assumed sender and also as an additional (but perhaps unnecessary) layer of error detection to know if the received packet is a complete valid one.

body:
You appear to be using the multiple pipes of the nrf24L01 to keep your data feeds distinct, and to be asking how you can differentiate the pipes on receive.

It's not clear *which* exact `RF24` library you are using, but if you look at the headers of a [typical][1] one you will find something like:

      /**
       * Test whether there are bytes available to be read
       *
       * Use this version to discover on which pipe the message
       * arrived.
       *
       * @param[out] pipe_num Which pipe has the payload available
       * @return True if there is a payload available, false if none is
       */
      bool available(uint8_t* pipe_num);

Additionally, you do not want to use any delays in receiving code, as that could cause you to miss transmissions - if you use delays for pacing, they should be on the transmit side.

It's not clear if you have 3 or 4 pipes (**and in your setup you have forgotten that C/C++ array indexing starts at 0 not 1**) but to read 3 of potentially 4, you could do something like:

    #define INTERVAL_MS 10000
    unsigned long lastMsg = 0;
    int values[4];
    char *pipeNames[] = {"Temp1:", " WindSpeed Bf : ", "temp2:", "temp3"};
    void loop() {
       uint8_t pipe;
       if (radio.available(&pipe) {
         if (pipe < 3) {
            radio.read(&values[pipe], sizeof(int));
            Serial.println(pipeNames[pipe]);
            Serial.println(values[pipe]);
            lastMsg = millis();
         }
         else radio.flush_rx(); //unclear if this is needed to allow new data on a pipe that is of interest
       }
       /* warning - may mis-operate after ~50 days */
       if ((millis() - lastMsg) > INTERVAL_MS) {
          Serial.println("no data received in past 10 seconds");
          lastMsg = millis();
       }
    }

  [1]: https://github.com/maniacbug/RF24/blob/master/RF24.h


body:
Is it safe to use a unique 12V 5A DC power source to feed both Arduino and its connected Motor shield, provided that

- the motor (connected to the shield) will eat 3A maximum
- the Arduino `Vin` will get the power

Arduino and the shield exchange information, and use both the same power supply, is there some risk of "interference" of some kind?

*edit*

This is the [motor controller shield](http://www.robotshop.com/en/10a-dc-motor-driver-arduino-shield.html) I intend to use. In the manual, the connections show that

- the Arduino and the shield have different power supplies
- the Arduino power pins are not used by the shield

title: Is it safe to use the same power source for Arduino and its Motor shield?

Answers: 2

body:
I'm assuming your shield has its own power input and you feed the circuit from there. If you are sure that your motor shield can hold that much current there shouldn't be any problem. You should see your motor shield's specs for that.

And actually if your shield has the standard arduino layout, it probably has an header goes into `Vin` pin. So even if you try to supply arduino from USB or power jack along with your power supply, the auto selector circuit of arduino board will use the power from 12 volt power source.

body:
In my case, when I was running my DC motors at full load, I noticed a large voltage drop in the circuit. This could affect the signals or transmission of data on the Arduino.

It is definitely recommended to power the arduino and motor shield with separate power source. Make sure the the share a common GND.


body:
I am encountering a very strange error using `freeRTOS` on an Arduino Mega2560:

In the setup block I can create an instance of my class:

    MyClass* myClass = new MyClass(/*char*/ a, /*char*/ b, new Vector(42));
    // new Vector(42) creates a new vector and pushes 42 in as first item

Using a `print()` method in this class, I get a legitimate output on the console, showing me all the chars and values in the vector.

Using the exact same line inside a task, causes the object not to be created properly. It seems like the fields are empty or there is something entirely wrong (like strange memory errors) with the instance. Printing it again results in an empty line (program doesn't crash) while printing a globally created instance gives the correct result.

Is there any trap in `freeRTOS` concerning the creation of new instances of an object inside a task? Below is the code for the task creation, increasing the task stack size doesn't help. For debug reasons this the only task running at the moment.

    xTaskCreate(displayTask,
     "DisplayTask",
     configMINIMAL_STACK_SIZE + 300,
     NULL,
     tskIDLE_PRIORITY + 1,
     NULL);

title: FreeRTOS: Object not created properly from within task

Answers: 1

body:
'Strange memory errors' you seem to be describing values that have gone out of scope.

This is all based on your code, so I may have misunderstood.

The third parameter is causing a memory leak, unless you happen to be deleting it within MyClass (which is normally, not always, bad practice).

It sounds to me that you are trying to access values that have gone out of scope.

Its also possible that this OS requires you to do something to allow the memory to be shared between the tasks.


body:
I recently bought a W5100 Ethernet shield and I'm trying to run this simple example, which is a little improvement of the basic WebServer sketch provided by Arduino.cc

    #include <SPI.h>
    #include <Ethernet.h>

    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress DnsServer (192, 168, 1, 6);
    IPAddress GateWay (192, 168, 1, 1);
    IPAddress SubNetMask(255, 255, 255, 0);
    IPAddress ip(192, 168, 1, 20); // IP address, may need to change depending on network
    EthernetServer server(80); // create a server at port 80

    String HTTP_req; // stores the HTTP request
    boolean LED_status = 0; // state of LED, off by default

    void setup() {
      Ethernet.begin(mac, ip, DnsServer, GateWay, SubNetMask); // initialize Ethernet device
      server.begin(); // start to listen for clients
      Serial.begin(9600); // for diagnostics
      pinMode(2, OUTPUT); // LED on pin 2
    }

    void loop() {
      EthernetClient client = server.available(); // try to get client
      if (client) { // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) { // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            HTTP_req += c; // save the HTTP request 1 char at a time
     // last line of client request is blank and ends with \n
     // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");
              client.println();
              // send web page
              client.println("<!DOCTYPE html>");
              client.println("");
              client.println("");
              client.println("<title>Arduino LED Control</title>");
              client.println("");
              client.println("");
              client.println("
LED
");
              client.println("
Click to switch LED on and off.
");
              client.println("<form method=\"get\">");
              ProcessCheckbox(client);
              client.println("</form>");
              client.println("");
              client.println("");
              Serial.print(HTTP_req);
              HTTP_req = ""; // finished with request, empty string
              break;
            }
     // every line of text received from the client ends with \r\n
            if (c == '\n') {
     // last character on line of received text
     // starting new line with next character read
              currentLineIsBlank = true;
            } else if (c != '\r') {
              // a text character was received from client
              currentLineIsBlank = false;
            }
          } // end if (client.available())
        } // end while (client.connected())
        delay(1); // give the web browser time to receive the data
        client.stop(); // close the connection
      } // end if (client)
    }

    // switch LED and send back HTML for LED checkbox
    void ProcessCheckbox(EthernetClient cl) {
      if (HTTP_req.indexOf("LED2=2") > -1) {
        // see if checkbox was clicked
     // the checkbox was clicked, toggle the LED
        if (LED_status) {
          LED_status = 0;
        } else {
          LED_status = 1;
        }
      }

      if (LED_status) { // switch LED on
        digitalWrite(2, HIGH);
        // checkbox is checked
        cl.println("<input type=\"checkbox\" name=\"LED2\" value=\"2\" \
            onclick=\"submit();\" checked>LED2");
      } else { // switch LED off
        digitalWrite(2, LOW);
        // checkbox is unchecked
        cl.println("<input type=\"checkbox\" name=\"LED2\" value=\"2\" \
            onclick=\"submit();\">LED2");
      }
    }

So I proceed with connecting my shield via a LAN cable to my router (Gateway `192.168.1.1`), but if I ping `192.168.1.20` (my Arduino) it says "Host Unreachable", my router use DHCP which always worked and still works fine, I'm sure that there aren't any MAC address or IP conflict. I googled around a lot but nothing seems to work.

My DNS server is `192.168.1.6` because I'm running PI-Hole (it's an ad blocker) on a Raspberry, and I don't think this is the problem because all devices connected to it are working fine.

Please any help? Do I have to assume that my shield is faulty?

I tried also using DHCP connection in order to get an IP from the router by doing a:

    Ethernet.begin(mac);

But no good as well.

title: Can't connect to my Arduino via W5100 Ethernet shield

Answers: 1

body:
*"...Please any help? Do I have to assume that my shield is faulty?..."*

Before trashing the shield, I'd run through a sligtly more comprehensive troubleshooting approach, from the lowest level of the network stack (the physical layer) up to the ICMP/IP layer. Let me expand over this process:

 1. **Physical layer**: I bet your router has some LEDs whose purpose is to show *IF* some ethernet device is connected to related physical router port... or not. So, as a very first step, supposing you connect your ethernet shield to PORT-1 of your router, you should check that once you connect the cable and turn on the Arduino.... the "port 1" LED on the router should turn on.
If it turns on... let's proceed to next step. Otherwise... let's launch a different question (or expand accordingly your OP);

 2. **Ethernet layer**: once the LED is on, we can be sure that the physical layer is OK. So let's go up at Ethernet layer. In order to communicate on an Ethernet network, every device need to have a MAC address. Also, even if not strictly necessarily, we can bet that every ethernet device (including your shield) implement the [ARP resolution protocol][1]. This is needed in order, for other ethernet devices, to obtain the MAC address of your shield, in order to include such a MAC address in all the ethernet datagrams to be sent over the network (to communicate with your shield).
So, if you configured your shield with MAC `DE:AD:BE:EF:FE:ED` and IP `192.168.1.6` I would:

    1. connect my Linux box to your router (*BTW: sorry! I can't help with other operating systems, as I switched to a linux-only notebook lots of years ago!*);
    2. configure my Linux ethernet interface (`eth0`) with an IP like `192.168.1.99`;
    3. run an `arping -I eth0 192.168.1.6` (where `arping` is [this][2] tool)

If everything is working correctly, you should receive something like:

    root@iMac-Chiara:~# arping -I eth0 10.20.20.2
    ARPING 10.20.20.2 from 10.20.20.1 eth0
    Unicast reply from 10.20.20.2 [A4:BA:DB:98:FC:A4]  0.736ms
    Unicast reply from 10.20.20.2 [A4:BA:DB:98:FC:A4]  0.729ms
    Unicast reply from 10.20.20.2 [A4:BA:DB:98:FC:A4]  0.720ms
    [...]

where you see that my notebook (10.20.20.1) is getting ARP-replyies from 10.20.20.2, who has the `A4:BA:DB:98:FC:A4` MAC address.

If you don't see replyies... we have an Ethernet problem (but not a physical one) and... chances are high that you have a faulty shield (BTW: the message "Host unreachable" you mentioned in your OP, let me think that this is your problem);

Viceversa, if you obtain replyies, than the Ethernet level is OK and problems are located on upper layers. Let's focus on this last particular case

  3. **IP layer**: once the physical layer and the ethernet layer are OK, you should be able to properly PING your target (I'm excluding the case where you have some firewall that, somewhere along the path from the two hosts, could "cut" some traffic. I'm also supposing that IP addresses and netmask are properly configured [from an IP point of view]). I'm not getting deeper with such a case, as you should be already familiar with PING (BTW: from your POST, it's not clear from *where* you were PINGing your Arduino. Directly from the "router"? or from you PC?)

Having said all the above, let me conclude by saying that several further checks could be putted in place but... it's much better to previously run above checks :-)

Hope this help!

  [1]: https://en.wikipedia.org/wiki/Address_Resolution_Protocol
  [2]: https://en.wikipedia.org/wiki/Arping


body:
I have been searching for cheap slim 3" 16:9 capacitive touch screens for a while now. But I couldn't find any that had an I2C or SPI interface. The cheap displays always have these ribbon cables with a ton or pins and it's really hard to find a way to control them from an Arduino (or ESP-32 or ESP-8266).

I recently found [this one][1], but how do you access such a touch screen that doesn't have an I2C or SPI interface?
Do I need some sort of driver board? What exactly would I be look for?
[![enter image description here][2]][2]

  [1]: https://www.alibaba.com/product-detail/3-inch-tft-screen-with-capacitive_60495467722.html
  [2]: https://i.stack.imgur.com/sLuBK.png

title: Controlling a capacitive touch screen that doesn't have I2C/SPI

Answers: 2

body:
There are two major parts to a capacitive touchscreen:

1. The touch panel
2. The controller chip

You have to have both in order to use the panel.

Basically the panel is like a matrix of capacitive sensors, and the controller chip has to rapidly cycle through each row of them (or column if you hold it the other way) sensing all the inputs on that row. It's quite a complex task, and so a special chip is really required for the job.

It's that chip, not the touch screen panel, that presents the SPI or I2C interface.

body:
> Do I need some sort of driver board?

There are quite a few solutions around to interface with parallel devices like that. Some can be purchased off-the-shelf. I described a home-made solution on my page [Connecting a graphical LCD via a I2C/SPI using a 16-bit port expander](http://www.gammon.com.au/lcd).

This isn't a touch screen, but from what I can make out of your (rather hard to read) image, it looks similar in concept.

[![Graphical LCD][1]][1]

I used a MCP23017 16-bit port expander (that is an I2C part, but you can get the MCP23S17 chips which has an SPI interface).

As you can see from the photo, there are only four wires from the Arduino to the LCD board: +5V, Gnd, SDA, SCL.

When I wrote that article it looks like the MCP23017 was $AUD 2.30. A quick Google search indicates it is still selling for around $US 2.50. On eBay they seem to be selling for around one dollar (eg. $5 for 5 chips).

Depending on the complexity of the driver (on the touch-screen board) writing suitable code may be moderately easy to slightly harder. It depends on how much you are used to coding for these port expanders, and how fiddly the interface requirements are.

Since Adafruit offer a driver shield, it can presumably be done.

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


body:
I am interface Arduino with nRf905 in receive mode use 433 MHZ.

I Have follow this link http://www.electrodragon.com/w/NRF905_Transceiver_433MHz-Wireless_Module.

And for transmitter, I am use RF-Transmitter-Door-Window-Sensor which works on 433MHZ.

Now, Arduino receive garbage data I have attached snapshot of received data.

I am quarry about to set address and 433MHZ.

My config_buffer is:
<!-- language-all: lang-cpp -->

    unsigned char config_info_buf[10]={
       0x4C,
          0x01,                   //output power 10db, resend disable, Current
          0x44,                   //4-byte address
          0x20,0x20,              //receive or send data length 32 bytes
       0x21,0x11,0x11,0x00,
          0x18,
    };

Question is there are 0x4C set exactly 433MHZ.

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

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

Any help will be appreciated.

Regards,
rajneesh

title: Nordic nRf905 (433MHZ) with arduino receive garbage data

Answers: 0


body:
I know that Arduino nano/Uno has one Serial port to read serial data. But if I use software serial can i read more than one serial data.

I have 150 Arduino's working on a project(Can be reduced to 50 if required) these arduino will generate serial data (150 serial data as of now). I wanna connect all these 150 serial data to a computer through a single COM port. How can i make it possible.

title: How can I read Data from 150 Arduino Serially to a Single Arduino to display it via serial port.

Answers: 2

body:
If each source generates messages at a low enough rate, you can put them all in series.

Each Uno has a serial input, and a serial output, and they are all chained. Each Uno labels its message with who it's from, and passes on received messages unchanged.

Obviously this means that if you used (say) 9600 baud, or approaching 1000 bytes per second, each device would only be able to source 6 bytes per second of message.

If that's not fast enough for your application, then you would need a higher baud rate at the COM port.

body:
You can attempt to connect your devices in a loop, if you are insisting on using a single serial port for each. How well all that works will depend on a lot of things.

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

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

<!-- End schematic -->

I have no idea what your computer is, but this is a common mention to string multiple units together where they only have a single serial port each. The software in each unit will need to pass along messages that belong to other units and you will have to device a method for achieving that process. But it can work. Message delays will exist, of course. And with from 50 to 150 units, you may find some serious frustration. But if the needs are modest, you may be able to get by with this mechanism.


body:
I'm new to Arduino, and I'm trying to connect my Leonardo via WiFi using a ESP8266 module. What I want to know is if I can power it directly from the onboard 3.3V pin like in the image:

![Leonardo](https://microcontrollerelectronics.com/wp-content/uploads/2014/12/esp8266_bb.png)

Or do I need an external voltage regulator? I don't want to damage it.
Thanks!

title: Powering ESP8266 from Leonardo's 3.3v pin

Answers: 2

body: The Leonardo is specified to provide only 50mA on the 3V3 pin. A ESP8266 can use up to almost 300mA when transmitting. Consider using a LDO regulator connected to the 5V pin instead.

body: Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module.


body:
Will all the classes in this library work with the MKR1000 with wifi hardware?
The guide mentions "wifi shield".

So, does the library work exactly the same with the Arduino MKR100 (with the onboard wifi HW) as it does with the wifi shield?

[WiFi101 library reference][1]

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

title: Is Arduino WiFi101 library fully compatible with Arduino MKR1000 with WiFi HW?

Answers: 0


body:
I'm using an Arduino Uno. "Regular" serial is plugged into my computer, and I can receive just fine.

I'm using AltSoftSerial (tried SoftwareSerial, same results) with RX and TX on pins 8 and 9 to interface with a BR-355S4 GPS module. According to the [data sheet](http://usglobalsat.com/store/gpsfacts/br355s4_gps_facts.html) on that module, the RX and TX are at 5v, which I believe is what the Arduino expects.

I combined the Serial and SoftwareSerial examples to test the connectivity from the Arduino to my PC and from the GPS to the arduino.

    #include <AltSoftSerial.h>
    AltSoftSerial altSerial;

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(19200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      printAsciiTable();

      altSerial.begin(4800);
    }

    void printAsciiTable(){
      Serial.println("ASCII Table ~ Character Map");
      int thisByte;
      for(thisByte = 33; thisByte < 127; thisByte++){
        Serial.write(thisByte);
        Serial.print(", dec: ");
        Serial.print(thisByte);
        Serial.print(", hex: ");
        Serial.print(thisByte, HEX);
        Serial.print(", oct: ");
        Serial.print(thisByte, OCT);
        Serial.print(", bin: ");
        Serial.println(thisByte, BIN);
      }
      Serial.println("~~Done with ASCII Table~~");
    }

    void loop() {
      char c;
      if(altSerial.available()){
        c = altSerial.read();
        Serial.print(c);
      }
    }
The data coming into the Serial Monitor tool looks fine until it starts pulling from the GPS serial stream (ellipses added by me):

> ...
> |, dec: 124, hex: 7C, oct: 174, bin: 1111100
> }, dec: 125, hex: 7D, oct: 175, bin: 1111101
> ~, dec: 126, hex: 7E, oct: 176, bin: 1111110
> ~~Done with ASCII Table~~
> 4™5f3y=›ùÙ)É9Ó¦Ì™¦ ...

I would like to receive the [correct NMEA strings](http://www.gpsinformation.org/dale/nmea.htm#stream) from the GPS module on altSerial and push them out to Serial. The garbled nature of the serial data looks like a baud rate issue, but I've tried a handful of combinations for Serial and altSerial speed with no success. Any ideas?

title: Garbled serial from GPS device

Answers: 3

body:
I looked up the datasheet and product specs for the GPS device. It says that the output is RS-232.
Note that RS-232 is NOT compatible with the Arduino levels. Arduino "talks and listens" at 5V or 3.3V depending on which board you're using.
So what you need is a RS-232-to-TTL converter. Now, TTL speaks Arduino. So Arduino will be able to understand that. So try using a MAX232 IC or a shield, whichever you're comfortable with.

body:
You can get 5V TTL USB serial adaptors. The classic being an FTDI one. Also you can get the MAX chip level converters as a tiny module, if you already have a normal RS232 adaptor. I would recommend connecting the GPS to your PC as a reality check. The garbled that you are seeing is typical Baud rate issues.

Also there can be polarity issues with the signal. (Not sure if you can switch the pin polarity of the Arduino in software.) So if you are connecting to a standard RS232 adaptor I think the MAX chips are available in inverting and none inverting versions.

Some PC RS232 adaptors are 5V tolerant. Google this for confirmation. You should just connect the GPS tx to the PC RX if you try this. (And 0V obviously.)

body:
In the comments I see that is not clear how you connect the module in your arduino.
The native mode is PS2 (old mouse and keyboard) you can use that directly with your arduino (PS2 protocol is 5v too), for this, you need implement a clock/data protocol.
If you use the rs-232 converter, notice that RS-232 as a amplitude from -12v ~ 12v this burn your arduino, so you need use a rs232-ttl converter.

Serial software are not a good choise, if you use that, save your data in a buffer and write only one time, in the end.


body:
I'd like to know how much current can supply the 5V pin and the 3.3V pin on an Arduino Leonardo board. I've been lead not to trust the specs on Arduino's website. And, as an added question, can the 5V pin supply enough power for an LM741 opamp?

Thanks!

title: What's Leonardo 5V pin current limit?

Answers: 1

body:
The 5V pin is either supplied by the USB port, which has a limit of 500mA (imposed by a resettable fuse) if directly connected to the computer or a powered hub (or 100mA in an unpowered hub), or the on-board regulator (NCP1117ST50T3G), which is 1A, when powered externally.

The 3.3V pin is regulated using an LP2985-33DBVR which has a current limit of 150mA (the specifications on the website say 50mA. This is wrong. I think it is a left-over from the old Uno boards with FTDI chips where the 3.3V was fed directly by the internal 3.3V regulator of the FTDI chip and thus limited to 50mA).

Yes, the 5V pin has more than enough current to run an LM741 op-amp.


body:
This question is posted here as a reference question (its actually a follows  on from comments in my earlier question "How to expand program memory on an arduino?") -( Edgar Bonet suggested this question and who answered 1 below  in the comments there).

I think its a useful question to others new to arduino. I have posted an answer too. But you can of course add your answer too. I dont know everything about arduino- still learning. It does not refer to the version of the Uno that uses a surface mount atmega328-but the version with removable atmega328.

1) If I take out the atmega 328 chip from its socket on the Uno and replace it with using atmega8-16PU instead and I burn a bootloader-does that mean I can use the arduino Uno with the atmega8 like the atmaga328 (but with a subset of the features of the 328)?  The atmega8 is of course an older chip than the 328 (and is significantly cheaper) but it still has same pinouts.

2). I am using the 16mhz crystal in my project. So using an Arduino Uno with atmeg8 chip does this mean that the bootloader will set the fuses on the arduino's atmega8 to use the crystal on the arduino Uno pcb? Or does the bootloader set the fuses on the arduino's atmega8 to use its internal oscillator?

3) So hw much memory is left after writing bootlader to atmega8 ?

4) Can I burn the bootloader more than once?

title: Using an Atmega8 Chip with an Arduino Uno instead of an atmega328

Answers: 1

body:
1) yes the arduino uno can be used with a blanked at mega8 chip with the NG bootloader burned onto it.
You would set the board as NG in the IDE to use the arduino IDE (to upload sketches and so on) with it.

2) A crystal and capacitors is still required -the same values as used for the removed atmega328.

3) The smallest bootloader will leave 7.5kb of program memory left to use on the atmega8.

4) Yes


body:
Maybe it's a simple question but I'm unable to get what I need.

My task is this:
Get the acceleration and speed of each axis of the accelerometer.

I thought of something like:

    const int VCCPin = A0;
    const int xPin   = A1;
    const int yPin   = A2;
    const int zPin   = A3;
    const int GNDPin = A4;

    // variables
    int old_x = 0;
    int old_y = 0;
    int old_z = 0;

    int new_x = 0;
    int new_y = 0;
    int new_z = 0;

    void setup() {
      // pin A0 (pin14) is VCC and pin A4 (pin18) in GND to activate the GY-61-module
      pinMode(A0, OUTPUT);
      pinMode(A4, OUTPUT);
      digitalWrite(14, HIGH);
      digitalWrite(18, LOW);

      // activating debugging for arduino UNO
      Serial.begin(9600);
    }

    void loop() {
      new_x = analogRead(xPin);
      new_y = analogRead(yPin);
      new_z = analogRead(zPin);

      Serial.print("Difference in X=");
      Serial.println(abs(old_x - new_x));

      Serial.print("Difference in Y=");
      Serial.println(abs(old_y - new_y));

      Serial.print("Difference in Z=");
      Serial.println(abs(old_z - new_z));

      old_x = new_x;
      old_y = new_y;
      old_z = new_z;
    }

Unfortunately, the analogRead will give me a value between 0 and 1023 and I don't know how to convert this to speed and acceleration.

Any ideas on how to get this convertion?

title: Transforming from analog output to speed and acceleration with gy-61

Answers: 0


body:
I'm trying to install a bootloader on my ATmega328P-PU. I'm trying to install it from Arduino Uno (not original). I can install all sketches. After I click "Burn bootloader" I get the following error:

<!-- language: none -->

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

    avrdude: Yikes!  Invalid device signature.
    avrdude: Expected signature for ATmega328P is 1E 95 0F
     ***failed;
    avrdude: verification error, first mismatch at byte 0x0000
             0x00 != 0x3f
    avrdude: verification error; content mismatch
    Error while burning bootloader.

How to fix it?

title: Error while installing bootloader ATmega328

Answers: 1

body:
EDIT: First ensure that you have made the hardware correctly (see comment below this post).

If you need different settings for custom avr hardware the following will help:-

The best way to create a custom board definition is to create your own `boards.txt` entry in the Arduino custom hardware folder.

But less effort to learn is to try to temporarily change or add to the Arduino IDE `avr` board definitions.

The board definition (properties) are passed to the tool that burns the bootloader. All board specific properties are provided by the `boards.txt`

Edit the `[ArduinoIDE\Hardware\hardware\arduino\avr\boards.txt` with a text editor and find the Uno section.

It looks like this. Notice the `mcu`, `vid`, `pid` and `uno.bootloader.file=` settings in particular. The bootloader points to a file in `[ArduinoIDE\Hardware\hardware\arduino\avr`

    uno.name=Arduino/Genuino Uno

    uno.vid.0=0x2341
    uno.pid.0=0x0043
    uno.vid.1=0x2341
    uno.pid.1=0x0001
    uno.vid.2=0x2A03
    uno.pid.2=0x0043
    uno.vid.3=0x2341
    uno.pid.3=0x0243

    uno.upload.tool=avrdude
    uno.upload.protocol=arduino
    uno.upload.maximum_size=32256
    uno.upload.maximum_data_size=2048
    uno.upload.speed=115200

    uno.bootloader.tool=avrdude
    uno.bootloader.low_fuses=0xFF
    uno.bootloader.high_fuses=0xDE
    uno.bootloader.extended_fuses=0x05
    uno.bootloader.unlock_bits=0x3F
    uno.bootloader.lock_bits=0x0F
    uno.bootloader.file=optiboot/optiboot_atmega328.hex

    uno.build.mcu=atmega328p
    uno.build.f_cpu=16000000L
    uno.build.board=AVR_UNO
    uno.build.core=arduino
    uno.build.variant=standard

You can add a new entry like this. The example uses a board prefix of `uno2.` but it can be any simple unique name.

Save the changes to `boards.txt` then restart the Ide:-

    uno2.name=Arduino ATmega328P-PU

    uno2.vid.0=0x2341
    uno2.pid.0=0x0043
    uno2.vid.1=0x2341
    uno2.pid.1=0x0001
    uno2.vid.2=0x2A03
    uno2.pid.2=0x0043
    uno2.vid.3=0x2341
    uno2.pid.3=0x0243

    uno2.upload.tool=avrdude
    uno2.upload.protocol=arduino
    uno2.upload.maximum_size=32256
    uno2.upload.maximum_data_size=2048
    uno2.upload.speed=115200

    uno2.bootloader.tool=avrdude
    uno2.bootloader.low_fuses=0xFF
    uno2.bootloader.high_fuses=0xDE
    uno2.bootloader.extended_fuses=0x05
    uno2.bootloader.unlock_bits=0x3F
    uno2.bootloader.lock_bits=0x0F
    uno2.bootloader.file=optiboot/optiboot_atmega328.hex

    uno2.build.mcu=atmega328p
    uno2.build.f_cpu=16000000L
    uno2.build.board=AVR_UNO
    uno2.build.core=arduino
    uno2.build.variant=standard

note: make a copy of the .txt or grab a new one from the zip on arduino.cc if you mess it up.


body:
Is there a way to route an analog signal from a simple temperature sensor through an ADC, MCP3008, into a digital pin. I have used all the analog pins on my Arduino  Mega 2560 and am trying to utilize all the digital I/Os.

Any insights on the matter would be greatly appreciated.

title: Trying to read analog signal with digital pin using outside ADC

Answers: 1

body:
The MCP3008 is an SPI device. You connect it to the SPI pins of your Arduino. Then you can read 8 analog channels through it.

It requires 4 pins: MISO, MOSI, SCK and a chip select pin.


body:
I have a few Arduino boards connected to my computer running firmata and I want the computer to be able to differentiate between them even when I unplug them and plug them back into a different USB port in a different sequence. My solution was to save and read a Unique I.D. into each Arduino's EEPROM, but I am not sure how to accomplish this using firmata?

I want to save a few bits of data to the Arduino UNO with EEPROM, but the Arduino has to be running code compatible with firmata. Is this possible?

title: Can you save data to EEPROM using firmata?

Answers: 1

body:
You have to edit the Firmata source code and add a few lines of code:

 1. add the EEPROM library
 2. include the library into the Firmata code
 3. in the setup() function use the EEPROM library to read the id from the EEPROM

How do you plan to write that data into your Arduino EEPROM?
If you want to do that via serial connection than you also need to add that code.
I have done something similar in an example for my [VoltageReference][1] library, specifically in [EEPROMCalibration.ino][2]

**UPDATE**

After a little investigation I understand there is the possibility to exchange generic messages and handle generic commands via Firmata: commands 0x00-0x0F are reserved for customization. On the Arduino side you can use:

    void storeToEEPROM(int id) {
      ...
    }

    void readFromEEPROM() {
      char buf[12];
      Firmata.sendString(itoa(the_id, buf, 10));
    }

    void setup() {
      ...
      Firmata.attach(0x00, storeToEEPROM);
      Firmata.attach(0x01, readFromEEPROM);
      ...
    }

That will allow you to write and read the id using those two custom commands.

  [1]: https://github.com/rlogiacco/VoltageReference
  [2]: https://github.com/rlogiacco/VoltageReference/blob/master/examples/EEPROMCalibration/EEPROMCalibration.ino


body:
I have a quick question to ask.
I have an Arduino Uno reading 4 temperature sensors (LM35) in 4 different rooms. What happens is that the two nearest rooms give stable values, while the two further ones give very unstable measurements (the temperature keeps floating +-30C around the real values.)

I have connected all the sensors with Ethernet cables with the longest one being about 8-10m.

Is this problem due to noise picked up along the line? There are no strong electromagnetic sources along the way.
I have also measured the voltage values on Arduino end with a multimeter: the values are all stable (and correct) and do not reflect the behaviour detected by Arduino.

Also, I have tried to substitute the LM35 in the farthest room with a photoresistor (the one in the starter kit) and this time the values read by Arduino are perfectly stable. I know that the LM35 works because I have tested it on a breadboard.

Can someone give my some help? Any idea is greatly appreciated.

Edit: I am adding a sketch, although it is a very basic setup:
The only difference with the real layout is that there is also a Ethernet shield.

![circuit schematics](https://i.stack.imgur.com/ITwcg.jpg)

title: Trouble reading LM35 with long (?) Ethernet connection

Answers: 2

body:
**Short answer**

Add `delay` between each reading, 100ms should be enough.

**Long answer**

The LM35 is an analog device and you are using the internal ATmega328 ADC to read the voltage on the signal pin.
The way the Arduino ADC works is a sample-and-hold process:

1. open a circuit to an internal capacitor
2. charge the capacitor
3. disconnect the circuit
4. compare capacitor to the reference voltage

Because there is only one of such circuits shared among all the 6 analog pins you need to let the capacitor charge up, which is much slower on long lines having a non negligible resistance and also a non negligible capacitance.

Also other wires and power lines near to your ethernet cable are going to influence your readings, but in that case the ethernet cable shielding is going to help you, [if properly used][1].

  [1]: https://en.wikipedia.org/wiki/Shielded_cable

body:
The LM35 has trouble driving any kind of capacitive load, so the long runs of cable are generally not a great idea if you are relying on a voltage signal. The datasheet for it (The one I have is from the Texas Instruments website), has a few strategies to reduce this problem somewhat.

The approach that I have used successfully, is to use a current signal, rather than a voltage signal. This has the advantage that you only need a two wire twisted pair cable (I made my own twisted pairs - it is easy for relatively short runs).

The idea is that you connect the LM35 output to the ground pin with a known resistor value (the datasheet example has a 200 Ohm resistor). Since the voltage is 10mv per degree, the current wil be 10/R mA per degree. There will be an additional small current from the LM35 device itself, but this is small, and almost constant. Then connect the supply and ground to one end of your twisted pair.

At the other end, it is necassary to convert the current signal back to a voltage so that your Arduino can read it. Simply put a resistor (again, 200 Ohms is that used in the datasheet example) between the low side of the twisted pair to OV, the high side connected to 5V, and measure the voltage across this resistor.

Figure 17 in the TI datasheet is the one to follow.

Other things that help to get more stable, acurate readings;

Choose a time to take readings when you are not running anything else that might interfere (wireless comms, ultrasonic sensors, motors, solenoids, etc).

Take several readings. Ignore the first two.

Take the median value of the remaining readings (eg take 5 readings, ignore the first two, and sort the others in order. Then take the middle value.).

Hope this helps.


body:
Is there a simple way to rig two balls in a way that lets you know if they are touching?

For example, here's a bad idea. Put a free-to-move magnet inside of each ball. When the balls get close, the magnets snap together. Use a magnetic sensor within each ball to tell the direction of the magnet. Use an accelerometer to tell the direction of gravity. When the gravity direction differs from the magnet direction, the balls are touching.

I don't need to know the direction of the contact (that would be ideal, but I don't *need* it). It should work over the whole surface. I would like to have more than two balls and be able to tell *which* two are touching. I can make the balls however I want.

(Even very basic advice would be quite helpful. I'm not familiar at all with hardware projects or what kinds of sensors are available or how to combine the available pieces into some desired thing. That includes advice like "this is probably too hard".)

title: Detecting mutual contact between balls

Answers: 1

body:
Option 1

Seems you say you can make the balls out of whatever you want, I would suggest the spheres be made of a metal and then you can either suspend them by wire spot welded or soldered onto the balls. Then what you do is you connect all the balls to inputs of an Arduino ( this is if you are doing this with one). Then connect all inputs to pull-up resistors.

Then to read if a ball is touching a neighbour you start with ball `n` and set it as an `output` and use `digitalWrite(n,LOW);`  and then poll all the other balls as inputs to see which one reads `LOW/0V` and then record that in an array, you the move onto ball `n+1` and scan the rest of the balls. There is also no need to read the previous ball to `n+1` as if it did not register a touch, then it won't register with the next ball.

Then at the end you reset everything and start at the beginning again. Using the data how you wish at the end.

Below code is just to show, not tested.

    for(int n =0; n < total_N; n++){
          pinMode(n, OUTPUT);

      for(int i = 0; i < total_inputs; i++){
              if(!(digitalRead(n)))// ball is touching
       {

             myArray[i] = 1;// store a point in the list, replace with a way you want
        }
        else myArray[i] = 0;
    }
         pinMode(n, INPUT);
    }

Option 2
 *(probably to much to go wrong)*

You could use material that will allow IR rays to pass through and make you balls with that. Then in each ball is have a IR transmitter and a IR receiver, making a transceiver basically and then have each ball echo a specific ID and let the other balls pick it up.

To solve the issue that IR travels a good distance you will need to limit the power/voltage/current to the IR transmitter(LED) so that they only work within a certain range.

Option 3

You could place reed switches or hall effect sensors in each ball, with a magnet. Place a niece of metal behind the sensor so that the magnet is drawn to it. The only issue with this is that either the magnet in each ball will not only affect its neighbour but also itself. So they will need to be spaced and also the right strength of magnet.

Option 4

A combination of option 2 and 3 would be to surround a IR receiver setup with a piece of metal disk(like a washer) and also a reed switch or hall effect sensor, and then have a ball with a magnet and a IR transmitter by a magnet, so that when the two are pulled together the transmitter and receiver match up in the same view and are able to tell them that they are connected, you would thus have each ball with a set, one to receive placed on one side and another on the opposite side to transmit.


body:
I am using CS5211AGP wireless RF transmitter to transmit some data and another side receive this data through nRf905 as receiver. But now problem is how can I decode RF transmitter address (because transmitter and receiver address must be same).

if any one working on this module then please suggest me how can I decode address.

Please show below image where you can see the connection of address and zone.[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/zEROM.jpg
  [2]: https://i.stack.imgur.com/7Lp7f.jpg

Now please say about what address should I set at receiver side for communication.

Thanks in advance.

Regards,
rajneesh

title: CS5211AGP wireless RF transmitter (433MHZ) address decoding problem

Answers: 1

body:
I am looking at mine, wich address is 01212012, acording to a sticker in a side. I can see in mine jumpers as follows (starting from A0): -HLHL-HL-H-H where - means no jumper. Based on my sticker I can see that 0 is equivalent to NO-JUMPER, 1 is H and 2 is L. By watching yours I can tell that your code is 21111002.
The other 4 jumpers is what I don-t understand, but if I change any of them, my alarm no longer detects any change.
Hope this helps...
Regards.


body:
I have this MQ-2 gas sensor for an Arduino Uno:

[![MQ-2 sensor][1]][1]

[![MQ-2 sensor][2]][2]

[![MQ-2 sensor][3]][3]

I found these two articles about how to use it:

 - https://create.arduino.cc/projecthub/Aritro/smoke-detection-using-mq-2-gas-sensor-79c54a
 - http://www.instructables.com/id/Ardunio-Smoke-And-Gas-SensorMQ-2/?ALLSTEPS

But I need to know if the sensor is analog or digital.
Also I would like to know what is the blue switch for.

This questions help me a bit:

It says that he use an analog sensor. But as this sensor is not mine I don't want to brake it or burn it.

  [1]: https://i.stack.imgur.com/WrBcL.jpg
  [2]: https://i.stack.imgur.com/IzJCU.jpg
  [3]: https://i.stack.imgur.com/9gwPi.jpg

title: Is my MQ-2 gas sensor analog or digital?

Answers: 1

body: Your sensor is analog. I have the same one. By the way, there is no chip on board, so it cannot form a digital signal ;)


body:
I have a `Channel` class which on instantiation receives a `_type` via `new Channel("type", ...)`. I can read the type back out via `channelObject->getType()` which returns a string.

This has always worked fine until today. I have no idea what changed but if I `Serial.print(channelObject->getType())` I get a nasty amount of garbage in the terminal:

    ���QQ���� 00@��������'����������������������(�����������b���������������������������������������H���E���������������������������������������������������������������uD��DESC  initializedOoops, no LSM303 detected ... Check your wiring!Ooops, no BMP180 detected ... Check your wiring!Setting IMU ground: Setting front: !! set ground kalman initConnect Powerbooting up...SWATBOT SETUP COMPLETEtype_xelevatoraileronthrottlerudderaux1aux2serial in: DISARMED!E;1
    B��LSM303(>.a+a+8L.�S2E/��BMP085.qL3GD20���T �4&�'�%�%�%&
    naninfovf�!,�!H�!��!��!Њ!�D�s6/&������?)m((a&l1=#k2���_
    X� +�����+����=� ��J�5�.d�6s'���z :����������-/�type_xtype_x elevatoraileron throttlerudderaux1aux2�F�OX4Vjx 7���2�?�xr����:~aileronaux1
    �:~ elevator
     ~ throttle:):~rudder������=�@��>�̀?��=�=�@��>�����=�=�@��>�f�B��=�i�?�k��BMP085QF��D�C
    �#<}D������D]v� ,B����^v�QF����P}D .?P���f�B.s�D2m .?�oIB��P��(=:@���A�A�@9�@ A@�@�?�A0SB0N�>dC9�@ A@�@�?�A ��A��dC��L?��L>s����C�B(��"� (� �"��
    (�

"elevator", "aileron", "throttle", and "rudder" are types for objects that I know exist but why is it coming out like this? I'm also seeing other unrelated parts of my program being spit out too like "Ooops, no LSM303 detected ...". This is all so strange.

If I had to guess, there must be an awry pointer somewhere in my application but I'm having no luck finding it. Worst case I'll rollback my application and retrace my last implementations (a couple days worth of work).

Can anyone give me a clue as to what is going on here?

My broken application is online at: https://github.com/jacksonkr/SwatBotSpine/tree/master

Emphasis on [Channel.h][1]:68 which is where all the garbage is coming from.

Related code:

- [RemoteControl.h][2]:37
- [RemoteControl][2]::getChannel

  [1]: https://github.com/jacksonkr/SwatBotSpine/blob/master/Channel.h
  [2]: https://github.com/jacksonkr/SwatBotSpine/blob/master/RemoteControl.h

title: Why are my objects losing their member's values?

Answers: 1

body:
You might be running out of RAM. I suggest you change all lines like this:

     Serial.println("SWATBOT SETUP COMPLETE");

to use the `F` macro like this:

     Serial.println(F("SWATBOT SETUP COMPLETE"));

There seem to be a *lot* of places you could change.

---

Also I would not put code (implementation) into the .h files. That belongs in .cpp files. The .h files are for declarations.

---

Inside a class function, using `this->` all the time just makes things look cluttered, eg.

    StabilityController::StabilityController(RemoteControl* rc, ROSController* ros, IMUController *imu) {
      this->_rc = rc;
      this->_ros = ros;
      this->_imu = imu;


body:
I have lots of `Serial.print()` and `Serial.println()` statements throughout my (rather large) program for debugging when things fail. I've commented out the `Serial.begin()` statement so I don't slow down execution by running a serial port. However, I'd like to leave the `Serial.print()` calls so I only have to uncomment `Serial.begin()` later on.

If there is no Serial port active on the device, are the `Serial.print()` lines still executed at runtime, or does the compiler ignore them? Is there any performance advantage to explicitly commenting out those lines?

title: Will unnecessary Serial.print() statements slow down my program?

Answers: 3

body:
No, there is no `USART` wasn't enabled so skip all `print`s. Everything must be done anyways (calls, conversions to strings, writes to `UDR` - `USART Data Register`). It is just not sent outside by `USART` and it doesn't have to wait for `UDRE` (`USART Data Register Empty` flag) so it might be slightly faster.

You can use similar technique as Loggers - log level variable and `if`s (this can be changed runtime).

Or you can use macros:

    // comment out this line, if you want to show logs:
    #define NDEBUG

    #ifdef NDEBUG
      #define LOG(...)
      #define LOGLN(...)
    #else
      #define LOG(...) Serial.print(__VA_ARGS__)
      #define LOGLN(...) Serial.println(__VA_ARGS__)
    #endif

And later:

    LOG(F("Something: 0x"));
    LOGLN(variable, HEX);

And how it looks after macro substitution? For code:

    if (...) LOG(F("something")); else LOG(F("something else"));

With NDEBUG defined it's expanded to:

    if (...) ; else ;

And without NDEBUG defined it's expanded to:

    if (...) Serial.print(F("something")); else Serial.print(F("something else"));

body:
The compiler cannot know what the situation with the device is at runtime. The function itself must determine that, so the call _will_ take place, with arguments and everything. A well-written function would test early on whether there was anything to do, and if not then return early - but that still wastes time.

The norm in programming is to have two versions of the code: one labelled "DEBUG", which has lots of `print()`s, and one labelled "RELEASE", which uses language contructs to ignore them. This is achieved a number of different ways - but Arduino doesn't really support this out of the box.

@KIIV's answer, using `#define`, is one way to do this. The problem with it comes when you have multiple modules, or are using libraries that themselves do their own `print()`s. If you only have your main sketch, then it would work fairly well.

body:
A quick test shows that not doing a Serial.begin makes things run 10 times as fast. For example:

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

    void setup ()
      {
      Serial.begin (115200);
      pinMode (13, OUTPUT);
      }  // end of setup

    void loop ()
      {
      digitalWrite (13, HIGH);
      for (byte i = 0; i < 100; i++)
        Serial.println ("But does it get goat's blood out?");
      digitalWrite (13, LOW);
      delay (500);
      }  // end of loop

That took 292 ms to do 100 x of those prints on my Uno. If I comment out the Serial.begin call it takes 29 ms. So, faster but not incredibly fast.

On [my page about debugging](http://www.gammon.com.au/forum/?id=11329) I have suggested code to turn on or off debugging prints. The basic idea is to have a Trace define that lets you output stuff if debugging is on, like this:

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

    #define DEBUG false

    // conditional debugging
    #if DEBUG

      #define beginDebug()  do { Serial.begin (115200); } while (0)
      #define Trace(x)      Serial.print   (x)
      #define Trace2(x,y)   Serial.print   (x,y)
      #define Traceln(x)    Serial.println (x)
      #define Traceln2(x,y) Serial.println (x,y)
      #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

    #else
      #define beginDebug()  ((void) 0)
      #define Trace(x)      ((void) 0)
      #define Trace2(x,y)   ((void) 0)
      #define Traceln(x)    ((void) 0)
      #define Traceln2(x,y) ((void) 0)
      #define TraceFunc()   ((void) 0)
    #endif // DEBUG

    void setup ()
      {
      beginDebug ();
      pinMode (13, OUTPUT);
      }  // end of setup

    void loop ()
      {
      digitalWrite (13, HIGH);
      for (byte i = 0; i < 100; i++)
        Traceln ("But does it get goat's blood out?");
      digitalWrite (13, LOW);
      delay (500);
      }  // end of loop

Now in this case, with DEBUG defined as `false`, the time taken with pin 13 high is now only 5 µs - a substantial speed-up.

If you define DEBUG to be true, then it is much slower - 290 ms as in the first test.

---

The suggestion made by KIIV will fail if you have `if` statements:

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

    #ifdef NDEBUG
      #define LOG(...)
      #define LOGLN(...)
    #else
      #define LOG(...) Serial.print(__VA_ARGS__);
      #define LOGLN(...) Serial.println(__VA_ARGS__);
    #endif

For example:

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

    if (something)
       LOG ("something is true");

    digitalWrite (8, HIGH);

Imagine that debugging is off. Now the empty define makes the code look like:

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

    if (something)
      digitalWrite (8, HIGH);

So you have a side-effect that the code behaves differently if debugging is off.

---

> Semicolon is not part of the macro, so it will be expanded into: `if (something) ;`

See [What does the c precompiler do with macros defined as (void)0](https://stackoverflow.com/questions/25021081/what-does-the-c-precompiler-do-with-macros-defined-as-void0) - there are subtle issues with using an empty define compared to void(0).

For example:

      Serial.println ("hi there"), LOGLN ("debugging");

That fails to compile (with the empty define) if debugging is off. The `void(0)` version does compile. Admittedly it's an edge case, but nevertheless ...


body:
I was trying to play with Arduino this weekend and connected a DC motor to `A0` and `GND` to measure the voltage it provides when I rotate it.

However,
when I rotate the DC motor with my fingers to test out the readings I see that when rotated clockwise it generates voltage that can be read in Arduino. But when I rotate it counter-clockwise the values I get are 0 - this is probably because DC motor generates negative voltage (?).

How do I fix this so that no matter the direction of the turn I get always positive value?

I am trying to build a simple anemometer, just for fun for kids and plot the values, however can't do much when I get 0 on `analogRead` when wind blows from the other direction..

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

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

thanks for any input into this.

title: analogRead DC Motor - Negative value

Answers: 2

body:
You can use full wave rectifier, but there is a significant voltage drop on it.

Another way is using Voltage divider to provide `1/2 Vcc` to one of the motor terminals. But then you can measure just `1/2 Vcc` in both directions (without another Voltage divider)

Something like:<br>
[![enter image description here][1]][1]

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

body:
I wouldn't connect a motor (or indeed any inductive circuit) to a semiconductor without protection. This should limit -ve as well as excessive voltages.

The simplest is to use clamp diodes to Gnd and 5V and connect the motor via a resistor. This will limit any incursions to one diode drop either side of the supply voltage, which should be safe.


body:
I'm building a MIDI guitar, using an Arduino, sound synthesising and wood.

To properly know which note I'm pressing, I built a voltage divider with 12 equal resistors (10K). One side is connected at +5V and the other end at GND, so each of the 6 strings connects the right tap to the ADC.
I had just calculated the expected value w/ a bit of math considering I also needed a pullDown resistor(1M) and capacitor for every analog channel to keep the readings stable when no key is pressed.

[![circuit][1]][1]

When measuring with my multimeter the readings are stable, and there are variations of less than 0.02V, and since the difference from tap to tap is about 0.4V that's quite good.

The problem is when reading the 6 channels together: channels supposed to be pulled down to gnd read voltages caused by nearby channels, readings are shaky and similar errors.
This mess disappears on one channel when I connect the multimeter to that one.
Instead of buying 6 multimeters, I figured I could ask you if someone has an idea on why this happens, my guess is on the pulldown resistor, but I'm not sure about Arduino's ADC; I'm also worried about having 6 wires half of a meter each so close, so any other idea on finding the keys is welcome.

EDIT
@EdgarBonet was right, I used 12x220ohm resistors, and at first the results were absolute garbage, then I made it so the code would read each channel about 10 times, discard the readings, wait a millisecond and finally read and store the value. Now it is perfect.
Thanks again.

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

title: AnalogRead from voltage divider ladder

Answers: 1

body:
The datasheet of the ATmega328P (the main chip of the Uno) states:

> The ADC is optimized for analog signals with an output impedance of
> approximately 10 kΩ or less.

The [Thevenin equivalent][Thevenin] output impedance of most taps of
your voltage ladder is higher than 10 kΩ. You 1 MΩ pulldown is
way beyond that limit. Cross talk from previously read channels is
exactly the symptom you expect from excess output impedance.

Taking each reading multiple times, until the value stabilizes, should
help. A buffer (e.g. an OP-amp set as a unit gain amplifier) is the
usual solution to this kind of impedance problems.

[Thevenin]: https://en.wikipedia.org/wiki/Thévenin's_theorem

------------------------------------------------------------------------

> Actually, the whole works perfectly with R as 220 and pull downs as
> 10K. The problem comes when connecting more than 3 strings at the same
> time, on any tap, as the pull down resistors become part of the
> ladder (i belive).

The pull down resistors will indeed have an effect on the potentials of
the voltage ladder, especially if you connect several strings. This
could be minimized by having the pull-downs be _a lot_ more resistive
than the resistors along the ladder, but then you would need very low
resistances along the ladder, which is not desirable because of current
consumption and heating.

Here is an idea for an alternative solution: If you can spare 6 digital
pins, you could build for each analog input a pull-down circuit that is
switchable between a “strong pull” mode and a “weak pull” mode. Assuming
D0 is the “pull strength control” pin for A0, it would look like this:

    A0 ---+--- 1 kΩ --- D0
          |
         1 MΩ
          |
         GND

Whenever you want to read A0, you:

* set D0 to `OUTPUT` `LOW`, which creates a strong pull-down to ground
* take a couple of analogRead()s
* set D0 as `INPUT`, which leaves only the weak 1 MΩ pull down
* take a couple of analogRead()s, keep the last one.

If A0 is not connected to the ladder, then the first reads will
discharge the internal sampling capacitor of the ADC. The final read is
done with only a weak pull-down, but this should be OK since the
capacitor has already been discharged.

The potentials along the voltage ladder will be disturbed by any string
connecting a tap to its strong pull-down, but this disturbance will
disappear when you switch to weak pull-down, so it will not affect the
readings.


body:
I'm trying to get some binary data from an Arduino Due to Matlab.

Basically this is the setup:

Due:
<!-- language-all: lang-cpp -->

    byte usbMsg[33]= {0};
    // filled with dummy as example
    usbMsg[1] = '00000001';// in[3];
    usbMsg[2] = '00000001';//in[4];
    usbMsg[3] = '00000001';//in[5];
    .
    .
    .
    SerialUSB.write(usbMsg, 33);

And on the Matlab side, I open the corresponding COM port and use a command like this one:

     a = fread(serialPort,3)

this gives me:

     a =

        49
        49
        49

which is the ASCII representation of the data I sent.

Can anyone explain to me why this happens and what I could do? As I understood `serial.write` sends binary data and `fread` reads binary data.

title: ArduinoDue - Matlab: SerialUSB.write() sends ASCII?

Answers: 0


body:
Here are three use cases. Are all preferred or is the use of the `F()` macro pointless on some?

**1.**

    Serial.println(F("some string"); // definitely useful here

**2.**

    String str = F("some string");
    Serial.println(str);

**3.**

    int num = 5;
    String str = F("some string with int ");
    str += (String)num;
    Serial.println(str);

title: Question of proper usage for F Macro

Answers: 1

body: Any time String is involved F() becomes pointless. Avoid String like the plague if you value your memory integrity.


body:
I am running the following sketch on an Arduino Uno using Arduino 1.6.8.
Strip is a WS2811 12V.

    #include <Adafruit_NeoPixel.h>
    #define PIN 6
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show();
    }

    void loop (){
       strip.setPixelColor(0, 255, 0, 255);
       strip.show();
    }
The problem is that the LED’s light in (Green) groups of three and what I want is individual control.

    strip.setPixelColor(0, 255, 0, 255); Illuminates Pixels 0,1,2
    strip.setPixelColor(1, 255, 0, 255); Illuminates Pixels 3,4,5
    strip.setPixelColor(2, 255, 0, 255); Illuminates Pixels 6,7,8

And so forth.

Although this code uses NeoPixel I get exactly the same issue if I use the equivalent in FastLed.

Any pointers to what I am doing wrong would be appreciated.

title: Arduino only addresses 3 LED at a time

Answers: 1

body:
LED strips with WS2811 and 12V are the ones with one driver and 3 RGB LEDs on it. These are interconnected so you just can't control less than whole group of three.

If you need individual control, you have to get 5V variant with [WS2812][1].

  [1]: http://www.tme.eu/gb/details/hc-f5v-30l-30_20/light-sources-led-ribbon/worldsemi/hc-f5v-30l-30led-wip20/