text:
Help with MPU-6050
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

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)? - And what the angular velocity is measured in?

Angular velocity = Degrees per second, I want gyro values in degrees @EugeneSh.

All the references of Jeff Rowberg's library are in his library. His code is pretty well commented. I used the raw.ino of his examples for one of my projects and it worked perfectly.

Just use Jeff Rowberg's code and go through all the lines in his code, perhaps even open up the .cpp and the .h to get a better understanding what is being done with your code.

Yea I opened and read library and cpp. I will try to go through again :). I got a work around for now thank you  @Len

@TejaAllani also, I get that not understanding the library can be frustrating, but I know for sure that it works really good. Sometimes that's enough and that's also a bit why you'd want a library: you don't have to write and understanding everything yourself because the library will do the hard work for you. Good luck with your project.

@Len, I read through every line of code in .h and .cpp file patiently. I finally got an outline of how it works. The problem when I first saw those files was my C++ programming. I didn't know how library is made and what does .h have to do with .cpp file. I thought they were separate and had no link to each other. After hours of googling finally I was capable of understanding link between .h and .cpp that .cpp had function definitions which were declared in .h file. Now I can use that library with satisfaction :D. Thank you for the help.

hey teja would you mind sharing the code, as I am also stuck on this for quite a while.

@Mahshida, the code is in the Answer

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;
}

Hi, Teja Allani, Thanks for sharing the code. It works. One issue puzzles me though, in the offset subroutine, the code takes the 2nd MPUread() for the initialization. Is there any reason for doing so?  I did some tests by marking the 2nd MPUread out and my tests do reveal different results.

Further, it seems that the code yields angles that are limited to (-45, 45). Where do I need to change for angle computation extended to (-90, 90)?

Hello :) @Jesse , The 2nd MPUread() because the first couple of readings are not stable it takes some time for MPU to give stable results, for this same reason I put i>100 in the loop so 1st 100 readings are not used for calibration.

and for that angles use atan2() instead of atan() to change the limits of the angles. This code still needs some improvement because I found that when roll or pitch cross 90 degrees they seemed to effect each other( I can't explain this phenomenon clearly test it out after replacing atan() with atan2() ) maybe its because the values of Ax and Ay  become negative after crossing 90 degrees and this sudden change from +ve to -ve and effects filter. _Also try changing gain value and observe results _

Thanks for the feedback. I did check that atan() takes one argument and  the angle can be between [-90,90], leading me to think that some improvements are needed.  Anyway, you got most of it in one sleepless night is quite impressive. Best wishes.

After testing this with my project I found out that this program is only helpful for roll and pitch < 90 degrees. So I decided to use Jeff Rowberg's library. After going through code, I found out that it was only way to get perfect values out of sensor.

Hmmm, interesting to know that. My test on your original code showed (-45, 45).  Have you updated your code?

@Jesse Just updated it

used atan2 which takes 2 args. Thanks. Nice learning from you.


text:
How to increase current in Arduino uno?
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

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

You can use a TT2148 power transistor-this can connect to arduino without a resistor and deal with high current.

Personally I'd prefer a MOSFET...

What model of MOSFET do you prefer to use?

That depends on many factors - current levels, switching speed and voltages, footprint, etc. I have many that I often choose between. One of my current common ones is the TSM2314CX

The TSM2314CX then. That depends on many factors-state the obvious!

Which type of transistors I can use?? I can use TIP120 transistor?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
SIM900 module not responding on hardware COM port
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.

Are you providing an external power source to the sim900?

Yes, the external power is there

Well, all I can suggest is to add an Arduino. Otherwise, why ask us?

What you mean "why ask us ?" I'm asking because I have a problem that I want to solve !

Yes, but you have removed the Arduino from the equation, so I fail to see how we, the Arduino Stack exchange, can help you with it?

There has been a similar question about connecting to the hardware serial pins on an Arduino Uno. The schematics revealed that this might be a problem. https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf

Why would that be a problem ? I've had my interface board connected to arduinos hardware serial on the breakout connector and running a sketch that just prints out "hello world". I've had the "hello world" printing correctly  on putty. However, I wasn't able to program arduino this way.

@Majenko - Although SIM900 can be used with many platforms, it is most commonly used with arduino, hence the reason I'm posting here.

But you aren't using it with arduino. You had no problems using it with arduino, so your problems must be related to things that we have no knowledge about.

Where do you suggest I go then ?

authors: กานต์ แซ่โซว

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Is applying 5 volts to LED dangerous?
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?

So you want to know if you should use a resitor along with the LED?

The brigtness of an LED depends on the voltage acorss it and the resistor value that used in series when it connect to a power supply. You will find varying the voltage and resistor values will cause the LED to have different brightness.

I don't understand why people downvote (and I don't want you to upvote). I'm just asking a beginner question that I cannot find answer to on Google. Should I put "WARNING: BEGINNER QUESTION" at the beginning of my question?

@Roman I see that someone has flagged this question as "off-topic" I think it's actually a very relevant question (though may fit better on electronics.se, but they'll probably dislike your question anyway). I must say that your question is also not very clear, you seem to ask a lot of different questions at once.

I'll vote to leave your question open, since it already has a lot of good answers. You may want to try to cleanup the question (make it clearer) for future reference.

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!
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 for more about calculating the proper LED series resistance.
In general, LEDs that are over driven will grow dimmer and not recover.

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.

What would happen if the LED recieved 5V for longer than a second?

It will probably survive, since the internal resistance of the supply will limit the available current. You should be more worried about what is providing the 5V - that won't be too happy.

Looks like the 5V pin providing the 5V

An IO pin? Then you will be stressing that IO pin considerably and sustained usage will result in the death of that IO pin as the high-side drive MOSFET burns out through excess current.

@Roman You can get LED's with integrated resistors if you dont want to use your own resistor

No, not the IO pin. I have little experience with this, but thank you for details. I'll have to bookmark this to read later.

@qwerty10 I have the whole kit from Amazon that comes with 100 resistors. So I think I'll watch and learn from exploding LEDs than use fancy LEDs :-)

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.

Blue LEDs tend to be very efficient and will even give a little bit of light when the current is in the micro amps range. PS running too much current through LEDs can be fun. They sometimes give a different color light for a while before dying. They won't explode. They can release a bit of smoke though.

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.


text:
Why have resistor at end of circuit cycle if GND dissipates final energy?
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: .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?".

Hint-Historically it was first thought that electricity travels from positive to negative. Then it was later discovered it actually travels from negative to the postive.

My world is flipped, not the LED. Ok then, what was the deal then with having the resistor attached to the POSITIVE, the 5V, not the GND, in challenge 1?

What do you think the resistor does in your circuit? I dont have your book in the photo by the way

I'm not big on physics or electricity, but if I have a resistor that converts 3V electrical energy to heat, then out of the 5V of current connected and flowing through the resistor, 2V will come out ;D

"Ground" means neither "no voltage" nor "no current".

Then what does it mean?

Ah. Ground it where current comes from. I need to get some sleep. AND so do you @qwerty10 you've been answering my questions all day.

why does resistor work on POSITIVE!? - you lost me there.

Sorry @NickGammon. I didn't mean to. I revised it.

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.

I'm learning about Ohm's law in the manual and voltage drop from a youtube channel. Don't underestimate the knowledge of an 8th grader! (So you are saying that current flows in a cycle without dissipating?)

I'm not sure what you mean by dissipating. If you flip that diagram upside down you could just as well say that "ground" is at the top. The current will still flow the same way. The word "ground" is really a convenient way of saying "reference point". For example, when you measure the height of kids in the classroom, you would normally measure with reference to the floor. However the floor is not "dissipating" their height.

I need to learn more about circuitry. I'll come back to this after I learn physics on Khan Academy. Brb.

One way to think of this is having marbles fall under gravity through some machines or restrictions. The further they drop, the more work they can do - but they remain intact all the way from top to bottom. The 12V battey here is an escalator lifting marbles back up to be used again.

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.

If current flows - to + then why does a resistor on GND make no difference on LED but connected to the 5V, it does? I'm now getting that the GND is some sort of "power supply return"..

@Roman You don't have  "a resistor on GND". An electrical circuit is just that a "circuit". It is a closed loop comprising the Power Supply, LED, resistor and switch. It makes absolutely NO difference in which order these are connected.

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.

If the current (electricity) then "flows" in a closed system in a loop, what's the point of GND? My dad told me that it makes the energy dissipate.

"Ground" is a bit of a misnomer. Most of the time it is actually "power supply return" and the 0v reference rather than a connection to physical ground.

Thank you @IgnacioVazquez-Abrams.
Of course it's not literally "ground". But if some of the energy on the 5V circuit is lost along the way, then what's the point of a power supply return? If say, 3V are lost/used in the circuit one way, then 2V isn't enough to power, right? I'll come back to this once I get more experience with circuits, schooling system here where I'm at isn't thoughtfully implemented. I first learn electrical engineering in 6th grade, forget everything and then start learning physics in 8th.

All of the energy is lost in the circuit. But the electrons still need to be returned to whence they came.


text:
Multiple transmitters and problem with ref
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!

I wouldn't send those three sensor values in different packets. Just combine them in a single packet. As you are currently relying on the order of the packets, things will get messed up if a single packed isn't being received. Using a single packet will prevent his problem.  I'm not really understanding your question. I'm also missing the senders Arduino code.

@Gerben the data is coming from three distinct radio transmitters, and the question seems to be about using the radio's multiple pipes feature to keep the feeds distinct.

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 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();
   }
}

Just two corrections: millis() is lowercase and from the available() prototype, you should pass in '&pipe' rather than 'pipe' so the function can modify it to the pipe that has available data. So, no need for the loop.

Thanks!   Tying "Millis" felt odd when I was doing it, but it is that way in the title of the reference page, but not for the actual function.

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.

This would work in the generic case, but the poster appears to be use the nrf24l01 "pipes" feature to keep their channels unique.  Since they have that out-of-band distinction, they don't need to implement an in-band one with identifiers in their data.

@ChrisStratton I agree. This is unnecessary, since the library already provides a convenient way to do it.

The actual capability comes from the radio hardware, the library merely exposes it.

@ChrisStratton True, but digging through the NRF24 docs to find this and then implement it would be a pain.


text:
Is it safe to use the same power source for Arduino and its Motor shield?
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 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

Only if the motor gets it's power from the power source itself. If you power it through the shield and Arduino, you will still kill your Arduino.

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.

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.

Please see my edit

Yea, it seems it's better to power the arduino seperately then like @goddar tells.


text:
FreeRTOS: Object not created properly from within task
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);

'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.

As I discovered just minutes ago, the FreeRTOS_AVR port only supports C and not C++. This might explain the error when creating a instance with the C++ "new" operator


text:
Can't connect to my Arduino via W5100 Ethernet shield
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.

Genuine Arduino shield, or Chinese knock-off? Those Chinese knock-offs often need a few resets to get them to actually communicate.

@Majenko it's a Chinese one, what do you mean by few resets? Clicking the reset button few times?

That usually worked for me, yes.

Oh, and you might like to wrap all your string literals in F("...") to move them out of precious RAM.

@Majenko alright, I'll try when I get back from work ;)

Does your Arduino support ping?  Looking at your code I can't see where you open the socket and monitor it for incoming ping requests.

@Matt I suppose yes, as long as the WebServer is up and running...

@FabioEnne - Do you mean the webserver on the Arduino?  I wouldn't expect that to make a difference to the ping service.  Maybe I'm wrong but I don't think an Arduino responds to ping unless you have put some code on there to do it.  Basically I think your system is working.

@Matt Probably you are right..anyway my Router doesn't see him as a connected device, so also via Browser I got no response from the Arduino IP.. very strange...probably is a faulty Ethernet shield..

Yes given that information I would get a new shield.

"...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:

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);
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. 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:

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!);
configure my Linux ethernet interface (eth0) with an IP like 192.168.1.99;
run an arping -I eth0 192.168.1.6 (where arping is this 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

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!

I read with a lot of interest, but yesterday I passed in front of a shop in Milan who was selling an original Arduino Ethernet Shield 2 for 22€ so I couldn't resist and I've bought one, connect and everything worked fine in less than 3secs..I suppose that the oder CHine clone for 4€ was a waste of money ;) Thanks everybody by the way


text:
Controlling a capacitive touch screen that doesn't have I2C/SPI
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, 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?

... You would look for the HX8352B datasheet and start reading.

I've never seen a I2C interface board for a proper display (the LCD 16x2 piggyback boards excluded).  Could you use something like this as a starting point MTCH6303-I/PT

@Matt I'd agree it isn't really an Arduino topic, but the touch issue is hardly an ESP8266 topic either - as Majenko points out it needs a capacitive touch controller.  If the touch issue were solved, the greater bandwidth and memory the ESP devices may make driving the display itself a bit easier than with an Arduino, but that's not the question being asked.

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.
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.

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.

There are two major parts to a capacitive touchscreen:

The touch panel
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.


text:
Nordic nRf905 (433MHZ) with arduino receive garbage data
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:

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.

Any help will be appreciated.
Regards,
rajneesh

This is far too incomplete to be answered.  You must provide full details of wiring, power, and transmit and receive software.

Your question Question is there are 0x4C set exactly 433MHZ. doesn't make a lot of sense. You should try to be more specific in what you are asking.
However a couple of pointers for troubleshooting:

Is the TX side set to transfer ASCII/Text data ?
Are you sure the baud rate is the same on the RX arduino and the PC you using the serial monitor on ?

Thanks for reply, I have provided all details in above post.  Wiring connection with arduino and nRF905 => TXEN=5;
TRX_CE=4;
PWR=3;
CSN=10;
AM=9;
DR=8;
CD=7; MOSI = 11; MISO 1;SCK=13; Ya I have checked baud rate of arduino and pc bath are same. As a transmitter device I have used https://www.alibaba.com/product-detail/RF-100m-transmission-distance-wireless-Magnetic_60286055162.html?spm=a2700.7724857.0.0.ov1gVH  .This is work on 433MHz. Still I am confuse If AM and DR pin set to high then why I am receive garbage data?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How can I read Data from 150 Arduino Serially to a Single Arduino to display it via serial port.
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.

That's... not realistic. On a uno or with rs232 as the chosen protocol.

How much data is being sent, and how often? Also, what is the "computer" that these Arduino's must talk with? Another Arduino? Or a PC?

Check out the Chainduino.

This should have been closed as a duplicate of existing questions on EESE, not migrated.

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.

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.

simulate this circuit – Schematic created using CircuitLab
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.


text:
Powering ESP8266 from Leonardo's 3.3v pin
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:

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

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.

Thanks! And the 5V pin can handle the current?

If supplying power via USB it should be fine unless you have a few other devices connected to it. If supplying power via an external 7-12V supply then the on-board regulator may get a bit warm, so you'll have to judge from that.

That specification in wrong. The 3.3v regulator is actually 150mA not 50mA. Don't believe everything you read on the Arduino website.

Ok, so which one should I trust? I don't want to find out by testing and killing my brand new Leonardo ;)

If you're communicating with the ESP8266 for very short bursts then you may be able to get away with the on-board LP2985 if you add a local bulk capacitor. If you need constant communications then you should strongly consider a larger regulator.

Ok, I finally used an LM2596 to lower the voltage from the 5V pin to 3.3V and a voltage divisor for the Rx pin in the ESP8266 module.

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.

Actually that's the one I've been using. Aaand, I got rid of the Leonardo. I'm programing the ESP module, avoiding the bottleneck of the slower Leonardo's processor.


text:
Is Arduino WiFi101 library fully compatible with Arduino MKR1000 with WiFi HW?
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


text:
Garbled serial from GPS device
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 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 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?

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.

This might be the case, but it also might not.  Can you say where you found the "datasheet" that lead you to conclude this?  Most of the information seems to be quite non-specific, so it's hard to be certain if the device itself uses RS232 signalling, or if they merely make a cable adapter available that converts between their undocumented proprietary signalling and proper RS232, just as they seem to make one which converters it for use with USB.

The model I bought is not using RS-232. Check the data sheet I linked in the initial question and search for "voltage," you'll see that it's using 5v for TX and RX.

I may have I jumped to a conclusion too quickly. The PS/2 to RS-232 cable set for PS/2 to RS232 conversion is what got me thinking. [link] http://usglobalsat.com/store/p-228-br305-rs232-rs232-cable-set.aspx#http://www.usglobalsat.com/images/product/large/228.jpg . You can see that the TX and RX pins go directly to the RS-232 connector. With not much info available in the "datasheet" I made the assumption that it uses RS-232. I apologize for not being too clear about how I came to the above answer.

No worries, @AjayPrabhu. Thank you very much for helping.

I spent some time looking around if anyone interfaced the same with arduino or any microcontroller. I found this project. You might want to take a look at this [link] (http://danceswithferrets.org/geekblog/?p=482). Hope this helps.

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.)

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.


text:
What's Leonardo 5V pin current limit?
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!

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.

But 5V is a poor supply voltage for a LM741 due to its rather large headroom requirements.

@IgnacioVazquez-Abrams You meant to say "But the LM741 is a poor op-amp because of its rather large headroom requirements"... ;)

Yeah, that too

@IgnacioVazquez-Abrams I can't recall ever actually seeing an LM741 in a new design in the past 10 years... They still exist for some reason, but I am not aware of anyone in their right mind that would actually use one.

It's been a while since I used opamps... I guess I messed up, should have used 358s instead :S

Ugh, just as bad ;)

what're the practical applications for op-amps? I know, google.

@user400344 Op-amps have many many practical uses - from comparators (as in the Uno power selector) to audio pre-amps, to instrumentation amplifiers for sensors - the list is long. They are incredibly useful gadgets.

I'm gonna get some :)


text:
Using an Atmega8 Chip with an Arduino Uno instead of an atmega328
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?

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

Part 2 of your answer doesn't apply if you edit boards.txt to match whatever oscillator settings you will use.  One can use a fuse calculator like at engbedded.com, click to select ATmega8, click to select feature and frequency combination as needed.  Edit boards.txt accordingly.

@jwpat7 I updated the question- should have mentioned Im using the crystal in the question. And your comment is useful and interesting.


text:
Transforming from analog output to speed and acceleration with gy-61
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?

Probably relevant http://arduino.stackexchange.com/q/13887/972

I assume that your accelaration hardware work. Becuase it gives you different analog outtput in with diffrent accelaration. it seems what you are asking for is how to calibrate it. As a guess there should be away to calibrate the accelaration for each axis when the sensor not moving in the x,y,z plane for zero acceleration. See the page https://learn.adafruit.com/adafruit-analog-accelerometer-breakouts/programming is what you seem to be looking for. Im not sure how your code works works, because acceleration is defined as the differential of velocity function which to me means that yoe mu

st measure the rate of change of velcocity at two different point in time to measure the accelaration-to estimate the accelaration at that time point. Or if the hardware gives you the accelaration directly you dont need to measure new and old velocities. Once you have calibrated it you can convert the accelaration to a single accelration by using pythagoros's theorem in three dimension to get the size of the final accelaration.

However, the above two comments are are just an educated guess, to give you some ideas,  becuase I dont have the accelaration hardware you are using.

Since I can't comment I must post this as an answer. To get changes in values to be considered as speeds and accelerations you need to take time into account. Distance=rate*time. So Distance divided by time gives you the rate (speed). Then you can measure the change in speed over time to get accelerations. The GY-61 is capable of directly giving some of the readings you are looking for. Here is one article about it that you may find useful: https://waime.wordpress.com/2015/03/15/basic-measurement-with-accelerometer-gy-61-with-adxl335-chip/ Like @qwerty, I am just ruminating here.


text:
Error while installing bootloader ATmega328
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:
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?

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.

Fixed! :D I must use 22pf condensator to quartz

Okay good. I think I should leave the answer because if anyone else has working hardware but needs slightly different boot loader settings for a different board it is useful. What do you think? I'll edit it to mention ensuring the hardware works first.


text:
Trying to read analog signal with digital pin using outside ADC
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.

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.

If you don't plan on adding anything else that uses SPI you could just connect the ChipSelect to ground, and free a pin on the Arduino.

@Gerben That is not good practice. Chip Select is not just used to multiplex the bus but also to synchronise the start and (sometimes) the end of communication.


text:
Can you save data to EEPROM using firmata?
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?

What have you tried so far in you code? Have you tried using the adrunio eeprom write function with your arduino program -so once it knows the unique ID (in your arduino program) it writes it to the EEPROM using the command EEPROM.write(address, value) and the library EEPROM.h

Which firmata sketch for the Arduino are you planning on using?

I am using Standard Firmata Plus for one board and Standard Firmata Wifi for the other.

Currently, I've been putting a resistor in the first analog pin and Identifying the board based on that resistor value, I need a better way of doing this and I haven't been able to successfully find a method of saving to EEPROM via firmata.

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

add the EEPROM library
include the library into the Firmata code
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 library, specifically in EEPROMCalibration.ino
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.

Thank you for the response! Yes, that would allow the Arduino to have access to its ID stored in EEPROM, but I need to be able to read and write this data over Serial using the firmata protocol.

Please find the updated response: you can use two of the 16 reserved commands (0x00-0x0F) and attach your EEPROM reading/writing functions.


text:
Trouble reading LM35 with long (?) Ethernet connection
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.

Can you show a schematic, preferrably with the ethernet wiring explicitly labelled. You might benefit from adding a line driver circuit to either end, or switch to a digital temperature sensor such as a DS18S20. Alternatively you could get some wonderfully cheap NRF24 modules and have everything wireless; that's worked for me.

Thanks, the NRF24 is really nice, but I am afraid that I do not have enough space for its library on Arduino.
But if I switch to a digital temp sensor wouldn't I face the same problem and need a line driver anyway?

I don't know; it depends on how you wire it. When I said "Ethernet wiring explicitly labeled" I meant for you to show the colours of the conductors you used. Not Fritzing's make-believe version: what YOU are actually using.

30C is quite a variation... you're looking at ±300mV variance in your analog signals. Check for loose connections in your wiring. Also check what voltage the LM35 receives on its power pin after the long run of Ethernet cable.

Sorry, I misunderstood your post. I am using the green, orange and white-orange conductors for 5V, ground and signal, respectively.
The voltage received by the LM35 is around 4.2V and with a multimeter I do not see that kind of variance. The problem also remains if I change the analog inputs on Arduino.

At least you're using a twisted pair for signal/ground. I wonder if you'll see an improvement if you connect white-green to ground as well.

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.

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:

open a circuit to an internal capacitor
charge the capacitor
disconnect the circuit
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.

Thanks a lot, I will try this as soon as I get back to the setup.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Detecting mutual contact between balls
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".)

If you want to do it with  easy to get  hardware I guess you can do it without an arduino as follows. If the balls are large enough and they are different colour you can use a machine vision C++ library (such as for example openCV can be used for example to track tennis balls direction and the uniquely colored tennis ball and it tracks more than one ball). All you need is a webcam and PC. Though, I dont know if openCV work an a small PC like a raspberry PI.

@qwerty10 That's an interesting idea. I don't think it will work in my particular case, because I intend to be holding the balls and moving around. My body would likely get in the way of the camera's view. It would also be difficult to distinguish between "touching" and "appear to be touching due to perspective".

I still guess your problem can be solved with machine vision becuase machine vision is used to detect if a point or score has been made
in professional televised tennis or soccer matches (or football
as its called outside USA). In those sports its required to detect
if the moving ball (where ever it is in the air) passed over a line
and touched the surface or floor and I guess you would need to be
accurate with that (say 1mm error bound) to decide that. Also there may be players in the way of the camera view of the ball. I dont know if that sports technology uses openCV.

To me your problem sounds like the problem solved by the sports technology (which uses machine vision).But I dont think an arduino can not do something like track a ball to accuracy such as 1 millimetre in 3D space in someones  hand with the person moving around a few metres-this is what you seem to be asking for-but I maybe wrong as Im new to arduino.

How big are the balls? How big is the surface? Can you do anything to the surface? What are the balls made of?

@Gerben The balls would be hand-sized, about as big as a baseball or softball. I'm not sure what you mean by "the surface"; I care about mutual contact between two balls not contact with a surface. I can make the balls out of whatever I want, but I want to be able to hold them without causing false positives.

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.


text:
CS5211AGP wireless RF transmitter (433MHZ) address decoding problem
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.

Now please say about what address should I set at receiver side for communication.
Thanks in advance.
Regards,
rajneesh

I don't think the nRf905 and CS5211AGP are compatible. They both use their own protocol.

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.


text:
Is my MQ-2 gas sensor analog or digital?
I have this MQ-2 gas sensor for an Arduino Uno:

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.

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 ;)


text:
Why are my objects losing their member's values?
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:68 which is where all the garbage is coming from.
Related code:

RemoteControl.h:37
RemoteControl::getChannel

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;

The F() macro is a life saver and certainly thwarted these goofy lockups. I must have been lower on memory than I realized. Thanks for introducing me to this. Also, I use this-> and other tactics to keep track (visually) of where my data is coming / going; everyone has their style.

authors: Женёк Семёнов


text:
Will unnecessary Serial.print() statements slow down my program?
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?

You may write your program in machine code instead then you'd know exactly what the microcontroller is doing.

What has that got to do with Serial prints?

No, there is no USART wasn't enabled so skip all prints. 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 ifs (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"));

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.

A quick test shows that not doing a Serial.begin makes things run 10 times as fast. For example:
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 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:
#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:
#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__);
  #define LOGLN(...) Serial.println(__VA_ARGS__);
#endif

For example:
if (something)
   LOG ("something is true");

digitalWrite (8, HIGH);

Imagine that debugging is off. Now the empty define makes the code look like:
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 - 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 ...

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

A way around the if(...) [macro] problem is, when debugging is turned off, to define your macros to equate to {}, such as #define LOG(...) {}, then the if(...) turns into if(...) {}

@Majenko But if you have: #define MACRO() {} and you'll use it as: if (...) MACRO(...); else ...  (notice that semicolon) it will turn into if (...) {}; else .... That's why the pattern do { ... } while(0)  is used sometimes instead of simple block { ... }

Semicolon is not part of the macro - you edited your post after I made mine. In your original post (as you can see from what I copied/pasted) you had semicolons.


text:
analogRead DC Motor - Negative value
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..

thanks for any input into this.

What you're doing is a bit like using a DC motor as an AC generator. So to convert a negative voltage to a positive on in this case you can use a rectifier circuit (its basically an arrangement of  4 suitable diodes) or buy it ready made. The rectifier will make the voltage positive all the time which is what you seem to want-though youll probably need another circuit to sense the direction of the wind. A brushless DC motor is probably a good choice for making  an motor based anemometer.

anemometers only rotate in one direction, because of the shape of the cups. PS you might want to add a resistor between the motor and the Arduino pin, to prevent damage if the voltage is above 5V or below 0V. Something like 10kOhm.

Some anemometers do measure direction of wind e.g. see wikipedia

@qwerty10 some do, but not the one shown in the picture.

@Gerben, thank you - that makes sense to allow the motor to spin in only one direction. All i really need is to show kids if there was wind or not and how 'big' it was - no details, just a fancy color graph. Let me try that, thank you all for your help.

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:

This is probably the easiest solution. Other option is to go for the full wave rectifier but using an op amp to take care of the voltage drop. An example can be found at http://www.eleccircuit.com/full-wave-rectifier-with-an-op-amp-ic/.

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.