text:
`servo.attach()` paralyzing (one) motor on L298N
I have 2 DC motors (well, 4; but each pair is controlled by the same "signals") connected via a L298N, which is connected to the Arduino. In addition, I have a servo motor connected to the Arduino.

When I run the following program (in reality, it's a bigger program; however, I've managed to chiseled it down to the following):
#include <Servo.h>

const int servoPin = 3;
Servo servo;

const int LMotorsSpeedPin = 5;
const int RMotorsSpeedPin = 10;
const int LMotorDirectionBit1Pin = 7;
const int LMotorDirectionBit2Pin = 6;
const int RMotorDirectionBit1Pin = 8;
const int RMotorDirectionBit2Pin = 9;
const int MotorSpeed = 150;

void setup()
{
  // 1
  pinMode(servoPin, OUTPUT);
  servo.attach(servoPin);

  // 2
  pinMode(LMotorsSpeedPin, OUTPUT);
  pinMode(RMotorsSpeedPin, OUTPUT);
  pinMode(LMotorDirectionBit1Pin, OUTPUT);
  pinMode(LMotorDirectionBit2Pin, OUTPUT);
  pinMode(RMotorDirectionBit1Pin, OUTPUT);
  pinMode(RMotorDirectionBit2Pin, OUTPUT);

  // 3
  digitalWrite(LMotorDirectionBit1Pin, LOW);
  digitalWrite(LMotorDirectionBit1Pin, HIGH);
  analogWrite(LMotorsSpeedPin, MotorSpeed);

  // 4
  digitalWrite(RMotorDirectionBit1Pin, LOW);
  digitalWrite(RMotorDirectionBit1Pin, HIGH);
  analogWrite(RMotorsSpeedPin, MotorSpeed);

  // 5
  delay(10000);
}

void loop() {}

1 Sets up servo.
2 Sets up L298N pins.
3 Sets up left motor data.
4 Sets up right motor data.
5 Tests the code above for 10 [s].

I assume that you'll need some experience with the L298N; however, here's the gist.
*MotorsSpeedPin sends each motor what speed (MotorSpeed 0-255) they must go (via PWM).
Data into a pair of *MotorDirectionBit*Pin tell each motor what direction to go (i.e. back 01, stop 00 11, right 10).

When I run the program above, only the left motor runs. However, if I comment out 1 (which essentially renders the servo useless), both left and right motors start to work.
I find this problem quite odd. What does the servo code have to do with the motor code (and only one at that!)?

The Servo library uses Timer 1 to create the servo control signal. That means it can run the servo on any pin or combination of pins, and at the 50Hz speed that a servo likes best.
However, pins 9 and 10 also use Timer 1 to create the PWM signal.
It can't do both.
As soon as you start using the Servo library you lose PWM on pins 9 and 10.
So what can you do about it? Simply move your pins around to different pins. You can't use 9 and 10 for PWM, but you can use them for the servo. So put your servo on pin 10 and your right motor speed control on pin 3 and all should be happy.

What's "Timer 1"?

A bit of hardware in the chip that counts real fast.

Thanks. Are you aware of any good sources that explain timers and other topics like it?

The datasheet for the ATMega328p is the source of all the information you could ever need.


text:
Why can't my .cpp file have a class of the same name?
I made a new Arduino IDE project ABC, and am given ABC.ino. Then I create a XYZ.h and XYZ.cpp.

ABC.ino:
#include "XYZ.h"

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

XYZ.h:
#ifndef XYZ
#define XYZ

#include "Arduino.h"

class XYZ { };

#endif

XYZ.cpp:
#include "Arduino.h"
#include "XYZ.h"

When I try to compile this, I get some error:
In file included from sketch/XYZ.cpp:2:0:
XYZ:8: error: abstract declarator '<anonymous class>' used as declaration
 };
 ^
exit status 1
abstract declarator '<anonymous class>' used as declaration

However, when I rename my class to something other than the file name, like XYZa, the compilation succeeds.

Why can't I have the same name class as the file?
I've done C++ projects (independent of Arduino) via Xcode and nano, and this has never been a problem.

INCLUDE THE FULL CODE!!!

@DatHa -- This is the full code. It's extremely boilerplate. :)

#define XYZ
...
class XYZ { };

After preprocessing, what do you think that ends up as?

IDK. But, if you're suggesting that it's because it's an empty class, I think I've ruled it out. If you add void QRS() to .h and void XYZ::QRS() {} to .cpp I still get that error AND another one.

Do you know what #define XYZ actually does?

I think it (along with #ifndef and #endif) is suppose to keep from duplicate code during linking?

That is what it is being used for. I asked if you know what it does?

Not particularly. :)

Ok. If I tell you that #define defines a symbol (XYZ in your example) as whatever follows it (nothing at all in your example) then you may see what is happening?

Ahh!!! Yes. I always assumed #define ends at a return carriage. After adjusting the first 2 lines by appending _H_, it begins to work. So, that leads to me asking, why does it work now?

Because now you are defining XYZ_H_ as nothing, and leaving XYZ as XYZ.  When you use #define, any occurrance of the symbol you have defined gets replaced verbatim with what you defined it as (nothing in this case), so by using XYZ  you ended up with XYZ being replaced by nothing, so the class definition ended up as class  { };

#define XYZ

class XYZ { };

The first line tells the "C preprocessor" (called before C and C++ compilers) to replace XYZ with nothing everywhere it happens, hence after preprocessing, and before compiling, that code becomes:
#define XYZ

class  { };

This is where C++ compiler complains. It has nothing to do with your file name.
Among C and C++ programmers, it is commonly admitted that header files should be protected by macros named after the file name including the extension:
#ifndef XYZ_H
#define XYZ_H

If you use this practice, you won't have this problem anymore.

That's what is inconsistent with my Arduino program and my other ones (Xcode/nano). I forgot to append the _H_ (or _H as you prefer).

source: Stack Exchange

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

sort: votes


text:
The Mysterious Case of the Mostly-Vegetable Servo
Story:
I was playing around with my Uno along with a servo.
To my stupidity (or more appropriately: ignorance), I set the voltage to my servo with analogWrite(), rather than servo.write(). It worked for a bit; but once it reached it's limit, it kept trying to move, to no avail.
Realizing what I had done, I pull the power source from my Uno.
Then, I went to change the code, and tested my servo once more.
The servo's casing is transparent (there is a sticker blocking the motor and circuit; but I can see 4 of the gears).
The bottom 2 gears are ticking ever so slightly (and the top 2 even less so), resulting in the propeller to move at most 5 degrees. At this threshold, none of the mentioned gears are ticking, but something is heard (probably a whirring gear not in sight).
At this point, I would've come to the conclusion that a tooth of the third gear had broken.
However, after I pull the power plug and put it back in, it spins (backwards) into it's initial position and begins the process mentioned above again.

Mystery:
Is my servo indeed broken?
What's not functioning correctly?
Can it easily be repaired?

Is my servo indeed broken?

Yes.

What's not functioning correctly?

As you said, some of the gears must have shifted in some way hindering the smooth mouvement of the servo or making it simply not working correctly.

Can it easily be repaired?

Well, it depends on you. Do you like repairing EXTREMELY small things? Are you skilled at that. I would say no, because it requires a lot of knowlage on the servo to be able to remove it, fix it, and not to forget, replace it into its original case. Simply buying a new one is quite cheaper and simpler.

@ Dat Hair Do----Rather than forgetting  it-  the OP could use the use the servo motor from it and make your own driver circuit for it they wanted to. They could also make a large new gearbox -if they wanted to. I dont think both of these things are difficult.

@DatHa -- I most likely won't fix it; I'm not willing to waste time (not saying that it's not useful; I'm just an ignorant teen who's got limited time to learn) learning how to fix tiny gears. However, I'll probably open it up and play around with it. Thanks for your diagnosis, though!

Very good idea. I also do that, before I throw anything to the garbage, I usualy open it to see how it works!!

P.S. check this out! https://www.youtube.com/watch?v=J8atdmEqZsc

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


text:
Why do I get a compiler error when I'm pretty sure I have such method?
Code
(I've omitted much of the code, and left just the outline and code probably relating to the error.)
SelfDrivingCar.ino
#include "JKMain.h"
void setup() { JKMain::setup(); }
void loop() { JKMain::loop(); }

JKMain.h
#include "JKMotors.h"
class JKMain
{
  static JKMotors motors;
public:
  static void setup();
  static void loop();
};

JKMain.cpp
#include "JKMain.h"
#include "JKPin.h"
const int leftMotorStraightSpeed = 100;
const int rightMotorStraightSpeed = 100;
const int leftMotorTurnSpeed = 150;
const int rightMotorTurnSpeed = 150;
const int turn90Time = 700;
void JKMain::loop() { }
void JKMain::setup()
{
  motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

JKMotors.h
class JKMotors
{
private:
  const int leftMotorSpeedPin;
  const int leftMotorDirectionBit1Pin;
  const int leftMotorDirectionBit2Pin;
  const int rightMotorSpeedPin;
  const int rightMotorDirectionBit1Pin;
  const int rightMotorDirectionBit2Pin;
  const int leftMotorStraightSpeed;
  const int rightMotorStraightSpeed;
  const int leftMotorTurnSpeed;
  const int rightMotorTurnSpeed;
  const int turn90Time;
  void setSideDirection(JKDirection _side, JKDirection _direction);
public:
  JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
    const int rmsp, const int rmdb1p, const int rmdb2p,
    const int lmss, const int rmss, const int lmts, const int rmts, const int t90t);
};

JKMotors.cpp
#include "JKMotors.h"
#include "Arduino.h"
JKMotors::JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
    const int rmsp, const int rmdb1p, const int rmdb2p,
    const int lmss, const int rmss, const int lmts, const int rmts, const int t90t):
      leftMotorSpeedPin(lmsp), leftMotorDirectionBit1Pin(lmdb1p), leftMotorDirectionBit2Pin(lmdb2p),
      rightMotorSpeedPin(rmsp), rightMotorDirectionBit1Pin(rmdb1p), rightMotorDirectionBit2Pin(rmdb2p),
      leftMotorStraightSpeed(lmss), rightMotorStraightSpeed(rmss), leftMotorTurnSpeed(lmts), rightMotorTurnSpeed(rmts), turn90Time(t90t)
{
  pinMode(leftMotorSpeedPin, OUTPUT);
  pinMode(leftMotorDirectionBit1Pin, OUTPUT);
  pinMode(leftMotorDirectionBit2Pin, OUTPUT);
  pinMode(rightMotorSpeedPin, OUTPUT);
  pinMode(rightMotorDirectionBit1Pin, OUTPUT);
  pinMode(rightMotorDirectionBit2Pin, OUTPUT);
}

JKPin.h
#include "Arduino.h"
struct JKPin
{
  // Ultrasonic
  static const int UltrasonicEcho = A4;
  static const int UltrasonicTrig = A5;

  // Servo
  static const int ServoSignal = 10;

  // Motor
  static const int LeftMotorSpeed = 5;
  static const int LeftMotorDirectionBit1 = 7;
  static const int LeftMotorDirectionBit2 = 6;
  static const int RightMotorSpeed = 3;
  static const int RightMotorDirectionBit1 = 8;
  static const int RightMotorDirectionBit2 = 9;
};

Notes
I wouldn't worry too much about the SelfDrivingCar.ino file. I had it "encapsulated" with JKMain.h. Also, don't concentrate on JKPins.h, as it is mostly "factual" information likely unrelated to the problem.

Error

sketch/JKMain.cpp: In static member function 'static void JKMain::setup()':
JKMain.cpp:19: error: no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'
       leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
exit status 1
no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'

Request
As far as I see, I do indeed have the constructor that the error claims I lack. What's wrong with my code?

Update
(reply to jantje)
I when removing static from motors, I receive a new error:
In file included from sketch/JKMain.cpp:1:0:

sketch/JKMain.h: In static member function 'static void JKMain::setup()':
JKMain.h:10: error: invalid use of member 'JKMain::motors' in static member function
JKMotors motors;
JKMain.cpp:16: error: from this location
motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
exit status 1
invalid use of member 'JKMain::motors' in static member function

In your question you have two of JKMain.h - is one of them supposed to be JKMain.cpp?

static JKMotors motors; why are you making a class when you appear to be planning to have a single instance of the class? A namespace might be more appropriate and less work.

By "the class", what are you referring to: JKMain or JKMotors?

I'm referring to JKMotors, since you are making a static variable motors. If you do it like that, you have to then also make a static instance of the variable at global scope.

The idea to embed both setup() and loop() with an OOP instance is good, but why not pushing the use of class JKMotors and class JKMain deeper by removing static variables and functions.
Step1 - use a JKMotors * in a non-static class JKMain:

The default constructor JKMain() is just used to initialize
  motors.

class JKMain
{
  JKMotors *motors;
public:
    JKMain() { motors = NULL; };
  void setup();
  void loop();
};

Step2 - create the motors instance in the void JKMain::setup() as proposed by @Mikael Patel

But now, the JKMotors *motors; is accessible from the non-static
  void JKMain::setup().

void JKMain::loop() { }
void JKMain::setup()
{
  motors = new JKMotors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

Step3 - declare a global JKMain instance and call setup/loop method from static setup/loop functions.

The JKMotors *motors; is now accessible from both JKMain::setup()
  and JKMain::loop()functions.

JKMain glbMain;

void setup() { glbMain.setup(); }
void loop() { glbMain.loop(); }

Nice work! That compiles OK.

I don't like static functions mixed with OOP. Enjoy C++ with your Arduino.

+1 -- Oooh. I like this way. I'll give it a checkmark once I implement it and make sure it works.

I think the problem is related to the fact motors is declared as a static member which makes it a global variable. This means the constructor can not be in the setup method.
I'm not 100% sure about the format but you need something like
#include "JKMain.h"
#include "JKPin.h"
const int leftMotorStraightSpeed = 100;
const int rightMotorStraightSpeed = 100;
const int leftMotorTurnSpeed = 150;
const int rightMotorTurnSpeed = 150;
const int turn90Time = 700;
  JKMain::motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
void JKMain::loop() { }
void JKMain::setup()
{

}

See update to my question for my reply.

void JKMain::setup()

{
  motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

You can't call a constructor like that. A constructor is either implicitly called, eg. if foo is a class:
foo bar;   // constructor for foo called

Or:
foo bar (1, 2, 3, 4);  // pass arguments to the constructor

Or even as some people do:
foo bar = foo (1, 2, 3, 4);

The last example creates a temporary instance of foo that is then copied into bar.
But what you can't do is this:
foo bar;   // make an instance of the class
bar (1, 2, 3, 4);  // call the constructor later

It's too late! The instance already exists. In your case motors is the instance of the class JKMotors. You can't call the constructor later on in the code. It doesn't make sense.

Ah, that's right. If I remember correctly, it is possible to do this if I implement operator=. Am I correct? If so, how would I implement it?

J. Piquard's answer compiles OK without needing to implement operator=. He calls new to create the instance of the class (deferred because it is now a pointer) and thus we don't need operator=.


text:
Arduino ADS1115 PGA settings
I am trying to use an external ADC with my UNO for very precise measurement of my signal.
The ADC which I am using is ADS1115.
http://henrysbench.capnfatz.com/henrys-bench/arduino-voltage-measurements/arduino-ads1115-module-getting-started-tutorial/
This is the site which I am referring to.It says the default reference voltage of the PGA gives a resolution of 188microvolt per bit.It also indicates towards changing the reference voltage to 2.048, to still increase the resolution per bit.
Can you please guide me in how to achieve this 2.048V.
Update:
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiFpq3P89vNAhXJro8KHa6IC04QFggpMAI&url=https%3A%2F%2Fcdn-learn.adafruit.com%2Fdownloads%2Fpdf%2Fadafruit-4-channel-adc-breakouts.pdf&usg=AFQjCNGhdMw47MRlXolMiMoHdsTwKMwMow
It seems that by adjusting the gain (page number 16-17 of 18) we can achive it.
WHat I need to know now, is where should I put that piece of code

ads1115.setgain(...)

in void loop() or in void setup()
Thanks
Anupam

Reference voltage inputs are usually high impedance requiring little current.  So you can get by with simple circuits like a resistor and zener diode.  Here is just one I happened across:

Do some research to find out more about this.
For your specific case, you should read the ADS1115 specification sheet.  As this ADC chip has it's own built in voltage reference.
In the Arduino paradigm, tasks that are to be executed once at the beginning of a program are placed in the setup() method.  Tasks which are to be executed repeatedly are placed in the loop() method.  As setting the gain of the ADC appears to only be done once (consult the ADS1115 PDF linked to above), it appears to fall into the former category.
Added later...
I changed the circuit diagram after I realized it was a bad example for creating an Analog to Digital Converter voltage reference.

setup() runs once at the beginning after the program is run.  However, loop() runs continuously after that.
The setgain() instruction is needed once at the beginning, so it should be in setup() function.
good luck!


text:
arduino + GSM/GPRS SIM 900A cannot able to read a message
Here I am using Arduino uno and GSM sim900A, I want to read sms from sim900A. But i am trying to read message, it is showing the empty values. I tried different methods, but no use. Here I have added my script. Please help me.
#include <avr wdt.h="">
String phoneSMS = "+91xxxxxxxxxx";
String messageTxt;
void setup()
{
Serial.begin(9600);
delay(60000);
srl_msg();
}
String srl_msg()
{
Serial.println("AT+CMGF=1\r");
delay(1000);
Serial.println("AT+CNMI=2,2,0,0,0");
delay(1000);
Serial.println("AT+CMGL=\"ALL\"\r"); // to read ALL the SMS in text mode
delay(1000);
char txtmsg2[100]; // AT command output
String date = readSerial(txtmsg2);
String value = date.substring(1, 50);
messageTxt = "Internal - Heart Beat;";
messageTxt.concat(value);
Serial.println(value);
SendSMS(messageTxt);
}
void loop()
{
}
void SendSMS(String message)
{
Serial.print("at+cmgf=1\r");
delay(1000);
Serial.print("at+cmgs=\"");
Serial.print(phoneSMS);
Serial.println("\"");
delay(1000);
Serial.println(message);
delay(1000);
Serial.print((char)26);
delay(15000); // AAN
}
String readSerial(char result[])
{
int i = 0;
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar != '\r')
{
result[i] = inChar;
i++;
}
}
return result;
}

output is look like this:
AT+CMGF=1
OK
AT+CNMI=2,2,0,0,0
OK
AT+CMGL="ALL"
OK

Check you sim card inbox. I also had the same problem, and it turns out the sim card sms inbox capacity is full.
You can also try to use another library, here is one of them

wdt.h is just time handling data library, and have no methods for send or receive sms...
Your method: SendSMS(String message)
is just printing serial labels and counting a char that you are putting in the serial monitor.
Try this GSM example...


text:
I have four servos connected to an arduiono uno and I cannot control them
I am making a simple bipedal robot. I have four 9g servos connected to my uno. Whenever I try to even do the simplest command, like move right foot 45 degrees it does not work properly. I have tried on my second Uno and i have the same result.
My program for testing the servos:
#include <Servo.h>

Servo myservo;

void setup(){
myservo.attach(6);
}

void loop(){
 myservo.write(45);
}

Each servo wire is attached to a breadboard where they all share power and ground from the arduino. Each servo wire then has another wire going to pins 3,5,6 and 9.
Does anyone know what the problem is and what I can do? Thanks

Maybe it's your wiring. Maybe it's the servos. Maybe four servos are too many for a single Uno to power. Please show your schematic.

Powering one micro-servo through the +5V pin of the Uno should be OK, and I would expect the program you posted to work. Powering four of them may be too much, especially if they are somewhat loaded.

Please let us know how the +V and 0V connections to the servos are made. Ideally they should be connected to an external battery or something similar.

An Arduino is not capable of powering four servos. Power them externally, but make sure the ground of the Arduino and servos is connected.

This has done nothing. Also I believe an arduino can power four servos but I tested it anyway.

Could you share your current setup of the servos and the Arduino?

Have you even tried powering the servos externally?

I don't think this answer should have been marked down - the arduino's regulator really isn't suitable for directly supplying power to that many servos as Len has said, partly due to electrical noise etc.

@Len yes I have tried powering the servos externally

With the grounds of the servos and Arduino connected? Because then I really don't know why it wouldn't work, unless your Arduino is already fried or something.

Keep in mind that you may also be limited by the USB power supply.  By definition that power source can cut you off at 500mA.  Also, servo current demand is hard to figure out.  As others have pointed out, you should be able to control 1 "unloaded-small" servo using the Arduino Uno's on board linear 5 volt regulator.  However, from your picture, you are only using the USB port.  This mean that you are not using the internal 5 volt regulator and that you are relying directly on what ever your are plugged into to provide 5 volts.  continued in next comment...

... So, given you have swapped around Arduino Uno boards and servos (you have swapped around servos, right?),  you should now swap out the USB power source.  Note: According to this schematic, there is a 500mA fuse in line with the USB 5 volt power line on the Arduino Uno.  So be careful not to exceed this.

I strongly advise against using the Arduino Uno to power your servos. The maximum current of the VCC and GND pins is 200 mA according to their official documentation. You can go over a bit, but 500 mA? That's just asking for a failure in your Arduino device.
Power the servos from an external power source, connect the grounds of the servos and the Arduino and you're good to go.

OK thanks everyone but I am still unsure how to properly power the servos externally, could you explain how. Secondly what power should I supply? 9v?

Depends on your servo. Mostly it's 4.8V, but sometimes 6 or 12. Too much volts also fries the servos, so you need a voltage regulator or a 5V external power source (like a phone charger).
Then you just split the VCC to the VIN of the Arduino and the servos. Then you connect all the grounds. That's basically all. But make sure you have the right voltage for your servos, you can find this information in the datasheet.

@Len: The 200 mA you are quoting is the absolute maximum for the Vcc and GND pins of the ATmega328P. It is not a limit of the Arduino. The current you source from the Arduino's +5V does not go through the ATmega's Vcc pin, thus that limit is irrelevant.

You're completely right. I didn't even know that. A quick search shows that the max values are between 500mA and 1A. So, it might actually be possible to power multiple servos, albeit it's still a risk.

As others have said, the Arduino cannot drive 4 servos - my experience is that it can have problems powering one if you try to move it too often due to the voltage drop caused by the high current consumption.  When you move a servo the power consumption rises considerably.  A large (220uF or more) capacitor near he servo can help, but even so, by far the best option is to supply the servos from a separate supply.
If the Uno resets when you try to move the servos (especially multiple times per second) then the power supply is most likely your culprit.


text:
Receive sms on android phone without GSM module
I have done a simple project which measures CO gas in air.Now I want that sensor will measure the level of CO gas and sms will be received on android phone when the area is under danger zone.How to receive sms on android phone without GSM module?

You can do it with the power of prayer, or wishful thinking, or some kind of module. Take your pick.

There are exactly two ways of sending an SMS. Both of which require more than "just" an Arduino.

Directly using GSM - for which you NEED a GSM shield
Indirectly using an Internet Gateway - for which you NEED some form of internet connection.

Since you have an aversion to 1, 2 is your only option. So you require some extra hardware (unless you have an Arduino with built in WiFi or Ethernet) to connect your Arduino to the internet. Then you have to pay an SMS gateway provider to allow you to send SMS messages through them, and implement their API in the Arduino.
Also you need an internet connection available wherever the Arduino happens to be.
All in all a lot of work and you're really no better off than using a GSM shield.

He might not have GSM reception at the location of measurment. (Basement maybe)? But in order to send SMS message you will have to use GSM network sooner or later. From price perspective I would have to agree that WiFi shield will cost you back the same amount of money as GSM shield.

Alternative from price perspective:
Assuming that you have internet at the location of sensor (WiFi or cable) you can buy a RaspberryPi (revision 3 has already integrated WiFi and bluetooth). Using python code you can than send SMS message using some free SMS service provider if there are any in your country using their API.
If SMS notificaion is not critical, you can use RaspberryPi to send an email or some other sort of notification. Heck you can even create a Twitter profile for your sensor and call it Mr.Sensor and then post tweets with sensor values. Possibilities are endless, it all depends on your use case and available infrastructure.
I hope you will find something that will satisfy your needs :)


text:
Bizarre transistor behavior and voltage with DC motor in simple circuit
I started a new motor related project recently with a new Arduino Uno, beginning with several tutorial circuits included in the Vilros Arduino guide. The circuit in question is #10, a simple DC motor circuit with a transistor switch (https://i.sstatic.net/KLC0K.jpg). The Arduino is being powered for the moment via USB.
The circuit, completed according to the diagram/common sense, does not work. The voltage across the transistor base is clearly not sufficient to activate the switch with the motor in the circuit. 5V (more like 4.6V) from Pin 13 is running across a 330 ohm resistor to the transistor base, but there is no current between the collector and the base. Bypassing the collector/base gap with a piece of metal will complete the circuit and activate the motor.
For some reason, the transistor will switch properly when the motor is replaced by a simple LED. AND, switching the cable from Pin 13 to the +5V out is enough to activate the transistor switch. I was under the impression that the transistor should only require .7V above the common grounded element.
But, even more bizarrely, with a cable running from +5V to the transistor base (through a resistor), a voltmeter across the DC motor is reading a potential difference of anywhere from 9V to 1702V (see https://i.sstatic.net/mwFKp.jpg, yes, with 4 digits). The multimeter is otherwise working normally, so I don't see a good explanation. Is the Arduino pin just incapable of providing sufficient current/voltage to activate the transistor, or am I missing something obvious. And does anyone have some idea why the voltmeter is reading so high and fluctuating so wildly? It is curious that the Arduino disconnects from the PC whenever the circuit is completed with the motor in it, so the Arduino likely is overdrawing from the USB.
The transistor included was not the one listed, but a common MPS2222A.
Thanks

There is nothing wrong with the circuit (although drawn in a bizarre method). Your understanding of how a transistor works is mistaken - forget voltage - transistors are controlled by current.
Most likely you have connected the transistor incorrectly.
The voltage reading is due to back EMF. If you used an analog meter it would give the reading you expect.
In all likelihood you have damaged the transistor.

Thank you. I have some background in physics, but none at all in circuit/semiconductor theory, although I'm learning. The voltage reading makes sense. A damaged transistor does seem likely, although I've replaced the transistor twice with an identical one to no avail. Curiously, the transistor works properly if I wire the transistor base to the 5V out instead of an Arduino pin. Is it possible that the pins can't provide sufficient current across the (possibly damaged) transistor while the 5V out can? Thanks again.

@JacobAustin The Arduino can supply 20mA, but with a 330Ω should put 15mA into the base (you can measure this by putting the meter in series on a mA range). This should be more than sufficient to saturate the transistor and be able to switch its 600mA current. If it isn't turning it on you have a wiring error (most likely reversed C E) or damage. The transistor does seem to be reversed in the image.

Okay. Thanks again. Curiously, I was able to attach a 9V battery to the Arduino and everything worked fine. It's possible that I damaged the USB by drawing too much current, and that was limiting the current supplied by the Arduino across the transistor.

According to second image transistor seems to be connected in oposite direction (switched Collector with Emitter). It means common collector configuration is used instead common emitter and it's usually not enough to drive motor. And C-E can handle only about 10V Max (more or less, depends on transistor) even if it could handle much more in oposite direction.
See link for more details:

Common Base Configuration   –   has Voltage Gain but no Current Gain.
Common Emitter Configuration   –   has both Current and Voltage Gain.
Common Collector Configuration   –   has Current Gain but no Voltage Gain.

I've just tested this circuit an it must be powered by power jack. USB is not strong enough.

The transistor that came with the diagram was itself reversed. Emitter-base-collector, instead of collector-base-emitter. I have also tried reversing the transistor to no avail.

@JacobAustin that's true for 2N2222 and PN2222 but for P2N2222 is schematic correct. SparkFun Inventors Kit contains P2N2222.

The kit contained the wrong transistor. It was an MPS2222A transistor. However, attaching a 9V battery seems to have solved my problem. Probably an issue with current draw from the board.


text:
Can I make so when I press a button on my Arduino Uno board, it will press a key on my computer?
I looked up the question before, but they only gave answers for boards that are not the Uno. Is there any way to make it so when I press a button on my board, it registers as a key press on my computer? I'm trying to make a flight controller for PC sims.
Thanks!

We already have a question on this very topic, we really don't need to cover it again.

Not without extra software on your computer side.
However if you use Arduino Micro, you can emulate keyboard and/or mouse directly.

Or you could change the firmware on the ATMega16u2 on the UNO. But that isn't for the faint of heart.

Yes, it came to my mind too, but FT232 or CH340 can be used in some cases (mainly if it's clone)

You'll need something on the Arduino that sends an event to your PC whenever the button is pressed. The easiest version of this would be the Serial channel over USB.
Second, you'll need a program running on your PC that receives that Serial message and generates your desired keyboard and mouse events.
In Windows, you can generate system wide keyboard and mouse events fairly easily using the Windows API. This would allow you to click a mouse, or keyboard button when inside of most programs written in Windows. https://msdn.microsoft.com/en-us/library/ms171548(v=vs.110).aspx
That said, you can have problems sending spoofed events to video games that don't use standard Windows forms. You might find this answer helpful from StackOverflow - https://stackoverflow.com/questions/7320424/c-win32-simulate-keypress-with-directinput

EDIT: check @JohnBurger 's comment. THIS is NOT good for the UNO.
You can connect your Arduino as a keyboard to the computer. There is a Keyboard Arduino library you can use. Here is a reference:
KeyboardWrite
For example this line of code will react just like you pressed A on your keyboard:
Keyboard.write(65);

Note the first line of the parent Keyboard [https://www.arduino.cc/en/Reference/MouseKeyboard] reference page: "These core libraries allow a 32u4 based boards or Due and Zero board to appear as a native Mouse and/or Keyboard to a connected computer" - in other words, not the Uno that the questioner was asking about.

@JohnBurger sorry, you are right! my mistake....

You can do USB HID device on any AVR or Arduino chip without USB hardware interface by bitbanging on any 2 DIO:
https://www.obdev.at/products/vusb/index.html
Supports 4 endpoints (like 2 mouse and 2 keyboard, if makes sense :). Sure no additional software or driver is needed on OS side (default drivers shall be ok if correct VID/PID specified).
EDIT:
Seems 2 endpoints are required for USB HID keyboard. If remaining 2 is enough for USB HID joystick, it could be useful for flight sim.


text:
SOLVED: Soft Power On SIM900 module - JP pads missing!
I have this SIM900 board and working just fine.
But i can't find a way to soft power on this board from arduino.
I read for JP pads. They need soldering first, but from my board this JP pads missing.
Know someone other way to soft power on this from arduino?

Dielatin... Winner, Winner, Chicken Dinner!! Works a treat, been trying to figure this one out for sometime and there is nothing on the web about it!! So thanks for the solution upload!!

OK for anyone who has the same problem. I solved this by soldering a cable on the underside of the board on this pin (see image) on power button. Then I connect the cable to pin 9 on Arduino and run this on sketch:
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  pinMode(9, INPUT);

I don't know how it works, but it solves my problem.

Near C6 and J15 you have 2 points.  You need to solder it.
Before soldering yon can hold wire on one of it (down pin , during code execution).


text:
Program jumps alone from void loop() to another void
//simple alarm system
int RipSensor1 = 12;
int RmkeyA = 3;
int RmkeyB = 5;
int RmkeyC = 6;
//--------------------------------------------------------------------------

void setup()
 {
  Serial.begin(9600);
  pinMode(RipSensor1,INPUT);
  pinMode(RmkeyA,INPUT);
  pinMode(RmkeyB,INPUT);
  pinMode(RmkeyC,INPUT);
  pinMode(13,OUTPUT);
  Serial.println(F("System Is Up & Running")); }
  //----------------------------------------------------------------------

void loop()
 {
  Serial.println(F("Main Loop Start"));
  digitalWrite(13,LOW);   //for debugging
  if (digitalRead(RmkeyA) == HIGH)
   {
    Rip1Status();
   }
 }
//----------------------------------------------------------------------

void AlarmSMS1()
 {
  //send sms to admin1
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Rip1Status();   // return to this void (monitoring)
 }
//----------------------------------------------------------------------

void Rip1Status()
 {
  Serial.println(F("VOID Rip1 Start..."));
  while (digitalRead(RmkeyB) == LOW) //Arm mode
   {
    digitalWrite(13,HIGH);
    if (digitalRead(RipSensor1) == HIGH) //when Rip sensor sense motion
     {
      Serial.println(F("Movement ALARM --> PowerUP Relay 1 & 2"));
      long RipTimer1 = 0;
      long Rip01 = 0;
      int z = 0;
      int x = 0;
      while (digitalRead(RmkeyC) == LOW)
       {
        RipTimer1++;
        Serial.println(RipTimer1);   //for debugging
        if((z==0) && (RipTimer1 - Rip01 > 500))   //1st CheckPoint do something
         {
          z = 1;
          Serial.println(F("1st CheckPoint OK"));
         }
        else if((x==0) && (RipTimer1 - Rip01 > 3000))   //2nd CheckPoint go on other void
         {
          x = 1;
          AlarmSMS1();
         }
       }
      Serial.println(F("C Key Pressed --> False Alarm"));    //if button C pressed
      RipTimer1 = 0;
      z = 0;
      x = 0;
      Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
      break;
     }
    else Serial.println(F("Monitoring"));  //for debugging
   }
  Serial.println(F("B Key Pressed --> Disarming"));  //for debugging
  Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
  loop();
 }

I make this code & i have this problem:
Program start & wait for A key pressed to Arm mode. works ok
Press A key go to Arm mode (monitoring). works ok
When its on "monitoring", if i press B key, system disarming then go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, then alarm start and if i press C key then disarming as false alarm and go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, if i left alarm to complete, go to sms void send sms to admin and return to Rip void (monitoring).
But on this point if i press B button to disarm system this happen...
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
B Key Pressed --> Disarming
Monitoring Loop ends --> GoTo Main Loop
Main Loop Start
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012.............

Why this happen?
What i am doing wrong?

It's called a function not a void.

loop() calls Rip1Status(), which calls loop(), which calls Rip1Status(), which calls loop(), which calls ....
That process will continue until the stack overflows (runs out of memory) or over-writes some necessary variable. If you just meant for Rip1Status() to return to the main loop, delete the loop() call at the end of the function. When Rip1Status()exits, control will automatically return toloop()at the statement following theRip1Status()` call.

JRobert. Same thing happen.

Same thing happen with you suggestion. RipTimer1 still count and program not stay on main loop. I try to redirect on other dummy void or break command but same think happen. Something big i missing here

JRobert thank you. After i read what you say many times finally i found the way. I have split Rip1Status() function in two. i have remove call function at the end of AlarmSMS1() and add return command on my code. Now works just fine. Thanks again....


text:
7-segment display code
What is the meaning of BitSet = bitRead(numeral[number], segment);?
const byte numeral[10] = {
  //ABCDEFG /dp
  B11111100,  // 0
  B01100000,  // 1
  B11011010,  // 2
  B11110010,  // 3
  B01100110,  // 4
  B10110110,  // 5
  B00111110,  // 6
  B11100000,  // 7
  B11111110,  // 8
  B11100110,  // 9
};

// pins for decimal point and each segment
//                          dp,G,F,E,D,C,B,A
const int segmentPins[8] = { 5,9,8,7,6,4,3,2};

void setup()
{
  for(int i=0; i < 8; i++)
  {
    pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
  }
}

void loop()
{
  for(int i=0; i <= 10; i++)
  {
    showDigit(i);
    delay(1000);
  }
  // the last value if i is 10 and this will turn the display off
  delay(2000);  // pause two seconds with the display off
}

// Displays a number from 0 through 9 on a 7-segment display
// any value not within the range of 0-9 turns the display off
void showDigit( int number)
{
  boolean isBitSet;

  for(int segment = 1; segment < 8; segment++)
  {
    if( number < 0 || number > 9){
      isBitSet = 0;   // turn off all segments
    }
    else{
      // isBitSet will be true if given bit is 1
      isBitSet = bitRead(numeral[number], segment);
    }
    isBitSet = ! isBitSet; // remove this line if common cathode display
    digitalWrite( segmentPins[segment], isBitSet);
  }
}

Do you now about chips like the Max7219?  It will help you handle a number of 7 segment displays (up to 8).

bitRead(x, y) takes a value x, and looks at bit number y.
So, if:

y is the number 2;
x is 53 (binary number 0 0 1 1 0 1 0 1)

                                       ^

it looks at bit #2. Bits are counted from the right starting at 0 - I have indicated the bit in question above.
So, bitRead(53, 2) would return 1, since bit #2 in 53 is a 1.
In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit 8 has all seven of its LEDs lit up, so you'd expect the encoding for 8 to have lots of binary 1s in it - and sure enough, it does (B11111110)! And the digit 7 has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, B11100000.
The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...


text:
How can I define a port extender MCP23s17 pin in Arduino
My task is to use a port extender (MCP23s17) to drive a touch keypad for which I have to define names of pins so that I can call those names in arguments of a function.
I have searched for different methods to define "PORT EXTENDER" pin but could not find any satisfactory results. Kindly help me handle the situation.
i have used the following libraries downloaded from Arduino playground
1. CapacitiveSensor.h
2. MCP23S17.h
Now I have to use MCP23S17 Pin in the following function
#define key1 2
#define key2 4
CapacitiveSensor cs_4_2=Capacitivesensor(key2,key1);  //capacitive sensor is connected to pin 4 and 2

key1 and key2 are Arduino's pins. I want some method by which I can refer key1 and key2 to the port extender's (MSP23S17) pin. The above answers are surely helpful but they doesn't fulfill my requirement.
Thanks in Advance
Sorry for English.

It all depends which library you are using.

It is not clear what your question is about. It makes me wonder if this is a school assignment which you did not understand or you just simply don't know how to describe your problem. In any case, you have to provide more details: wiring, code you have written so far... In particular the sentence "I have to define names of pins so that I can call those names in arguments of a function" is not clear; maybe you could give the prototype of the function as you imagine it, that would give us food for thought.

i have to use multiple touch keypads with arduino via a port extender. I have managed to operate both the sensors and the port extender individually but when i came to combine them i faced a problem that when i call the library of touch keypads, i have to pass them the pin numbers on which they are connected. in my case i have connected them with port extender via SPI. i am confused how to refer port extender pin number because if i simply type a pin number, arduino will refer to its own pins.

You may have to edit the touch keypad library's code or write your own to use the port expander's pins instead of the Arduino's own pins.

If you are using my library you can do something like:
MCP23S17 expander1(&SPI, 10);

#define LED_PIN expander1, 15

void setPin(MCP23S17 &expander, int pin, bool level) {
    expander.digitalWrite(pin, level);
}

// ... later ...

setPin(LED_PIN, HIGH);

If you use this arduino library:
#define LED_PIN 15

mcp.pinMode(LED_PIN, LOW); //set led pin on the MCP23S17 to an OUTPUT

mcp.digitalWrite(LED_PIN, LOW)

There is also the Adafruit Library, all do similar things, just in a slightly different way. I use this one, it just depends on which method you are most comfortable with and what your requirements are. Try them all and find out.
void setup() {
  Serial.begin(9600);  // debugging
  mcp.begin();      // use default address 0

      for(int i = 0; i < 6; i++) {
        mcp.pinMode(trafficLights1[i], OUTPUT);
      }
       for(int i = 0; i < 6; i++) {
        mcp.pinMode(trafficLights2[i], OUTPUT);
       }
        for(int i = 0; i < 5; i++) {
        mcp.pinMode(trafficLights3[i], OUTPUT);
        }
  for (int P=0;P<16;P++) {
    mcp.pullUp(P, HIGH);  // turn on a 100K pullup internally
    mcp.digitalWrite(P,LOW);
 }
      mcp.digitalWrite(11, HIGH);
}

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


text:
max7219 chained display showing mirrored text
I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code with the one that can be found online at arduino code and changed the display with the chained one, the text appears to be mirrored on the matrix display.
.
Below, I'll attach part of the code. Please help me find the problem.
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// Define the number of devices we have in the chain and the hardware interface

#define MAX_DEVICES 4
#define CLK_PIN     13
#define DATA_PIN    11
#define CS_PIN      10

// Hardware SPI connection
MD_Parola P = MD_Parola(CS_PIN, MAX_DEVICES);
// Arbitrary output pins
// MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

void setup(void)
{
  P.begin();
  P.displayText("Hello", PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
}

void loop(void)
{
  P.displayAnimate();
}

Changing the incorrect line to #define HARDWARE_TYPE MD_MAX72XX::FC16_HW
did the trick. It took time to find, but thanks a million!!!

In my case I had to change to #define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW

Since version 3.0 MD_MAX72xx.h no longer supports that definition. Now the hardware type is defined as a parameter on creation (in the "Example" file you are using - not in MD_MAX72xx.h)
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
...
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

Note that I've changed the hardware type from PAROLA_HW to FC_16.

Check the configuration in MD_MAX72xx.h file and ensure you have the right module selected.
For example there is a define
#define USE_PAROLA_HW   0

if your hardware is this item then turn off the other hardware settings and turn this one on so it reads as follows:
#define USE_PAROLA_HW   1

there many other settings if it is not there then you will have to experiment until you find the correct one.

In library, change #define USE_GENERIC_HW 0  to #define USE_GENERIC_HW 1 is the solution.

In latest version of #include <MD_Parola.h>, #include <MD_MAX72xx.h> you have to define the following and characters will display correctly.
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW

Isn't that what @Den1al said in their answer?

authors: عازفة الإحساس


text:
How to use correctly a microstepping driver with a lower voltage stepper motor
I want to use a microstepping driver like Haitronic's HS2215 with a NEMA 17 stepper motor with rated voltage of 4.2V and rated current 1.5A.
The input voltage range of the microstepping driver is 9-40VDC.
From what I understand,  I can use the switches to set the maximum current. In this particular case I would use SW4=On, SW5=On, SW6=Off.

TB6600 current settings
You can adjust the current that goes to the motor when it is running by setting the dip switches S4, S5, and S6 on or off.

I've found this Maker's Guide which describes the settings for use with an arduino.
However, I am not certain what voltage (VCC) should I supply to the mircrostepping driver? Should I provide, the minimum of 9VDC, should I provide less? Is this irrelevant?

Look at https://electronics.stackexchange.com/questions/200324/how-to-interpret-the-stepper-motor-voltage-requirement . My guess it that the stepper driver itself requires at least 9V to run, so it wouldn't even work (properly) with only 4.2V. PS I'd probably go with a bit lower current setting, as to not push the motor to it's max. Unless you really need the torque.

what does this do? SW4=On, SW5=On, SW6=Off

I think it set the maximum current to 1.5A and peak 1.7A, based on what I see on the label on the product.

if the driver has current limiting, then the driver should automatically limit the output voltage, to keep the output current below a set threshold ... if the difference between the supply voltage and the output voltage is large, then the driver may generate extra heat, depending on design

That doesn't matter at all.
The voltage stepper motors are rated for is the voltage that, if applied to the motor coils, would create its rated current.
Stepper motor drivers monitor the current, and always use the full voltage available to them (9 - 40V in your case) to drive the stepper motor - using PWM.
The stepper motors coils inductance slows down the change in current, allowing the driver to reach its set current.
Higher drive voltages simply mean that it's easier to overcome that inductance, allowing for faster stepper motor movements.
You'll want to set your driver at 1.0 or 1.5 A, and supply it with as much voltage (up to the rated 40 V) as you can.

So, if I read your answer correctly, in stepper motor drivers (like the one I'm posting) the VCC voltage has to do with required voltage for the driver, and not the motor?

Yes, basically. Only the rated current matters if you're using a stepper motor driver.

Do most modern stepper drivers work in this fashion (I mean using PWM to control the current)? In most datasheets I can't say I've found that information... I mean the L298 which is an older driver, did not seem  to use this approach.

They do, and it's usually somewhere at the top of the data sheets (e.g. A4988, DRV8825, TMC2209). The L298 is technically not a stepper driver - if you used that, yes, you should definitely not supply it with 40V, but only the rated voltage of the stepper motor - unless you manage current and PWM yourself on the MCU driving the L298.
If it's called an "integrated" or "complete" stepper motor driver, it'll use PWM to drive the coils and regulate the current.
Note: When stopped on a full step, you could measure the "rated" voltage across the coils too - it's just created via PWM from Vcc.

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


text:
Cannot ping ESP8266's IP address from a computer on the same network
I have an ESP8266 module connected to my Arduino Mega 2560. I sketched a simple code to pass whatever command I typed from the Serial Monitor to ESP8266 and vice versa:
void setup() {
  Serial.begin(115200);
  Serial2.begin(115200);
}

void loop() {
  if (Serial.available())
  {
    Serial2.write(Serial.read());
  }

  if (Serial2.available())
  {
    Serial.write(Serial2.read());
  }
}

So from here on I just type my AT commands inside Serial Monitor and receive the output also inside Serial Monitor. Managed to connect into a wifi network using the command:
AT+CWJAP="SSID","password"

And obtain my ESP8266 module's IP address using the command:
AT+CIFSR

+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"5e:cf:7f:c2:ce:30"
+CIFSR:STAIP,"192.168.1.103"
+CIFSR:STAMAC,"5c:cf:7f:c2:ce:30"

OK

Problem is, whenever I run CMD and "ping 192.168.4.1" or "ping 192.168.1.103" from my PC which is connected to the same network, I will get "request timed out". Pinging my own PC's IP gets me a reply. What is wrong here? Totally clueless... :-/
EDIT My PC's IP address is 192.168.56.1

And are those IP addresses actually on the same subnet as your computer?

What is your computers IP address.  You will not be able to ping one of the addresses unless you have set the subnet mast to 16(ish) bits (255.255.0.0)

The IP address 192.168.4.1 is the default IP address used by the ESP8266 when it is running as an access point. You can ignore that, it doesn't actually exist.
You need to make sure that you are actually connected to the access point by issuing AT+CWJAP? which should respond with the access point name an OK if it is connected.
Secondly you need to make sure that you are on the same network segment as your ESP8266 - that is, the same subnet.  If your computer isn't on an address in the range 192.168.1.1 to 192.168.1.254, and your subnet mask is set to (what is usually the default) 255.255.255.0, then you won't be able to communicate unless there is an appropriate route between the subnets.
Also some wireless routers impose client separation on the WiFi channel, which means that WiFi devices cannot talk to each other, and LAN devices cannot talk to the WiFi devices. This is usually something that can be disabled in the router's configuration.

First, you need to confirm that your PC's wireless connection is on the same IP subnet as the ESP8266. At the CMD prompt, type:
ipconfig /a

and look for the wireless adapter. Hopefully the IP address will start with 192.168.1.... It should but there's no harm in checking!
Second, check that your WiFi router hasn't disabled pinging between its clients - some do (mine did, until I threw it out...). Do you have a smartphone or other WiFi device? If so, find out its IP address (hopefully also 192.168.1....) and confirm that you can ping it.
Pinging your own address isn't very useful. Normally it detects the fact that it's its own address, and replies with no attempt at sending over the air.


text:
How to control MKR1000 from outside your local network
I want to send an HTTP command to MKR1000 from outside my local network.
So far, all the googled resources point to getting the local IP (example 192.168.0.10) of MKR1000 and sending a command like http://192.168.0.10/H to it and then parse it.
How do I send a command to MKR1000 from outside its local network?
I should clarify that I want this to be a consumer product and can't have the end-user fiddling with their routers for port forwarding etc.

Google "port forwarding" along with the make and model of your router.

I want it to be a consumer product and don't want every end user to be fiddling with their router. Edited my question accordingly.

Well you can't. Simple fact: devices on an internal network, regardless of how you may wish it, are not accessible from outside. Only the user can configure their router to forward access to it.

But a lot of consumer IOT products (e.g. NEST) are controlled from your mobile device from anywhere?

No they aren't. An external service is controlled from your device, and the IoT device queries that same external service.

What you really want is something like MQTT

I see, so I need a server. Mobile device writes to server and MKR1000 keeps querying the server to get commands? I think Firebase will work nicely BUT this continuous query on MKR1000 side will be battery and data consuming.

Depends how "continuous" you really need.

The only way I can think of to achieve this would be to port forward your router, and forward port 80 (http) to your MKR1000. You can check out https://portforward.com/ for instructions on that.
If you don't want to port-forward, you'd have to have the MKR1000 connect to a centralized IOT server somewhere, and have the user go through the server to access the MKR1000. That's how other iot devices such as nest cameras do it.

You now can try this UPnP_Generic library to do the auto-portforwarding for you without manually touching the router.

Many of us are manually port-forwarding in Internet Gateway Device (IGD, Router) in order to provide access to local Web Services from the Internet.
This library provides the easier way to automatically port-forward by using the Simple Service Discovery Protocol (SSDP), running on nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, ESP8266/ESP32, using ESP WiFi, WiFiNINA, Ethernet W5x00, ESP8266/ESP32 AT-command WiFi supporting UDP Multicast.
The SSDP provides a mechanism whereby network clients, with little or no static configuration, can discover network services. SSDP accomplishes this by providing for multicast discovery support as well as server based notification and discovery routing.
The SSDP is used for advertisement and discovery of network services and presence information. It accomplishes the task without assistance of server-based configuration mechanisms, such as Dynamic Host Configuration Protocol (DHCP) or Domain Name System (DNS), and without special static configuration of a network host. SSDP is the basis of the discovery protocol of Universal Plug and Play (UPnP) and is intended for use in residential or small office environments.
This UPnP_Generic library is created to automatically update your IGDs with the requested port-forward information, using one of the many available boards / shields. See Currently Supported Boards.
The time between checks to update the UPnP Port Mappings is configurable to match your use case, and is set in the examples at 10 minutes. The LEASE_DURATION is also configurable and default to 10hrs (36000s). The Virtual Server Name can also be specified in the sketch and is shown in the IGD, e.g. NRF52-W5X00 or ESP8266-WIFI as in the following picture:

The UPnP_Generic code is very short, can be immersed in your Projects and to be called in the loop() code.


text:
From Wiring to pure C
I'm using the Teensy 2.0 (atmega32u4) and decided to switch from Arduino IDE with Wiring to pure C. I think it's much more useful to master programming microcontrollers on that level. Wiring seems to be quite limited at some point.
It was really easy to use some basic libraries such as avr/io, or util/delay and write simple programs like "arduino hello world".
My problem comes with more complex tasks such as acting as usb mouse. On http://pjrc.com are references just to use with arduino ide/wiring. I couldn't find anything useful on google. Is there any good reference for pure C programming tennsy/arduino and/or using libraries such as "usb_mouse.h" (from pjrc.com) with pure C?

EDIT 1
Let me add some details (based of @st2000 answer).. Yes, Tennsy (and Arduino) are microcontrollers, not microprocessors. Programming avr chips in pure C doesn't require so much work as programming microprocessors. This is the simplest avr C program I could come with (typical blinky):
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
        (CLKPR = 0x80, CLKPR = 0x00);
        DDRD |= (1<<6);
        PORTD &= ~(1<<6);

        int sviti = 0;

        while (1) {
                if (sviti)
                        PORTD |= (1<<6);
                else
                        PORTD &= ~(1<<6);
                sviti ^= 1;
                _delay_ms(40000);
        }
}

As you can see (@st2000), there are no dozens of setting up registers. It does not require any expensive equipment to upload resultant .HEX file - for teensy the only thing you need is a USB cable.
If you want a concrete example, I want to use this library with pure C, but it's obviously meant for wiring and arduino IDE primary. So how to use this library with pure C? And back to my main question, how to generally use libraries of this kind with pure C avr programming?

Datasheets? Atmel application notes? Anyway, USB programming is not an easy task - which is why people use libraries.

You can use pure C with libraries. Just search "atmega32u4 HID Mouse" that should pop up some githubs/forums/resources/blogs.

Please try make your question more specific. Are you actually after a library so that your Teensy behaves like a mouse? What do you plan to do with it? That will help the community determine what answers to give. http://arduino.stackexchange.com/tour

If you want to do USB on an AVR with USB hardware capability outside of the Arduino realm, you might look at LUFA.

The library you are referring to is meant to work in plain C. It does not depend on any Arduino libraries, nor does it require C++. Look at the provided example to see how to use it. To compile the example, just type make at the command line. With one caveat: all PROGMEM arrays should be made const in order to be compatible with recent releases of gcc. You can of course tune the Makefile to your taste.

Oh my god.. You're right, I am sorry. Sometimes I can't believe how dumb I am...

If even Majenko scoffs at the notion of doing it in C....

And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.
nothing magic about going in "pure c".

Refer to the actual processors used on the platforms to find reference material for ordinary C or C++ programming.  There are different processors used on various Arduino boards.  Be aware that this approach normally requires programming hardware which range from a few dollars to hundreds of dollars.  Also be aware that "bare metal programming" requires the programmer to setup the processor's resources of interest.  This normally involves setting dozens (as in the Arduino Uno AVR processors) if not thousands (as in Arduino Zero's ARM processors) of registers which can deal with everything from the processor's clock to interrupt vectors.
USB programming is very complex.  Consider the complete description of RS232 could be contained in a white paper.  The equivalent for USB would be at least a book.  To simplify your efforts, we can eliminate all USB Host features as a mouse is a peripheral or USB Device.  Further, you will probably want to limit your USB Device to a USB HID or Human Interface Device.  This allows most OSs to easily recognize and use the mouse as the HID definition is more complete / restrictive. Also note, embedded processors which happen to have a USB port usually only support USB Devices as USB Host requires additional features & resources.  Now that the scope of USB support has been narrowed, you can start searching through the different processor's libraries for what you need to create a USB HID Mouse.

You seem to be confusing microcontrollers and processors (literally in your text). But also, "bare metal programming" really doesn't take that much registers on Arduino/AVR, you'll only have to set up what you need, and you can use libraries or the datasheet.

I will gladly change "processor" to "micro-controllers" in the answer if you explain why.  Now that I think about it, I believe "embedded processor" is the more commonly used term.  As for initializing the embedded processor's registers, I agree, if you do not rely on the feature you do not need to initialize the register. Regardless, the point of the answer was to make the OP realize that he / she was giving up a key feature of the Arduino platform.  The abstraction from the embedded processor's own hardware.

Getting a "bare metal" program into this sort of chip requires no tools different from those used to get an Arduino sketch in.  The same compiler can be used (even literally as installed by the Arduino IDE), and the chip can't tell the difference.

I had assumed the OP wanted to remove the Arduino boot program and do all his / her own C programming.  In such a case, at minimum, you would need a 2nd Arduino to act like a programmer.  Or, perhaps, pick up this or that AVR programmer.


text:
Format hour and minute integers to HH:MM format (char*)
In Arduino code, I'm calling the getTextBounds() and print() API methods on my TFT handler object which accepts char* parameters and I have two integers holding a specific time's hour and minute part, for example:
int _hour = 7;
int _minute = 30;

I need to construct a char* variable that holds this string: 07:30.
What is the simplest way to do that?
I tried this:
char* timestr = (_hour < 10 ? '0' : '') + _hour + ':' + (_minute < 10 ? '0' : '') + _minute;

But it gives me two kind of errors:
error: empty character constant
error: invalid conversion from 'int' to 'char*' [-fpermissive]

You don't want a char *, you want a character array, i.e. you have to
allocate the memory for the string, not only for a pointer. That being
said, you can build the string one character at a time like this:
char timestr[6];
timestr[0] = '0' + _hour / 10;
timestr[1] = '0' + _hour % 10;
timestr[2] = ':';
timestr[3] = '0' + _minute / 10;
timestr[4] = '0' + _minute % 10;
timestr[5] = '\0';

Then you can use timestr just as you would use a char*.
Edit 1: If you are not too short on RAM, you could allocate the string
statically, and have the C runtime initialize the characters ':' and
'\0' at program startup. Then you just have to set the four remaining
chars on each conversion:
static char timestr[] = "--:--";  // initialized only once, with template
timestr[0] = '0' + _hour / 10;
timestr[1] = '0' + _hour % 10;
timestr[3] = '0' + _minute / 10;
timestr[4] = '0' + _minute % 10;

Edit 2: Maybe the “simplest”, in the sense “closest to what you had
in mind”, would be to use a String object:
String timestr = String() + (_hour < 10 ? "0" : "") + _hour
    + ':' + (_minute < 10 ? "0" : "") + _minute;

You could print() that String directly, or retrieve the internal
char* with the c_str() method.
I added this method only for completeness. Although simple in the source
code, it would not be my first choice: it uses more memory, it is more
CPU-intensive and – what worries me most – it uses heap allocation,
which carries the risk of memory fragmentation.

That's one good answer!
What if I would like to form this value: "03 Dec, 2016", where "Dec" comes from a char*[12] or char[12][3]? Should I manually set each piece of the timestr variable?

@papaiatis: Best option would probably be to use strftime(), from <time.h>, but it is only available on recent releases of avr-libc. You will have to test, as I don't know whether a time.h-enabled avr-libc is shipped with the Arduino IDE. If you don't have strftime(), sprintf_P() is a reasonable fallback. C.f. KIIV's answer.

I ended up using your Edit1 solution. Thank you a lot for your efforts! :-)

What about using stdio.h? I know, it eats up some flash space, but:
#include <stdio.h>

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

void loop() {
  int _hour = 3;
  int _minute = 9;
  char buff[14]; // in worst case 6digigts per integer, separator and string terminating char

  sprintf_P(buff, PSTR("%02d:%02d"), _hour, _minute); // format string resides in flash (it needs special version of sprintf.
  // sprintf(buff, "%02d:%02d", _hour, _minute); // usual variant, but format is stored in RAM (and Flash too)

  Serial.println(buff);
  delay(5000);
}


text:
Arduino Uno and ESP8266 serial monitor issue
I plugged in the Arduino Uno and the ESP8266 following this schema:

When I enter "AT" in the serial monitor, I get an "OK". I can also connect to my wifi using typical ESP8266 commands.

What doesn't work is passing these commands using an Arduino Script. For example, if I use this script, I don't get an "OK" from the ESP8266.
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

 void loop() {
  // put your main code here, to run repeatedly:
 Serial.println("AT");
 delay(10000);
   if(Serial.find("OK")){
    Serial.println("OK");
     }
     else{
     Serial.println("NOT OK");
  }
}

I tried a bunch of different codes,and nothing works. What am I doing wrong?

With the code above, how can you say that you don't receive "OK" from ESP8266? Your code contains no read from Serial, so if "OK" is sent, you cannot know it.

Ok so my question was stupid i guess. What do I need to add so that I display the "OK"?

For that you'll need to check Serial.available() and then use Serial.readString() or other Serial methods. Then you will have to decide how you "debug" your sketch, that could be lighting a LED (quite limited) or printing to another serial port (for that you will need to use SoftwareSerial. I think you can easily find simple examples that just do that.

I updated the code above using serial.find(). It still displays "NOT OK". What I don't understand is when I type in the command "AT" everything works fine. When I try to pass it programatically, then it stops working.

What you are doing wrong is:
If sending AT commands from PC to ESP and receiving OK ,as you said, works - that means you connected TX output from USB --> RS232 IC on the board to both RX pin of the ATmega328 and RX pin of the ESP8266 - not as in your picture. Similarly, you connected RX input of the USB --> RS232 IC on the board to both ATmega328 TX and ESP8266 TX pin of the ESP8266. If communication between PC and ESP works, then you connected TX Arduino pin with TX ESP pin and RX Arduino pin with RX ESP pin and not as shown in the picture.
When you send AT command from PC both ATmega328 and ESP8266 are getting the signal from USB --> RS232 IC in their RX pins. As your firmware in the first 10 seconds doesn't read the RS232 data, ATmega328 just ignores the packets sent by PC but ESP8266 receives the packets and responds with OK.
Since you shorted RX on ATmega328 and RX on ESP8266 and you shorted TX on ATmega328 and RX on ESP8266, ATmega328 can not send the data to ESP and vice versa so there is no OK.
In the other case, if you connected ATmega328 TX with ESP8266 RX and ATmega328 RX with ESP8266 TX (as shown in the picture) then you would have shorted USB --> RS232 IC's TX with ESP's TX and you would have shorted USB --> RS232 IC's RX with ESP's RX.
In that case ATmega328 might be able to send AT command to both ESP and PC at the same time and ESP would respond but now ESP's TX would be connected to ATmega's RX which is now shorted with USB --> RS232 IC's TX so PC can't receive that packet. However, when ATmega328 responds with OK, the signal now goes from ATmega328 TX to USB --> RS232 IC's RX (as always) and you might see the response in serial terminal.
So, you can't get the ESP to respond directly to PC and to ATmega328 without interchanging the TX/RX wires. Furthermore, as you may know RS232 is designed for communication between two devices, not three - and this is the case where three devices (USB --> RS232 IC, ATmega328 and ESP8266) are connected to the same TX/RX pins at the same time in a rather unusual way. Because, devices are usually connected TX to RX and RX to TX. However, when using the Arduino's onboard USB --> RS232 converter (by removing the microcontroller or holding it under reset) then you have to connect TX to TX and RX to RX. That is because there is one more TX/RX pair in between PC and the RX/TX pins on the board. The output of the USB --> RS232 converter (TX) sends the data to RX pin on ATmega328 (and RX pin on the board) but if you want to send the signal further (to some other device), then the pin marked with RX is going to act as TX.
To summarize:

The schematics does not correspond to what you have written. Such a connection would not allow to send the AT commands from the PC to ESP and to receive response, meaning you connected the TX/RX the other way round.
You can not have both at the same time. You have to decide whether you want to send AT commands from the PC or from microcontroller and then connect the wires accordingly.


text:
Voltage on analog pin arduino when arduino turned off
So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

internal logic can be also configured as high impedance (High Z) - did you consider that?

All the GPIO pins have protection diodes in them. The are arranged, effectively, like this:

simulate this circuit – Schematic created using CircuitLab
The internals of the ATMega chip can be visualised for this purpose as a small resistor:

simulate this circuit
If you apply a voltage to the input without anything applied to Vcc you effectively connect the input to ground through the diode and the internals:

simulate this circuit
That means that too much current flows through the diode and potentially breaks it. And that's the least of your worries. The rest of the circuitry in the chip is subject to the same rules - any voltages that can flow back up to the Vcc rail the wrong way through parts of the circuitry in order to get down to ground risk breaking things.
It's almost as bad as connecting the power to the chip backwards. In effect your GPIO pin is acting as Vcc and powering the chip - badly.

If you add a large value resistor between the analog pin an the analog voltage source, not enough current can flow to cause damage. You have to be careful that the resistor doesn't influence the reading. Another option is to have a lower value resistor, but add an external clamping diode that can handle a lot more current.

The resistor increases the output impedance of whatever you are reading the value from - and yes, if too high it can affect the accuracy of your reading. It does provide some protection though. A better diode will protect the internal diode, but it won't stop the problem of back-powering through the internal logic. The proper solution is to use a MOSFET to isolate the input when there is no power applied.

An example and explanation can be found here: http://electronics.stackexchange.com/questions/134157/jtag-circuit-to-prevent-back-powering

So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

yes and yes.

Every AVR datasheet I've read gives the absolute maximum input voltage to a pin as something like Vcc + 0.5V - which in this case would be 0.5V.


text:
Replacement crystal on Uno for cold temperatures
I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?
P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost

Have you tried it at -40?  The crystal may still function but be out of spec, and you might need lower standard baud rates, or to tweak the generated baud rate to match what the reciever would expect..

@DaveX The baudrate seems to fail around -20c at 9600, have not tried tweaking it much

You could run the Arduino of the internal oscillator. After that you can calibrate the oscillator on the fly using the UART. PS are you even sure crystals exist that do work at -40?

All crystals change physical properties as their temperature changes. Heating it is always the fix.

@Gerben it's actually not the the arduino that has the issues, it's the serial to usb chip on the board
@ IgnacioVazquez-Abrams I know heating can fix it.. but I would end up increasing the power draw by a factor of 10 in order to keep the thing heated - also there are different components with different temperature ratings

If it's the USB to serial you could try connecting to the serial pins directly and have a separate USB to serial breakout, outside of the -40 environment.

What Gerben said--use the hardware serial instead of the 12MB USB2.0 connection, and its lower speeds should be more resistant to mismatched speeds, and should also be tunable if you get far out of spec.

Please give more details about the application. How are you connecting the board? Maybe using a remote oscillating circuit is the best way, or you can make a small board with a compensated oscillator. But... -40° is the limit for the atmega328p, so are you sure that you really need to have a arduino out there? You will need to power it, and batteries are useless at that temperature, so you'll need a power cable. If you have to wire it, then you can wire just the sensor you need to put there...

if you insulated it you wouldn't need 10X the power of running it to keep it "warm"

@dandavis that's assuming it starts warm, if it starts cold (which without running not even insulation will help against) it will take a while to warm up

Why do you think the crystal is the weakest link (the one for the serial chip)? Tolerancewise it is 200 times better than the ceramic oscillator (+/- 0.5%) used by the main processor. The ceramic oscillator has a 0.2% temperature sensitivity and is only specified to work for -20 °C to +80 °C.

There is a solution for just this problem, it's a "crystal oven". It is used to keep a crystal at a constant temperature so that the oscillating ferquency remains very stable.
Crystal ovens are usually expensive as they are quite precise and have good insultaion, but here's a kit that you might adapt for your uses: http://www.minikits.com.au/Oscillator-Heater, or google around to see if you find something that might suit you better.
You could also consider making a heater with a simple temperature regulator of your own to keep the crystal warm  (many temperature sensors for Arduino are available on the web).


text:
Oxygen sensor up to 50%
Are there any oxygen sensors that measure up to 50%?.
As I understand, there are sensors that measure only in range 0-30%.
Is it possible to increase the threshold of sensitivity of the sensor?

You can try SO002 or DS-TR250.

Is it possible to increase the threshold of sensitivity of the sensor?

I don't think its possible. Perhaps you can tweak the reading sensitivity, but since the sensor are mostly analog, it's not possible. And maybe that also the reason the 2 sensors I've mentioned above have several series based on their measuring threshold.

The Bosh LSU 4.X sensor(s) are what I think you are looking for. Here are some related links:
http://www.waltech.com/open-source-designs/wbo2_report/
https://github.com/Hell-Fire/WidebandO2


text:
What does the following code in Morse Code Arduino mean?
  struct node *root, *currentNode;
  root = (struct node*)malloc(sizeof(struct node));
  root->value = '\0';
  root->next = 0;
  currentNode = root;

It means allocate a structure of type and size node and initialize it - then copy the contents to another local variable called currentNode.

Just want to add, that the copied content of the variable root is a POINTER, so after theat root and currentNode points to the same place in memory. So for example after you do currentNode->value='a'; then root->value becames 'a' too, as it is on the same place in memory. (until you move root or currentNode to poit to other place - I would bet, that somewhere else is command like currentNode=currentNode->next;)

@gilhad The post has changed since I commented. Originally currentNode wasn't a pointer, but a local variable.

What does the following code in Morse Code Arduino mean?

Step by step:
  struct node *root, *currentNode;

Pointer variables root and currentNode. Pointers to struct node.
  root = (struct node*)malloc(sizeof(struct node));

Allocate memory for a struct node and assign root pointer.
  root->value = '\0';
  root->next = 0;

Assign struct node members using the root pointer. Assign value member to character 0. Assign next to zero, NULL, i.e. often marks end of list.
  currentNode = root;

Last assign currentNode to point to the save value as root, i.e. the allocated struct node.
Next question?

What's missing from this tiny code excerpt is the definition of 'struct node'. From the name, 'node', the member name, 'next', and the way these are being assigned, it's very likely that these 'struct node's are part of a linked list structure; a collection of data that is arranged, not by location as in an array, but by each node having a pointer (memory address) to the next one in sequence. One fixed memory location (apparently 'currentNode') points to the first datum; that one points to the next, and so on until the last one in sequence whose pointer value iz zero (or NULL, the symbol commonly used for an invalid pointer value).
Sorting a list is quicker than sorting an array or a collection of arrays of data, because only the pointers need to be changed; no data needs to be moved. Adding or deleting data in the middle of the list benefits even more; in an array you'd have to move all of the data following the add- or delete-point to create or close a gap for the new or removed datum.
Look at the rest of the code. It's quite likely that is how the 'node's are being used. Also read about linked lists, if that is a new concept.


text:
How accurate the an attiny timer function
I have an AT-Tiny (trinket) and I want to trigger LED on for 30 seconds every 24 hours. I'm using the timer library as follows
timer.setInterval(86400000, toggleit());

void toggleit()
{
  turnLightOn();
  delay(6000);
  turnLightOff();
}

How accurate will this be, if it's off by a few minutes each day that's fine, but will this drift over time? Also does it make a difference if I'm running it in 8 or 16 bit mode?

Just measure how long it actually take. Then change 86400000 to a lower or higher value, depending on whether it took more of less that 24 hours to re-flash the led. You could still get some drift, depending mostly on the temperature, but probably accurate enough in your case.

The on-chip systemclock is not very accurate. You can calibrate it to some degree but it also depends on the temperature and load of the MCU. You will need a high quality quartz oscillator as external clock source to reduce it. But it will still have a drift. Switching from 8-bit to 16-bit won't make a difference.
In your case an RTC sounds like the way to go.


text:
How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval
My objective is if ultrasonic readings ranging between 1 to 10 cm and no distance change for 10 seconds or more, a LED will turn on. Here is my current code.
#define trigPin 7
#define echoPin 8
#define led 13
#define led2 12

long duration, distance, interval = 4000;
int detection = 0;

void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
   detection = millis();
}

void loop() {

   ultraSonic();

   if (distance > 0 && distance < 10 && (millis() - detection >= interval)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW);
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH);
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

Sorry for my bad english.
Cheers.

In your primary if statement:
if (distance > 0 && distance < 10 && millis() - detection >= interval)
Consider grouping clauses with parentheses to make order-of-operations explicit. If nothing else, it will improve readability of the code.

Based on previous answer and your comment, maybe you can try this one
I assume if the range is ranging 1-10 cm for 10 secs or more the led will turn on:
void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
}
int togle = 0;

void loop() {

   ultraSonic();

   if ((distance >= 1) && (distance =< 10)) //dont use (distance>0)
   //there are possibility you get 0.xx distance
   {
     Serial.print("Distance on range - ");
     if (toggle == 0)
       {
        toggle=1;
        detection=millis();
        Serial.println("last detection outside range");
       } else
     if (toggle == 1)
     {
        Serial.print("last detection in range - ");
        if ((millis()-detection) >= interval)
            {
             Serial.println("objective complete");
            }
        else Serial.println("not enough interval");
     }
   } else
   {
     //turn off the led
     Serial.println("Distance out of range");
     toggle = 0;
   }

}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

Feel free to tell if something is not right

Sir, thanks for your help. Can you explain about starttime that you made it in the code?

ah sorry I did not notice that. I fixed the answers

the result of that code is the led turned on after distance is more than 10 cm. any suggestion sir?

Can you provide more information? About the test condition, results, expected results, etc

the result I expect is if the distance is between 1 and 10 cm, and no change in distance in a minimum of 10 seconds, the led turn on. as long as the distance still no changed after 10 seconds, the led still on. but if any change in distance after that, the led will turn off.

its debugging time then. I update my answer, tell me what you got

Let us continue this discussion in chat.

great. everything is working as my expected result. thanks for everyone.

void loop() {

   ultraSonic();

   if ((distance > 0) && (distance =< 10)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW); // turning LED on
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH); // turning LED off
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

sir, how about the timing? what i want is if no change in distance for more than 10 seconds then led will turn on. Cheers.

Take an integer and increase it every time that the object is on the required distance. If it's not, you set it back to 0. You can then check if the integer is as high as required (amount of checks done). Find a neat way to put a little delay between the checks, and you're set.

Paul is correct, but using integer as counter will less precise. Even if delay is arranged neatly, a small change in program can decrease the accuracy of "10 secs". But its simple and great if the "10 secs" accuracy is not too important


text:
Make something happen on a continous input just once and for a specific amount of time
My project is very complicated, but here is a visual synthesis

The input actually comes from a kinect, that detects a person position through Processing, which I connected via Serial to Arduino.
Whenever my trigger is activated, a character is sent to arduino.
What I need to make everything work properly is, upon the said input, some lines of code have to be executed once and for a specific amount of time. And upon repeated input, these lines must not be executed until the input changes.
A semplified version would be: I press a button, led turns on for one second and then turns off (even if i'm still pressing it). led doesn't turn on again until i stop pressing and press again. Obviously in my project the input is the character received via serial and the output is the motor to turn on for some time, and then turn off.
I wanted to make the serial thing specific because i think it makes the thing a little bit trickier than the led example.

Your button analogy falls apart immediately when you try to convert it to serial. Could you delete it, please, and explain exactly how you want it to behave, considering that characters being received on the serial port are discrete events?

Well, te problem is actually the same provided that you write correctly the first program.
How did you solve the button problem? My suggestion is to use a simple state machine:
const byte ledPin = 13;
const byte buttonPin = 2;

const int onTimeMs = 1000; // The time the led should be on

// In this state the board waits
// for the user input
#define STATE_WAITING 0
// In this state the button was
// pressed (so the led is on)
#define STATE_PRESSED 1
// In this state the board is waiting
// for the button to be released
#define STATE_WAITREL 2

byte currState;
unsigned long pressTime;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  currState = STATE_WAITING;
}

void loop() {
    switch (currState)
    {
    case STATE_WAITING:
        if (digitalRead(buttonPin) == LOW)
        {
            digitalWrite(ledPin, HIGH);
            pressTime = millis();
            currState = STATE_PRESSED;
        }
        break;
    case STATE_PRESSED:
        if ((millis() - pressTime) > onTimeMs)
        {
            digitalWrite(ledPin, LOW);
            currState = STATE_WAITREL;
        }
        break;
    case STATE_WAITREL:
        if (digitalRead(buttonPin) == HIGH)
            currState = STATE_WAITING;
        break;
    }
}

In this case you can be in three states: waiting for the button press, waiting for the led to turn off (after one second) and waiting for the user to release the button.
So... The states remain the same even for the serial input, you just have to trigger the transitions in another way. The only problem is that the serial input is not continuous, so you have to determine what you mean by "stop sending". In my opinion, you can just set a timeout. The simplest way to achieve this is with this code, IMHO:
const byte ledPin = 13;
const char cmdChar = 'x';

const int onTimeMs = 1000; // The time the led should be on
const int timeoutCmdChar = 50; // The time the char should be off

// In this state the board waits
// for the user input
#define STATE_WAITING 0
// In this state the character was
// received (so the led is on)
#define STATE_RECEIVED 1
// In this state the board is waiting
// for the char to be absent
#define STATE_WAITABS 2

byte currState;
unsigned long recvTime;

unsigned long lastTimeCmdChar;

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
    currState = STATE_WAITING;
}

void loop() {
    bool cmdCharReceived = false;
    while (Serial.available())
    {
        if (Serial.read() == cmdChar)
        { // Received the character
            cmdCharReceived = true;
            lastTimeCmdChar = millis();
        }
    }

    switch (currState)
    {
    case STATE_WAITING:
        if (cmdCharReceived)
        {
            digitalWrite(ledPin, HIGH);
            recvTime = millis();
            currState = STATE_RECEIVED;
        }
        break;
    case STATE_RECEIVED:
        if ((millis() - recvTime) > onTimeMs)
        {
            digitalWrite(ledPin, LOW);
            currState = STATE_WAITABS;
        }
        break;
    case STATE_WAITABS:
        if ((millis() - lastTimeCmdChar) > timeoutCmdChar)
            currState = STATE_WAITING;
        break;
    }
}

you want something along the lines:
bool continuing;
#define trigger 't'
void loop(){
  if( Serial.avaiable()) {
    char c;
    c=Serial.read();
    if (continuing) {
       if (c==trigger) { //do nothing, ignore it
       } else {
       continuing=False; }
   } else {
     continuing=True;
     motors.start();
     the_time=milis();
   }
 };
 if (the_time+timespan>milis()) {motors.stop();};
}


text:
Precise rotation (steering direction to a given angle) on obstacle avoidance robot
Forgive my lack of knowledge of some robotic related terms, but the way my two wheel drive robot steers is simply by having each wheel move at different speeds; for left, for example, the left wheel moves while the right one stays stationary for a given delay of time and vice versa.
but I want to make my obstacle detection a little more sophisticated with the following logic:
As the robot moves, scan the environment using an ultrasonic sensor(60 degrees to left and 60 degrees to the right) and using a simple max finding algorithm find the optimal angle i.e. angle at which the ultrasonic reading was highest. and then I want to find a way, using the same system of vehicle rotation if possible, turn to that specific angle proceed to move forward and scan simultaneously.
what I aim to achieve in the end is smoother obstacle avoidance as compared to the most common stop when close to obstacle -> turn left or right -> move and loop

The only way you can know how far you have turned, with any form of accuracy and, more importantly, repeatability, is by employing some form of feedback.
In other words, to work out how far you have turned you need, first, to know how far you have turned.
The simplest method is probably to use some form of monitoring on the wheels themselves. That could be an optical encoder to give a nice high resolution "number of degrees the wheel has turned", which can be coupled with the circumference of the wheel to calculate the distance travelled (which can then be used with some simple trigonometry to work out the angle you have turned through) or a more coarse "magnet on the wheel + hall effect sensor" to give you the number of revolutions the wheel has gone through (not very accurate and only really any use at higher speeds when there will be lots of revolutions. Maybe this method would be better on the motor before the gearbox that drives the wheel?)
However, do you really care that much anyway? Are you over thinking things a little too much?
Surely a simpler method would be to first turn left an arbitrary amount (somewhere around 60-degrees-ish, you're not really worried) then sweep from left to right (a distance of somewhere around 120 degrees in total) looking for the furthest distance. Once you have completed your sweep you then just reverse your turn direction until you read the same (or within a certain tolerance) distance at which point you will be facing your longest space.
All that can be done just with spinning the wheels either for a pre-defined period, or until a specific reading has been obtained. No need to worry about precise angles or anything fancy like that.

You could try an electronic compass, such as this one. Use it to compare your current (turn) angle to the desired angle, and keep turning until the desired angle is reached.


text:
Show images on a monitor using Arduino via Wifi
Consider a computer monitor hanging on a wall. Next to it is an Arduino Uno with a wifi. Is it possible to create something like this? Using wifi it should be possible to send data (images) to Arduino. This will be output to a monitor, like an image gallery. Images can be any type (videos included).
Is it possible? Where does one start?
Thank you.

This should be a fun challenge, if you're looking for a learning experience. As others have pointed out, you'll be working at the limits of the Arduino to get much of anything to work. If your goal is results, on the other hand, you'd be best off rethinking your design.

I have somewhere in my stash a shield that enables an Arduino to overlay graphics on the screen. But it is kinda crude and low-res. What you're trying to achieve is definitely not for Arduino, it is way underpowered.
You'd better look into doing this with something like a Raspberry Pi.

For the novice/intermediate, this is going to take way too much time and effort to meet the requirements you have asked with an Arduino Uno (if it is even possible).
May I suggest a Raspberry Pi instead.
The Raspberry Pi (depending on the model) has multiple video outputs:

HDMI
Composite video
LCD display

Each of these video outputs require very little effort to get going.
Adding WiFi capability requires just a USB WiFi dongle (and possibly downloading a driver) a bit of set-up and that about it. The RPi 3 (Model B) has on-board WiFi so you won't need the dongle.
What you want is very similar to a digital photo frame, so I would search for people who have already done that using google. I imagine that there would be plenty of free code/software out there on the internet.
All of this is a lot easier on the Raspberry Pi compared to using the Arduino.

pcDuino is another hardware platform much like the Raspberry Pi that would meet your requirements. The pcDuino is less popular than the Raspberry Pi and so there may be less open source code out there in cyberspace - but it would still be worth a try.

What you want is the GameDuino shield which gives you a full VGA experience on your Arduino. Also good for making games with.