text:
Modbus Communication protocol for Arduino as Slave
I have an Arduino Uno board, with these components:

rs-485 Modbus module shield
Multiprotocol radio shield board for Arduino

In addition I have a level sensor which reads either 1 when it is above water, and 0 when it is below.
I need to be able to give the value of this sensor to a modbus master over rs485.
Cooking Hacks Tutorial
This page has a description of how to use the ModbusMaster485 library, but I can not find any information about the slave library.
I can not find any documentation for this library, and would really appreciate any pointers.

Can you post the links to all the library that you've tried so that none of us would post the same. Thanks.

@Dat Ha I've tried using SimpleModBusSlave.h, but the problem is, I have to use Arduino Nano, while the data system in that library is using enum (so it starts from 0). Meanwhile, the data from master is reaching 3000+, which causing full-memory stack error

It's not very well documented for the slave but maybe that is because it only has two methods...
It looks like the slave library is contained in the same library as the master but with name ModbusSlave485.h
You can see in the .h it only has two public methods. One is connfigure() and the other is update(). see below an extract from the .h which explains what each method does.
#include "ModbusSlave485.h"

mySlave = ModbusSlave485();

void setup()
{
  mySlave.configure(slave, baud, parity, txenpin);
}

void loop()
{
  //check for update from master
  mySlave.update(regs, regs_size)
}

extract from .h
/*
 * configure(slave, baud, parity, txenpin)
 *
 * sets the communication parameters for of the serial line.
 *
 * slave: identification number of the slave in the Modbus network (1 to 127)
 * baud: baudrate in bps (typical values 9600, 19200... 115200)
 * parity: a single character sets the parity mode (character frame format):
 *         'n' no parity (8N1); 'e' even parity (8E1), 'o' for odd parity (8O1).
 * txenpin: arduino pin number that controls transmision/reception
 *        of an external half-duplex device (e.g. a RS485 interface chip).
 *        0 or 1 disables this function (for a two-device network)
 *        >2 for point-to-multipoint topology (e.g. several arduinos)
 */
  void configure(unsigned char slave, long baud);

/*
 * update(regs, regs_size)
 *
 * checks if there is any valid request from the modbus master. If there is,
 * performs the requested action
 *
 * regs: an array with the holding registers. They start at address 1 (master point of view)
 * regs_size: total number of holding registers, i.e. the size of the array regs.
 * returns: 0 if no request from master,
 *  NO_REPLY (-1) if no reply is sent to the master
 *  an exception code (1 to 4) in case of a modbus exceptions
 *  the number of bytes sent as reply ( > 4) if OK.
 */
  int update(int *regs, unsigned int regs_size);

  // constructor
  ModbusSlave485()
  {
    myDevice = RS485();
  }


text:
Problem with combination of Bluetooth and RF 434MHz with Arduino Mega
I want to receive text from Bluetooth from an android phone to Arduino Mega. Then I want to send that text to other Arduino UNO through RF 434MHz.
Here is my code for Transmitter.
#include <VirtualWire.h>
void setup()
{
  Serial.begin(9600);
  vw_setup(2000);
}

void loop()
{
  String voice;
  digitalWrite(8,HIGH);
  while (Serial.available())
  {                 //Check if there is an available byte to read
    delay(10); //Delay added to make thing stable
    char c = Serial.read(); //Conduct a serial read
    if (c == '#') {break;} //Exit the loop when the # is detected after the word
    voice += c; //Shorthand for voice = voice + c
  }
  if (voice.length() > 0)
  {
    Serial.println(voice);
  }
  send(voice);
  delay(1000);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

after compiling, I am getting an error as

exit status 1
  cannot convert 'String' to 'char*' for argument '1' to 'void send(char*)'

Please anyone tell me a way for solving this.
Problem is at transmitter part only. So I posted only about it.

[This should be a comment, but its too long]

•exit status 1 invalid conversion from 'const char*' to 'char*'
  [-fpermissive]

This means that the function you are calling wants a char* as a parameter, but you are passing it a char* that can't be modified.  The chances are that the send function doesn't modify the value in the parameter, so you might be OK just casting it, but you might get a runtime error if send does modify the value (a segmentation fault most likely, or just an ugly crash).  If you do you will need to allocate a temporary buffer that is big enough (str.length() + 1) and then copy it into that buffer and pass that to send.
So, try this first:
send((char*)voice.c_str());

If that fails then try this:
char* tempBuffer = malloc(sizeof(char) * (voice.length() + 1));
if (tempBuffer)
{
    strncpy(tempBuffer, voice.c_str(), (voice.length() + 1));
    send(tempBuffer);
    free(tempBuffer);
    tempBuffer = 0;
}

Of course if the data is always a fixed length then you can allocate an array on the stack instead of mallocing a buffer onto the heap.

thanking you. It worked very well the first one  send((char*)voice.c_str());    But after that I got another error in transmission. Once I send a string of length 15 characters then after that if I send 16 or more than 15 characters string , it is receiving only up to 15 character in same way the string length is getting fixed and unable to send more length string than previous one.In such a way the length of string receiving is getting reduced. Can you suggest me any solution for this problem?

exit status 1 cannot convert 'String' to 'char*' for argument '1' to 'void send(char*)'

The compiler is telling you about the issue. You can access the String as a character vector (C string) with the member function c_str(), e.g. send(voice.c_str());
You might need to check that it is not too long for the payload in the VirtualWire library.
Cheers!

I had done what you said then it returned with following error > - exit status 1 invalid conversion from 'const char*' to 'char*' [-fpermissive]

source: Stack Exchange

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

sort: votes


text:
Air data rate nRF24L01
I'm using two nRF24L01 to communicate with each other. I did the right setup and they worked fine, however I wanted to change the air data rate to a lower value, for more stability, as the datasheet says.
How can I setup the configuration for this?
After a small research I knew that you can change this using RF_DR
to change the value of the transmission, but I didn't really know how I could exactly write the correct code for this.
Another question: does this effect the range of the module? Or does it only affect the stability? And if not, then which code can I use to extend the range of these two modules ?

Which library are you using?

i'm using this library https://github.com/TMRh20/RF24

The documentation tells you how to do it. Did you try reading before coming here? It took me precisely 15 seconds to find it from the link you just provided: http://tmrh20.github.io/RF24/classRF24.html#aeb9920e7a95699748b003c4a839b0814

can you please tell me where to find it, i'm sorry but i honestly tried to do my best, so if you can, give me where did you find it

Did you click the link I provided?

yes i found it, thanks alot  , so can you help me with my second part of the question

Let us continue this discussion in chat.

Increasing stability will increase the (usable) range. At least a bit. You could try decreasing the packet size, to make it even more reliable. There is no way to increase the output-power (only decrease).
You could try different channels, and see which one gives you the best range in your application.
After that you have to get NRF24 modules, with external antennas and amplifiers.

According the nRF datasheet if you decrease the data rate it will definitely affect your range.
A lower data rate will increase your stability due to which the nRF can detect weaker signals (-102 dB at 250Kbps) due to this you can significantly increase the range (up to 1km theoretically).
Also if you need to increase your range further you can attach an antenna with a higher gain than what you already have.
No other software changes will affect the range other than reducing the transmission speed.

The documentation for the function you want is here.
Reducing the speed doesn't directly increase the range, but increased stability will have the knock-on effect that the fringes of transmission distance will be more reliable, making it appear that you have slightly greater distance.

Your claim about speed and range is untrue.  A narrower bandwidth signal has a greater power spectral density for a given total power output, a properly designed receiver listening for a narrower signal sees less total noise, and depending on architecture may see higher gain.  The data sheet is even explicit about some of this: " The 1Mbps data rate gives 3dB better receiver sensitivity compared
to 2Mbps."  However it also mentions that transmitting the same data at a slower rate increases the period of time during which it could be interfered with.

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

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


text:
Send stepper to position and back AccelStepper
At the moment I am working on a code that should send a plateau to a certain position and back. The plateau is being moved by the stepper, in my case a Nema 17 with a Polulu DRV8825 driver. Everything is hooked up correctly.
My goal is to press '4' on the keyboard and that then the stepper moves to a certain position. However, I am not succeeding in this. I am using AccelStepper and at the moment I have the following code:
#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1
int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.runSpeed();
}

Does anyone have tips or know how to achieve this?
Thanks is advance!

You need to call stepper.run() instead of runSpeed, for moveTo to work.

Gerben's comment:

You need to call stepper.run() instead of runSpeed, for moveTo to work.

provides the answer. The updated code is:
#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1

int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.run(); //You need to call stepper.run() instead of runSpeed, for moveTo to work. – Gerben
}


text:
Keyboard.println missing characters when I print long strings
The topic is pretty straight forward: When I use Keyboard.println(), it sends short (up to 30-ish) strings just fine, but when I get up around 100 characters there are random characters missing. "Random" - meaning it is not all the time, it's somewhat consistently the same characters missing though.
I've checked and the data is arriving at the Arduino correctly (over web service), but once it shows back up in the notepad, it's missing random stuff.
Any thoughts or suggestions?
Edit: Examples as requested:
I'm sending...

cheat SpawnDino Blueprint'/Game/PrimalEarth/Dinos/Pelagornis/PelaCharacter_BP.Pela_Character_BP' 10 1 1 10

And what's printing is...

cheat SpawnDino Blueprint'/Game/PRIMALEarth/Dinos/Pelgornis/PelaCharacter_BP.Pela_Character_bP' 10 1 1 10

I've actually noticed now that it's changing capitalization too, the BP to bP and Primal to PRIMAL.

Could you provide examples which compare the data arriving and the println output?

Not sure why it's happening, but you can probably avoid it by sending only a smaller number of characters at a time, and then add a small delay in between.

Yeah, thanks for the suggestion. I've already tried that though and it's being weird too.. Wont send anything when I nest a keyboard.anything inside of a for loop, regardless what the wait is set to..
Back to tinkering :) thanks.

Could you please provide your code?

I'd bet the issue is overflowing the keyboard buffer of the device you're talking to. On Windows, you can change a registry value to make the buffer larger:
http://www.windowsnetworking.com/kbase/WindowsTips/WindowsNT/RegistryTips/Hardware/KeyboardBufferSize.html
(and in fact, the Windows keyboard buffer is 100 characters by default.)
The reason the capitalization is becoming strange is because the device missed the shift-down or shift-up event, so it's using whatever it would use if the shift key wasn't pressed or released.
The best solution is to avoid sending so much: break it down and send a little at a time as Gerben said.

I just got another idea how to do that instead of character by character since you said that.. Will give it a try, thanks a lot


text:
PCF8547 Wire.write explanations
I am using an ESP8266-12E with a PCF8547.
I have managed to turn on and turn off LEDs using these two things.
I am using these three commands to do it.
 Wire.begin(SDA_PIN,CLK_PIN);
 Wire.beginTransmission(0x20);
 Wire.write(~((uint8_t)1<<cnt));
 Wire.endTransmission();

The problem I am facing here is: I am using 4 LEDs and I am only able to turn on one LED at a time. When I turn on another, all the LEDs turn off - in short, the LEDs or the PCF8547 do not preserve the state.
I want to toggle on the LEDs without disturbing the other's state.
How can I do it?
I think, I need more knowledge about the write function, don't I?
Update:
I have already connected A0, A1, A2 to ground. This is the function I use now to toggle the LEDs.
void enlight(int cnt)
{
  if (cnt == 1)
    value = value | 1<<cnt;
    if (cnt == 2)
      value = value | 2<<cnt;
    if (cnt == 3)
      value = value | 3<<cnt;
    if (cnt == 4)
      value = value | 4<<cnt;
    value = ~value;
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20); Wire.write(value);
    Wire.endTransmission();
  }

but when I turn off/on any other LEDs they also toggle, which I don't want.

Please add circuit description. How have you connected the LEDs? With to low resistors the LEDs will draw to much current. Check the numbers!

Forwarded from the user Pete: Aren't the addresses of the LED's (or devices) given in the datasheet?

@MikaelPatel : i will add the circuit image that is not an issue.
what i want to achieve is just like we send HIGH and LOW signals to GPIO pins of ESP8266-12e and turn off/on the led connected to that GPIO ,  the same i want to do with PCF8547.  i want to know technique to access the address or some identification to the I/O pins of PCF8547 so that only one led at a time i can turn on/off without affecting other pins  .

Just remember the value you sent last time, and modify only the bits you want to change. Google will tell you how to change a single bit in C (or C++).

This might be of some help; https://github.com/mikaelpatel/Cosa/blob/master/libraries/PCF8574/PCF8574.hh

@MikaelPatel : The library from which you have provided the link , does not support ESP8266-12E.

The library/code was to expire you on how to write this type of code. Cosa is a totally different approach and more advanced programming of the Arduino. https://github.com/mikaelpatel/Cosa

@MikaelPatel : I appreciate the help , but the type of functions and their working in Cosa is not there for Esp8266 . Please guide me more if possible.

Thanks for your edit - it's much clearer. I've added code to my answer showing you how to modify one light at a time - you have to remember the value of all the other lights.

(I haven't used this library, but this looks like a general C(++) question...)
The important part of what you're doing is this:
Wire.write(~((uint8_t)1<<cnt));

Let's break it down.
It calculates a value by taking the number 1 and shifting it left cnt times. Then it takes the complement of that number - changes 0s to 1s and 1s to 0s.  This number is sent to Wire.write() and lights up light number cnt.
Example: Let's say you start with cnt==2, to light LED 2.  It will shift the number 1 left by two digits, giving you the binary number 00000100.  Then it will invert this, giving you 11111011.  This is given to Wire.write().
We can see from this that to light an LED, we need to put a '0' in the right place.
How can you make several numbers light up?  We need to put several zeros in, at the right places.
Here's an example of how you might like to do this - which isn't the prettiest code but I hope it shows you what's going on.
// How we would like the LEDs to appear
boolean led0 = true;    // LED 0 ON
boolean led1 = false;   // LED 1 OFF
boolean led2 = true;    // LED 2 ON
boolean led3 = false;   // LED 3 OFF

// Start with all LEDs off
uint8_t value = 0;

// Put a 1 in place for each LED we want to be ON
// The | symbol means "logical OR" (Google it)
if (led0) value = value | 1<<0;
if (led1) value = value | 1<<0;
if (led2) value = value | 2<<0;
if (led3) value = value | 3<<0;

// Invert this value
value = ~value;

// Write it to Wire
Wire.begin(SDA_PIN,CLK_PIN);
Wire.beginTransmission(0x20);
Wire.write(value);
Wire.endTransmission();

Since it appears you have to send values for all the lights every time, you need to remember the value you sent last time, and modify only the bits you want to change.  Here's a way you can do that:
void setLight(int lightNum, boolean lightOn) {
  // Remember the last state of the lights.
  // Start with all lights OFF.
  static uint8_t lightsOn = 0;

  // We only have four lights (0-3).  Only respond for lights
  // we we have.
  if (lightNum<4) {
    // Get a bitmask with a single 1 in the right
    // position for this light
    uint8_t position = 1<<lightNum;

    // Clear (to 0) that bit in the state
    lightsOn &= ~position;

    // Set (to 1) the bit if we want the light on
    if(lightOn) lightsOn |= position;

    // Write out the value of all lights
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20);
    Wire.write(~lightsOn);
    Wire.endTransmission();
  }
}

Call it with something like
setLight(0, true);    // Switch the first light ON
setLight(3, true);    // Switch the fourth light ON (first stays on)
setLight(0, false);   // Switch the first light OFF (fourth stays on)

totally explainable. i got how it works now.
but i am not be able to analyse what address does the pins have.
the code you have provided toggles all the other leds too.
is it possible to get the addresses of the pins on PCF8547 so that the actual led is toggled by us.

Can you experiment with the values of led0...led3 to find the addresses? They should be the same numbers you were using for cnt.

I have been doing experiments, the results are various , but not be able to trigger only one Led , its complicated for the person with non-electronics background, me.
i have managed to find what will the value of the variable value but that also not only triggering the particular pin. plus since few days my Serial monitor is not working. so cant predict the output same time.

Then I think we need a circuit diagram please.

I'd also suggest, if your serial monitor is not working, you're making things harder for yourself by working blind. Don't fall into a gumption trap https://en.wikipedia.org/wiki/Gumption_trap - get that fixed first.

hi i am using the WIFIClient , and the function client.print() , it gives me the values i want to see , but they are not helpful, is there any other way to just toggle the led on a particular pin of PCF8547. other all things i have written properly in my code , the GPIOs of ESP8266-12e i can toggle coz i have the pin no , but don't know how to access and toggle the pins on PCF8547.
Serial monitor issue i will solve afterwards i have priority to solve this first. i have added circuit diagram in question too.

awesome. answer. solved my problem.

Glad I could help :-)


text:
How to use ESP8266-12E with PCF8574 as an I/O extender
I am using ESP8266-12E with a PCF8574 as an I/O Pins Extender.
There are videos on youtube to use the PCF8574 with an ESP8266-01, but my problem is that I'm unable to analyze the pin connections with an ESP8266-12E.
In the youtube tutorial it is said that the GPIO0 AND GPIO2 will go to the SDA and SLC pins of the PCF8574, but then, in the case of ESP8266-12E, the pins will go to the PCF8547.
Thanks in advance.

What is the link to Arduino UNO as you tagged your question?

sorry , i thought people who knows arduino things might also know this.

The '8C-ESP8266 Interface I2C' document may help, if you have access to it.  It's available on Scribd, which is non-free.  One can see the  first page of '8C-ESP8266 Interface I2C' without a Scribd subscription

@jwpat7 : thanks . only first page , unfortunately cover page is visible in free.

i guess very less people plays with such things o wat!

Found the answer .
The data sheet of ESP8266-12E explains everything.
The pin diagram has the given tags which shows which pins we can use.

Would you mind detailing the answer so that your question can bring benefits to other people having the same question?

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

@jfpoilpret, he IS the author...

i have added details to the answer.

@DatHa this comment was automatically generated from my delete vote; please don't think I can be so stupid, thanks.

@all : is my way wrong to provide and declare answer. if yes plz guide.

@karmaCoding, it could have a little more detail. You could add a wiring diagram and/or code you used to get it working. In that way, others can easily verify and/or use it.


text:
Understanding Soil Moisture Sensor Values
I have soil Moisture sensor inserted into the pot soil, wet in state. (not too damp) and soil moisture sensor is connected to Arduino Mega 2560.
This is the soil moisture sensor I am using:

Soil Moisture Sensor VCC is fed by 4.95 coming from Mega's 5 volt power out and soil moisture signal is connected to A0.
below are the readings
+---------------------+-------------------+-----------------------+
| timeStamp           | pot1_soilMoisture | pot1_avg_soilMoisture |
+---------------------+-------------------+-----------------------+
| 2017-01-26 14:31:19 |               825 |                    80 |
| 2017-01-26 14:32:19 |               816 |                    80 |
| 2017-01-26 14:33:20 |               828 |                    83 |
| 2017-01-26 14:34:20 |               826 |                    82 |
| 2017-01-26 14:35:20 |               820 |                    79 |
| 2017-01-26 14:36:20 |               833 |                    83 |
| 2017-01-26 14:37:20 |               463 |                    46 |
| 2017-01-26 14:38:21 |               546 |                    32 |
| 2017-01-26 14:39:21 |               156 |                    26 |
| 2017-01-26 14:40:21 |               157 |                    22 |
| 2017-01-26 14:41:21 |               509 |                    23 |
| 2017-01-26 14:42:22 |               204 |                    25 |
| 2017-01-26 14:43:21 |               226 |                    26 |
| 2017-01-26 14:44:21 |               190 |                    30 |
| 2017-01-26 14:45:22 |              1023 |                    84 |
| 2017-01-26 14:46:22 |               604 |                    83 |
| 2017-01-26 14:47:22 |               773 |                    79 |
| 2017-01-26 14:48:22 |              1023 |                    80 |
| 2017-01-26 14:49:23 |               599 |                    77 |
| 2017-01-26 14:50:23 |               766 |                    82 |
| 2017-01-26 14:51:23 |               579 |                    81 |
| 2017-01-26 14:52:23 |               729 |                    74 |
| 2017-01-26 14:53:24 |              1023 |                    82 |
| 2017-01-26 14:54:24 |               795 |                    80 |
| 2017-01-26 14:55:24 |               651 |                    77 |
| 2017-01-26 14:56:24 |               765 |                    83 |
| 2017-01-26 14:57:25 |              1023 |                    81 |
| 2017-01-26 14:58:25 |                 0 |                    60 |
| 2017-01-26 14:59:25 |               921 |                    30 |
+---------------------+-------------------+-----------------------+
1439 rows in set (0.02 sec)

I got three kind of readings of the sensor:

pot1_soilMoisture reading from 825 to 833 is when the sensor was dipped in water.
pot1_soilMoisture reading from 463 to 190-1023 is when soil moisture sensor was in air.
pot1_soilMoisture reading from 604 to last 921 is when soil moisture sensor is in soil. The soil is moist/wet.

I don't understand how to be definitive state of soil with such values?

I had this same problem when I began experimenting with soil moisture readings. I noticed that the readings from the sensor can vary widely when not hooked up correctly, or when other nearby objects are somehow interfering.
For instance when I put a SparkFun breakout similar to yours in dry soil and continuously take readings every 50ms, the signal oscillates from 0 to 50, and simply touching the soil with my finger can affect the signal due to the electricity in my body. If you have a metal pot on a metal table, that could be affecting your readings. There's a lot to consider!
However, once I water the soil and let it soak in, the reading generally becomes much more stable. Below I included a real-time plot using a plant I watered about 24 hours ago. Here's how I set up my soil moisture sensor, including code. The readings are taken every 60s and the plotter repeats the old reading until a new one is taken. There's very little deviation when all connections are secure and the soil moisture is evenly distributed.

In general, the specs for the sensor will inform you on what kind of signal to expect. Based on your sample data I suspect yours is a 10-bit signal from 0-1023, so 800 range means the soil is quite moist. If you just watered the plant, then the water content around the sensor will change as it seeps through the soil, leading to fluctuations when measuring. Give the soil a few hours to absorb the moisture and try measuring again.

Oh well thanks, I will use this strategy and see how it goes however, I have hooked up a realtime clock module using which I give water to pot for 10 seconds(enough for small pot) twice a day . And I think there really isn't need to set up a powering solenoid to water pot based on soil moisture . Thanks for your answer

I agree, for potted plants this is over-doing it. Still useful to learn how the sensor works. I think if you have a large number of plants in a raised bed this is a more useful technique for regulating water automatically.

Cool, now I have setup as per your answer, but millis instead of delay and now I am turning on soil moisture sensor using digital pin 8 . But so far I still can't make out huge distinction between when it is dipped in water or out in air or in soil

Do you have a second sensor to test? Or any other component that could use the same pins on your Arduino, so that you can verify that something works as intended? It's difficult to troubleshoot without some sort of reliable baseline. I did a search for your sensor and the example output on the official tutorial page seems to wildly fluctuate just like your sample data. The page doesn't provide specs so we can't be sure how it should be powered. Perhaps you could try powering with 3.3V instead of 5.

for experimenting I connected it to Arduino Uno and got this result : http://pastebin.com/1jDV0kjv with delay of 600 milieseconds, I found lower the delay more incorrect values but it seems to oscillates which I feel needs calibration that I dont know how to do it !

The values in your pastebin are the min/max of the sensor, so it sounds like there is a hardware problem. Is it possible for you to remove the header pins and temporarily place wires directly in the terminals of the sensor? Are you sure you're providing 5V to VCC? GND is secure? You can use A0 to reliably collect data from a different sensor? Perhaps your sensor needs more delay between powering on and taking a reading. Mine was fine with 10ms delay, but components and materials vary by manufacturer and it might make a difference.


text:
Bluetooth signal returns 0
I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that  immediately it becomes 0.
Why does it become 0? And how can I get rid of that problem?
Here is my code:
int x,y;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0)
  {
    x=Serial.parseInt();
    y=Serial.parseInt();
    Serial.print("x:");
    Serial.print(x);
    Serial.print("\n");
    Serial.print("y:");
    Serial.print(y);
    Serial.print("\n");
  }
  else
  {
    ;
  }
}

and here is the result:

Serial.parseInt() has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, Serial.parseInt() will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs parseInt() just returns 0.
IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial here.


text:
Checking for multiple values in IF separated by commata
My code is:
if ((minute == 31) && (hour == 4, 6, 9, 11))
{
  digitalWrite(8, HIGH);
}

I want to turn on the LEDs when it is exactly

04:31,
06:31,
09:31,
11:31

However, the code above doesn't work.
Might be the multiple values the reason for this?

Yes, the list of values 4, 6, 9, 11 does not mean what you think it does.
if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
    digitalWrite(8, HIGH);
}

Optionally, you could store the values in an array and go across all of them with some code like this:
int hours = [4,6,9,11];

function isInArray(inputValue, array) {
    boolean isIn = false;

    for ( int i = 0; I < array.length; i++) {
        // "isIn |= statement" is shorthand for "isIn = (isIn || statement)"
        isIn |= (array[I] == inputValue);
    }

    return isIn;
}

if (isInArray(variable, hours)) {
    //do whatever
}

//might be able to do
if (isInArray(variable, [4,6,9,11])) {
    //do whatever
}

Some language may allow you to write that, but not C++, which is the standard language for Arduino.


text:
MatLab connection to Arduino using Bluetooth
I am attempting to send some information from MatLab to an Arduino Uno via Bluetooth with the following
MatLab program:
b=Bluetooth('HC-06',1);
fopen(b);
for i=1:1:15
  fprintf(b,i);
  out(i) = fscanf(b,'%d');
end
fclose(b)

and Arduino program
int matlabval=0;

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

void loop() {
  if (Serial.available() > 0) {
    matlabval = Serial.read();
    Serial.println(matlabval);
  }
}

the output  of arduino is
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
10
10
10
11
10
12
10
13
10
14
10
15
10
The number 10 appears after each number. Why is that so?
Thanks in advance!

http://www.asciitable.com/
Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value.

As discussed in the comments, the "problem" seemed to be Matlab adding a "New Line" which is a decimal 10 in ASCII.

asciitable.com Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value. – Paul Apr 14 at 8:15

thank you very match the problem is solved – abbas hussien 5 hours ago

You might want to accept this answer so that this question gets "closed" and the site's statistics will be more accurate.
It will also avoid this question being bumped up by the system and people reading into something that has already been solved.


text:
Atmega328P 8MHz External Clock
Has anyone experience configuring the Atmega328P to work with an 8Mhz external clock?
I want to reduce the power consumption of the device. If I just connect an 8MHz external quartz oscillator then simple programs like LED blink still work (With the time delays doubled), but if I try to use communication like UART, then I am unable to. So no programming new sketches.

Looks like you are not using the correct "board". F_CPU has to be defined as your clock frequency. You can check LilyPad as an example.

Hi could you elaborate a little more on that for me ? I'm using a UNO as an ISP to an Atmega328P.

What "board" are you selecting in the Arduino IDE? Have you checked that the definition of the board has the correct clock frequency? My guess is "no".

How do you connect to serial communication? You write communication like UART but no circuit description!

Yes I checked in the board.txt file it is set to 16000000. Which is what I'd expect. I tried setting this to 8000000 but then the boot loader no longer works. I select the Arduino/Genuino

With the UART I am using a UB232R connected to the the Atmega328 Rx Tx lines, and with a capacitor connecting the DTR and reset pin. I know it works I have a second Atmega328 chip that I use to test it.

I'd try making the arduino sleep, and turning off unused devices. That will reduce the power more that running at half speed.

It should work with any crystal speed between 1mhz and 16Mhz. The fuse values allow 1Mhz to 16Mhz. But the arduino IDE assumes that you are using 16Mhz. You can probably google around to find a setting that can be chosen from the menu for 8Mhz.

If you reduce the main clock speed by 50% then everything else is reduced by 50% as well.
The whole chip runs at half the speed. That includes things like the UART.
For example, the bootloader is set to run at 115200 baud on a 16MHz chip. If you run that same chip, with the same bootloader, at 8MHz then the bootloader will actually be running at half the baud rate, so 115200 / 2 = 57600 baud.
Unless you tell the IDE that your board is now running at 8MHz (by creating or using the correct board configuration information to set F_CPU to 8000000) then time runs at half the speed in your sketches too. So a delay of one second will last two seconds. Every two milliseconds a single millisecond will pass. And again baud rates will be wrong. If you use:
Serial.begin(9600);

you will actually be running at half that speed (4800 baud) and so you would have to set your serial terminal program to that speed instead of the one you requested.
To to do things properly you will have to:

Replace the crystal
Edit, compile, and install a new version of the bootloader that runs at 8MHz
Create (or edit) a suitable board definition (in boards.txt) to compile sketches that expect to run at 8MHz.

Hi thanks for the reply, I have replaced the oscillator, and tried to edit the uno.build.f_cpu=16000000L to uno.build.f_cpu=8000000L. But if I do this then when I try to bootload the modified file I get 'avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xff'

Paragraph 3 of my answer.

Well I tried it I halved the baud rate to 9600, on the example ISP sketch. Then edited the board.txt file. Changed the oscillator. The bootload worked. but when I try to upload a sketch I get ''avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00'. Makes me think I need to change the Baud rate of the Arduino IDE but I have no idea how to do that. Does anyone??

uno.upload.speed=115200 in boards.txt

No, if I change this then the boot load fails

And what did you change it to?

The easiest way is to use the settings:
Tools > Board > Arduino Pro or Pro Mini
Tools > Processor > ATmega328 (3.3V, 8MHz)
The problem with that is the Pro Mini bootloader is 2kB and has a bug that causes an endless reset loop if you do a watchdog reset.
The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.
After selecting the correct configuration for your hardware from the Tools menu, do Tools > Burn Bootloader, which will set the fuses on your ATmega328P and upload the correct bootloader.

That is exactly what I was working on last night after someone suggested just using a Pro Mini. It worked well with no problems. I still never figured out why is never worked by changing the CPU and Baud settings in the Boards.txt file.

Same two menu selections work for other boards too, in conjunction with model selection as a third configuration essential if it is available and not already defaulted to the desired choice.

Firstly, you can buy 8MHz Atmega328P Pro-Minis from China. They are cheap and run at 3.3V. Look at eBay.
If you want to reduce the power consumption of Arduino boards, you have three primary attack vectors:

Removing the power LED
Removing the voltage regulator
A Low-Power library

All of these have different impacts on the power consumption of your respective board.
An extensive comparison can be found here in this blog-post.

That is an answer, but the china man won't deliver on Sundays, I could also use the internal 8MHz Oscillator but it also has 10% accuracy to calibrate it I need a 28KHz Oscillator, China man dos't deliver those on sundays either

hmmmm Pro mini perhaps that may work .... Thanks :)


text:
Arduino and A4988
I am new in the Arduino area.
What is necessary to control motors through Arduinos.

What is the difference between A4988 and the Arduino motor shield?
Is one A4988 needed for each stepper motor?
Or is one A4988 enough for all motors?

An A4988 can control a single motor and supply up to 35V at 1.5A.
An Arduino motor shield can drive 2 DC Motors or 1 stepper motor at up to 12V and 4A/2A.
An A4988 needs mounting.
A motor shield drops straight in.
There are other options, including getting the ICs and doing it your self.  I have a motor shield which drives 4 DC motors or 2 Stepper motors that I got off eBay.

The A4988 is a bipolar stepper driver. It is designed specifically to drive a single bipolar (4-wire) stepper motor. It consists of a pair of H-bridges and some extra drive logic to provide a simple GPIO interface.
The motor shield, in contrast, uses the L298D motor driver chip. This provides, as well, two H-bridges like the A4988. However it just gives you direct control of those H-bridges without a simple stepper-oriented interface.  So it is up to you to provide the correct control signals to effectively emulate the A4988's outputs.
Both chips can interface with exactly one bipolar stepper motor. The A4988 can only interface with a stepper motor. The L298D can also be used with other types of motor (though of course not at the same time as a bipolar stepper).

The L298 may seem more versatile, but it's also an antiquated high-loss bipolar device, vs a relatively modern and efficient FET one.

@ChrisStratton Agreed. But then people around here still use the LM741 and the TIP120, so the L298 isn't that bad by comparison ;)

@Majenko Are you absolutely certain the A4988 can't be used as an H-bridge for any type of motor?

@user2497 There's nothing to say you couldn't any other load up to it - however the interface to it is geared towards stepping. You don't have control over the H-bridge directly, you can only send it instructions on how to step a stepper motor and the internal logic controls the H-bridge for you. You have pins to set how far to step (1/1, 1/2, 1/4, 1/8 or 1/16 step), one for the direction, and one to initiate a step.  So yes, you could connect some other motor up to it, but you wouldn't be able to do anything useful with it.


text:
How do I program my Arduino Yun Shield when I keep getting this AVRDUDE error message?
The error message is:

avrdude: AVR device initialized and ready to accept instructions
  avrdude: Device signature = 0x1e950f
  avrdude: Expected signature for ATmega32U4 is 1E 95 87
  Double check chip, or use -F to override this check.

This error message is thrown when I attempt to upload any program to the Yun shield through an Arduino Bridge between the Uno and Yun shield with the Uno’s ATMega32 shorted into reset mode.
Any advice on how to get this working? Thanks.

Make sure the board selected in the Yun Shield is the correct one (in this case Arduino UNO).
Steps for selecting the board on the Yun Shield

In your web browser load the Yun Shield page and log in (how to do this is described in the Quick Start Guide).
Click on the SENSORS menu button.
Under Arduino Board Type select the correct one.
Click on the CONFIGURE & RESTART MCU button to apply settings.
Maybe manual restart of the board would be needed (power unplug).

Apparently there is no ATMega32U4 on that board but ATmega328P according to the signature 0x1e950f.
Anyway, you may have to change or add new board with correct MCU setting.
Now I can see the difference between Yun and Yun shield. Shield can be connected to any Arduino board and Yun is similar like Shield + Leonardo.
I've found board definition for Arduino UNO:
unoyun.name=Arduino Uno -- Dragino Yún
unoyun.upload.via_ssh=true

unoyun.vid.0=0x2341
unoyun.pid.0=0x0043
unoyun.vid.1=0x2341
unoyun.pid.1=0x0001
unoyun.upload.tool=avrdude
unoyun.upload.protocol=arduino
unoyun.upload.maximum_size=32256
unoyun.upload.maximum_data_size=2048
unoyun.upload.speed=57600
unoyun.upload.disable_flushing=true
unoyun.upload.use_1200bps_touch=true
unoyun.upload.wait_for_upload_port=true

unoyun.bootloader.tool=avrdude
unoyun.bootloader.low_fuses=0xff
unoyun.bootloader.high_fuses=0xde
unoyun.bootloader.extended_fuses=0x05
unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
unoyun.bootloader.unlock_bits=0x3F
unoyun.bootloader.lock_bits=0x0F

unoyun.build.mcu=atmega328p
unoyun.build.f_cpu=16000000L
unoyun.build.board=AVR_YUN
unoyun.build.core=arduino
unoyun.build.variant=standard

More info about it here: https://www.arduino.cc/en/Guide/ArduinoYunShield or similar product http://wiki.dragino.com/index.php?title=Yun_Shield

So there may be a chance that the reset and gnd pins aren't shorted?  Definitely not a clone btw - original Uno, and I've got the bill to prove that...

@Raihaan Yeah, I've noticed the difference between Yun shield and Yun, so it's updated now.

Ah.. I tried adding this to my boards.txt file but it wouldn't let me make changes as an admin... I also used another installer to install these definitions onto the IDE (the dragino yun shield with arduino uno) but same error... I tried it with an Arduino 101 too, but that's not an AVR board so didn't really expect that to work...


text:
Use of struct and sizeof in C for Arduino
I am a newbie in C and I can not understand the point of using a structure in C. Could someone explain to me what is the point of defining a structure in C programming?
For example, this code(written in C for Arduino)
struct books
{
  char name[30];
  char author[30];
  int ID;
} Mybook, Yourbook;

void setup()
{
  Serial.begin(9600);
  // put your setup code here, to run once:
  strcpy(Mybook.name, "Girl in the train");

  strcpy(Yourbook.name, "Gone");

  Serial.print("Name of the book is:");
  Serial.println(Mybook.name);
  Serial.println((long)&(Mybook.name));
  Serial.println((long)&(Mybook));
  Serial.println((long)&Mybook);
  Serial.println(sizeof(Mybook));

  Serial.print("Name of the book is:");
  Serial.println(Yourbook.name);
  Serial.println((long)&Yourbook);
  Serial.println(sizeof(Yourbook));
}

Would use the same amount of memory as defining
char Mybookname[30];
char Yourbookname[30];

And you should type the same amount of lines.
So what is the point?
I have another question:
Why I get 62 for the sizeof(Mybook)? I have not defined it anywhere. Is it set automatically?

It is all about reduction of complexity and abstraction. A book (a struct in your example) has a title, author and identity. Collecting these together instead of scattering them helps when the size of the program grows, and if it "lives" for a long time and needs updating. struct is easy, wait until you get to class :)

@Mikael Patel Thank you, I thought struct and class were the same!

C has no classes. In C++, struct and class are almost the same. The only difference is members being by default private in a class and public in a struct. A C++ struct with no methods (only data members) nor static members is very similar to a C struct.

With classes we approach programming from the point of view of operations on local data (objects). In your example above; the class Book could be used in a collection in a class Library. The Library would have member functions such as lookupBookBy(title/name/identity), borrowBook, returnBook(), etc.

I have not defined it anywhere. - yes you have, in your code.

Don't cross post

Consider the following:
void printBook(const books &theBook)
{
    Serial.println("Name of the book is: ");
    Serial.println(theBook.name);
    Serial.println("author is: ");
    Serial.println(theBook.author);
    Serial.println("ID is: ");
    Serial.println(theBook.ID);
}

void loop()
{
    printBook(MyBook);
    printBook(YourBook);
}

You should appreciate this avoids the code duplication you have in your
example.

Why I get 62 for the sizeof(Mybook)?

30 bytes for name[30] (each char is one byte)
30 bytes for author[30]
2 bytes for ID (the AVRs have 16-bit ints)

No padding between the members because this architecture has no
alignment constraints.

Using Arrays-of-Parts (AoP) to represent a single item or "record" means that record's information is scattered among the AoP. When you need to do more than storing and listing 'N' records, that can get cumbersome and error-prone (as in: you miss one of the AoP when writing one of your routines). It also limits how you can allocate memory for the set of records.
Using an Array-of-Structs (AoS) only requires you to manipulate the one struct as a unit. If you move a record, all of its parts go with it. If you delete it, all of its parts get deleted. When you need more space, you only need to re-declare one array instead each of the individual parts arrays.
And one step up from an AoS is a Linked List of Structs (LLoS). Each record will contains one or more pointers (links) to some other record(s). Sorting then requires nothing more than writing some record's address into this record's link, and you've established a precedence. LLoS really shine when the records get large; writing a couple of pointers is way faster than copying 100 or more bytes. Same with deleting a record (call it "me"): change my predecessor's link-to-me to instead link to my successor, and Bang, done! I'm out of the list, there's no hole left as there would be with AoS or AoP, and my memory can be de-allocated, or I can be linked onto a different list.
Bottom line, arrays can get cumbersome when the data-set is large and and the records are complex. Structs gather a whole record together and allow more flexible manipulation.


text:
Cannot assign COM port to HC-05 bluetooth device
I can't set a COM port to my paired BT module. For better understanding I recorded a YouTube video to make sure I show everything.
Hardware:

Arduino Nano knock-off by RobotDyn (atmega168)
Bluetooth module HC-05 (zs-040) which looks like this
Windows 10 Home 64 bit on tablet

I have wired them up like this .
However, before that, I tried to wire it up without the resistors (so I hope I didn't damage anything).
Here is my very simple code which should just echo back what it get.
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available())
  {
    Serial.println(Serial.parseInt());
  }
  delay(100);
}

Hi Tomas, can you add details about your Windows? what version is it? and version of bluetooth adapter

@dpw I have Windows 10 Home 64 bit. It's a tablet and the BT adapter for the tablet is build in so I don't know any additional information about it.

I have exact the same problem.
Expect also to see a com port number after my device a MLT-B05 (clone of HC-05) is paired and (after fill in correct pass-code) is connected.
Did you see a you tube film for a correct assignment of the com port? I did everything the same as you did, but perhaps we are both wrong. Harry

Based on my experience, there is nothing wrong (yet) on the Arduino. You can check  this or this. Unlike previous windows version, Win 10 tend to "ignore" bluetooth connection, so you have to assign the COM port manually.

That's exactly what I did. However when I want to assign the COM port I have no device to choose from even though I can see it paired in the main BT window.

link Here is screenshot of the problem.

Ah, the same problem also occur to me. I don't know if there are any solution other than mine, which solved by using external bluetooth dongle. Turns out my build-in bluetooth adapter is not compatible with the bluetooth module (which is HC-05 and HC-06).

Well but my mobile phone also cannot communicate with the module. It seems to me pretty odd that the built-in BT cannot communicate with other BT devices.


text:
MQTT and IR code Raw
I want to upload/pubish RAW IR Code to MQTT server received through my ESP8266. I have received the following RAW IR code from the Television using the IR receiver sensor:
RAW IR CODE = {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450,
  650,500, 600,500, 600,500, 600,550, 550,1700, 550,
  1650, 600,1650, 550,550, 600,500, 600,550, 550,550,
  600,500, 600,550, 550,1650, 600,550, 550,550, 600,500,
  600,550, 550,550, 600,500, 600,1650, 600,500, 600,1650,
  550,1700, 550,1650, 600,1650, 550,1650, 600,1650, 600
}

I want to create a new variable with the following structure:
value = RAW IR CODE+";" + "ESP8266-01"(This is the ID of the esp8266)

value =  {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450, 650,500,
  600,500, 600,500, 600,550, 550,1700, 550,1650, 600,1650, 550,550,
  600,500, 600,550, 550,550, 600,500, 600,550, 550,1650, 600,550,
  550,550, 600,500, 600,550, 550,550, 600,500, 600,1650, 600,500,
  600,1650, 550,1700, 550,1650, 600,1650, 550,1650, 600,1650,
  600
}; ESP8266-01

I am unsure: which data type do I need to save the variable value so that it can later be retrieved/subscribed and sent to another IR sender using irsend.sendRaw, because I want to split the variable "value" into 2 parts after receiving it, the ID and the RAW code. After getting the RAW code, I want to use the irsend.sendRaw(RAW CODE, length of RAW , 38).
Could someone help me?
My attempts:
At first I tried to save it as a string, so that it can be retrieved and separated for irsend.sendRaw. However I am unable to compile it.
This is the code which I used to upload:
      /*
     * IRremoteESP8266: IRServer - MQTT IR server
     * An IR LED must be connected to ESP8266 RX port (GPIO-3)
     * An IR receiver to GPIO 0
     * used library:
     * https://github.com/markszabo/IRremoteESP8266
     */
    #include <WiFiClient.h>

   #include <ESP8266WiFi.h>

 #include <IRremoteESP8266.h>
    #include <PubSubClient.h>
    int RECV_PIN = 0; //an IR detector/demodulator is connected to GPIO pin 0

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    const char* ssid = "MY-SSID";
    const char* password = "MY-WIFI-PSK";

    const char* topicRaportPrefix = "esp8266/02/info/";
    const char* topicSubscribe = "esp8266/02/sender/#";
    const char* topicPrefix = "esp8266/02/";

    const char* mqtt_server = "10.10.10.10";
    const char* mqtt_user = "mqtt_user";
    const char* mqtt_pass = "mqtt_pass";

    String clientName; // MQTT client name
    char message_buff[100];

     void dump(decode_results *results) {
        const int count = results->rawlen;
          Serial.println(c);
          c++;
          Serial.println("For IR Remote ");
          for (int i = 1; i < count; i++) {

          if ((i % 2) == 1) {
            Serial.print("+");
            Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
        uint16_t  raw_ir_code[count] = results->rawbuf[i]*USECPERTICK;
            client.publish( "esp8266/02/sender", raw_ir_code);

After doing the changes proposed, I still get an error in compiling:

no matching function for call to 'PubSubClient::publish(const char [18], uint16_t [(int)count])'

Check the prototype for the publish() member function and cast the parameter to the expected type. Check that null terminated string is not assumed. In that case you will have to do the conversion. The member function should have at least three parameters to work; topic, data pointer, number of data bytes.

First create a topic and include the ESP8266 ID. Do not make it part of the published value.
Second publish the raw data as-is, uint16_t raw_ir_code[RAW_IR_CODE_MAX]. The alternative is to convert to string (characters). But if the subscriber has the same architecture (interpretation of data), there is no need to convert it to string and back. Simply publish the raw data as it is.
You will need to cast the raw_ir_code vector to the appropriate type for the MQTT publish call.
Cheers!

Could you explain how to retrieve the value from the mqtt server.

What library are you using?

Esp8266IRremote

And what library for MQTT?

No specific library but using the code for normal connection with Mqtt server.


text:
Update Variable via Arduino to Arduino I2C
I am attempting to send a simple 1 byte value from one arduino to another using I2C with the Wire library. From reading I see that this is typically done using the event monitor supplied by the Wire library, but this has caused problems for me because the handler function may only have one argument and it must be a void function or else the library throws errors during compilation. So I have a couple of questions about what is or is not possible with the Wire library short of modifying the source:

Should the Wire.available() function respond to attempted transmissions if the event handler referenced above does not exist? My first idea was to simply write my own function that would be called whenever this value is not 0, but it appears that this value never changes - unless the event handler is used.
Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments? Because recall from above that I cannot pass any arguments besides the one specified for the number of bytes received.

I cannot understand how this library could be useful for Arduino to Arduino communication if it is literally not possible to use the transmitted values anywhere other than inside of the event handler. My next step is start modifying the source to suit my needs, but I would imagine what I'm describing is a basic thing and would be shocked to find out that it's not possible without modification.

Why do you think it's not possible to use it elsewhere? What about global variables and volatile modifier?

One word: Scope. Google it.

I have thought about the volatile modifier, but I was under the impression that this simply means the variable can be changed by an interrupt which means the variable can change in the middle of an iteration of the main function. However, I do not believe this translates to a regular void function having access to that variable. Scope is exactly the problem here is it not? If I set variables using Wire.read() inside of the event handler (in the scope of that function) then how am I supposed to get those values into the scope of the main function without passing that function pointers?

I see now what the issue was. But to answer my questions:

Wire.available(); will not work if called outside of an event handler. I confirmed this while reading through the Wire.cpp source code and it explicitly states that the function should only be called from an event handler.
It is as simple as only a matter of updating global variables. I feel quite silly for not realizing that simply declaring variables outside of a function gives ANY function access to it rather than only the main function.

I see that the other answer mentions applying the volatile modification to the variables, but this is only necessary when the function in question is attached to an interrupt handler.

this is only necessary when the function in question is attached to an interrupt handler. - yes, which applies in your case. :)

Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments?

Yes, that's exactly what global variables are for. Make them volatile as they will be updated inside an ISR (or more exactly, a function called from an ISR).

authors: Максим Жуков


text:
Using a SPI based ADC (ADE7912) with Arduino
I'm trying to use Analog Devices' isolated ADC ADE7912 to build a native product for voltage and current sensing, using an Arduino as a microcontroller. The IC communicates with the Arduino using SPI (and SCK frequencies of 8,4,2 and 1 MHz), and I have followed the datasheet and written down some basic code using SPI-transactions and all, which seems to be giving correct results when I apply a positive voltage to the inputs of the ADC. I have two problems here:

When I try to display the SCLK, MISO and MOSI signals on an oscilloscope, the clock seems to have trouble maintaining its value (it becomes erratic and hence the SPI communication also misses some values etc.) Why is this happening?
When I apply a negative voltage to the ADC inputs, the IC does not really show any response to that even though it clearly supports negative voltage inputs to the ADC, as mentioned in the datasheet. This might be an IC related problem, but I am not sure.

Also, is there anyone who has built a library for this IC? Would be greatly obliged if they could share it.

As for the first question, what happens when you don't connect the oscilloscope? Cause sometimes (unlikely in this case, but who knows) the capacitance you add by connecting a probe changes the behavior. As for the second question, probably you'll need to post the schematic too

Please post screenshots of what you see on the oscilloscope -- that makes problems like this much easier to debug.

The Arduino drives the SCLK pin of the ADE7912, right?
I often find it much easier to debug problems if I can (at least temporarily) use a slower clock. The ADE7912 datasheet says it works at 250 kHz SCLK; can you program the Arduino to use that speed? (It is normal for the SCLK to run at the programmed frequency for 8 or 16 cycles, and then pause for long times; that kind of "erratic SCLK" is perfectly normal).

I have not written a full library, but I have recently been using the ADE7913 (same as ADE7912 but with an extra voltage channel) with an Arduino MEGA.
The basic sketch located here talks to the ADE7913 over SPI, and then prints the results of the measurement registers over serial (so you can see them using a serial monitor).
I have not yet done much measurement testing, so can't comment on the negative voltage issue you have seen, but the sketch sets up the ADE7913 to use the V2WV register for monitoring temperature, and converts the result into degrees C, so you should be able to tell if its working properly.
In terms of the issues you have been having with the SPI comms, I can offer the following suggestions based on my troubleshooting experience (I also had glitchy comms initially):

I'm pretty new to SPI, but my interpretation of the data-sheet is that the ADE791X chips use SPI_MODE3 (i.e. SCLK is normally high, and samples are read on the trailing clock edge). I have found SPI_MODE1 also works, but unless others can correct me would suggest using 3.
I found having physically long jumper wires (my prototyping is still on a bread-board) caused issues. I have read elsewhere that at frequencies in the ones of MHz, distances less than tens of meters shouldn't be an issue; but I shortened / tidied my wiring and it seemed to help.
I would run everything at lowest possible speeds to troubleshoot, i.e. set the ADC sampling rate to 1kHz (set CONFIG bits 5:4 to 11), and set the SCLK at 250kHz.
In the attached sketch, I am reading the register values based on an interrupt from the CLKOUT\!DREADY pin. You have to be careful that this reading routine takes less than one ADC sampling time to read all the registers. There is a good explanation of this timing constraint in Figure 8 of this application note. The attached sketch also reports some timing information over serial to help with this.

Hope that helps,

Khalid.

Just to update the note above, I have now tested over a range of positive and negative voltages (from +250mV to -250mV at the V1P pin) and confirmed excellent linearity over this range (within 1% is as good as I can say with the test equipment I have).


text:
AVRDUDE Error (Arduino Leonardo)
I, like many others, have encountered the avrdude error. However, I am not sure how to go about fixing mine after looking at numerous forums, etc.
avrdude: verification error, first mismatch at byte 0x0002
     0x74 != 0xe6
avrdude: verification error; content mismatch

I am simply trying to upload a simple sketch, but right when it seems it is about to finish, I get this error and the uploading loading bar simply never finishes...
Thanks for the help!

I had lots of issues when I first started.  these are all things I tried and at least one of them stopped this problem occurring, but I haven't a clue which.

Close the IDE (if you are using it and open it again)
Disconnect your board, wait 10 seconds and reconnect it.
Check you settings, are you using the correct board, etc.
Use a different cable.
Update your drivers.
Update your IDE/Toolset.
Use a different physical port on your PC.
Load the Blink example, if that doesn't work you serious have issues.
Reboot your PC.
If you can, try a different PC.

So I have tried all of those except for 5 and 6. I have a mac so I am not sure how to update my drivers since they were automatically downloaded.

Damn, always makes it more difficult when people have odd hardware platforms :).   Does it work when you try and upload blink?

I does not, gives me the same error actually.

Do you have a spare board?
Are you communicating via a 3rd party board (a USB to TTL device?)

I do have a spare board, another Arduino Leonardo that works just fine. It is only this one that for some reason has been giving me this error. And I am not sure what to do.

You can try to use your spare board to flash bootloader as ArduinoISP. It can be used to upload sketches too, but it is not so comfortable as direct upload. And if this doesn't work, you have some more serious problem.

I have a USB socket on the PC which causes the Arduino to lose track of its COM port although apparently Ok with other USB devices. Check your COM port before and after you try uploading.


text:
Stepper motor jittering
I'm trying to make a nema17 stepper motor work using ramps1.4 and A4988 driver.
But when I'm trying to rotate motor, it spins with almost no torque and constant shaking.

Motor 2-phase nema17 , Step Angle 1.8° .
Power supply 12v/60w.

Here is the sketch:
(I copied it from RepRap wiki , and removed everything except X Motor)
#define X_STEP_PIN         54
#define X_DIR_PIN          55
#define X_ENABLE_PIN       38

void setup()
{
  pinMode(X_STEP_PIN       , OUTPUT);
  pinMode(X_DIR_PIN        , OUTPUT);
  pinMode(X_ENABLE_PIN     , OUTPUT);
  digitalWrite(X_ENABLE_PIN, LOW);
}

void loop ()
{
  if (millis() % 10000 < 5000)
  {
    digitalWrite(X_DIR_PIN    , HIGH);
  }
  else
  {
    digitalWrite(X_DIR_PIN    , LOW);
  }

  digitalWrite(X_STEP_PIN     , HIGH);
  delay(1);
  digitalWrite(X_STEP_PIN     , LOW);
}

The wiring diagram:
(I have only X Motor plugged in)

and video: (Google Video link is dead @ 2017-02-09)

Does the stepper motor breakout have a potentiometer to set the maximum current?

Add a second delay after:
digitalWrite(X_STEP_PIN    , LOW);
Also try increasing the delay maybe you are pulsing the step pin too fast.

Nothing changed , it keeps doing the same , but slower .

Have you tried removing your if that control the dir pin?

You may also want to check your driver current: https://www.pololu.com/product/1182/faqs

If i remove if completely it is just shaking . If i remove  if , but leave digitalWrite(X_DIR_PIN    , HIGH); it keeps doing the same thing .

Yes , checked driver current limit , it is set to 700mA and motor has Rated current of 400mA .

And you did try with a different step motor and driver right ?

Yes i tried three different motors and two drivers but nothing changed .

How is your power connected to the arduino and driver board? Ground is common ?

And i also forgot to mention that copied code from RepRap wiki and just removed everything except X Motor . But original code does the same thing .
link

Yes ground is common , if i understand everything correctly .

According to the A4988 datasheet the driver requires 200ns setup time to read signals MS1, MS2, MS3, RESET and DIR, before the STEP signal can be set. Maybe all you need is delay(1) at the end of void setup(){}?

authors: Йордан Жечев


text:
Arduino Uno Digital to Analog Converter
I'm trying to read in an analog signal (a heartbeat) to pin A0 on the Arduino Uno and then convert it to digital. I'm hoping to use the digital signal to make an LED light up every time the voltage of the heartbeat signal goes over 1 volt. This is the code I have right now, but something is wrong because it isn't lighting up the LED.
unsigned int analog0;             // Raw data from A0 ranging from 0 to 1023
unsigned long data_range = 2000;  // Length of time to record data for
double volts;                     // The analog data from A0 converted to volts
int ledPin = 13;
unsigned long start_time;
unsigned long data_time;

void setup() {
  Serial.begin(9600);             // Initialize and set serial port baud rate
  pinMode(ledPin , OUTPUT);
}

void loop() {
  start_time = millis();
  while ((millis() - start_time) < data_range)
  {
    // Record current time of analog acquisition
    data_time = millis();

    // Record analog data on A0
    analog0 = analogRead(0);

    // Convert raw data into voltage
    volts = (analog0 / 1023.0) * 5;

    Serial.print(volts);
    Serial.println();

    // Slow the rate of data acquisition
    //delay(1);

    if (volts > 1.5){
      digitalWrite(ledPin, HIGH);
      //delay(50);
    }
    else{
      digitalWrite(ledPin, LOW);
    }
  }
}

Is it going over 1V?

Yes it is, the peak is around 1.2V on the oscilloscope.

I mean does the Arduino think it is going over 1V? And if the peak is 1.2V and you want to know if it is over 1V, why are you looking to see if it is over 1.5V?

We were just trying arbitrary values because nothing below that seemed to work, and whatever value we put there affects the voltage printed out to the serial monitor for some reason.

Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.
Edit: even better, you could try this for a faster response time:
void setup(){
  digitalWrite(13,0);
  pinMode(13, OUTPUT);
}

void loop(){
  if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
    digitalWrite(13,1);
    delay(100);
    digitalWrite(13,0);
  }
}

I think your voltage formula is wrong. Try this:
float volts = analog0 * (5.0 / 1023.0);

This it the same formula, just written differently.

@emilyf dis you try printing the raw value of analog0 ? Also maybe try a different analog input in case of A0 being bad ?

We did try to print the raw value of analog0 and it was jumping from 0 to 5 within a second. We figured out how to make the LED light up using a comparator op amp configuration by comparing our heartbeat signal to a 0.8V signal, and when the heartbeat signal was above 0.8 our LED lights up. Unfortunately we couldn't do it with the Arduino, but any suggestions about how to fix the code are welcome!

@emilyf just tried your code on an Arduino UNO exactly as you have put it and it works as expected.
My theory is either a blown ADC pin on your Arduino board or a miswiring.


text:
RadioHead library nrf24 sending and receiving struct data problem
I am using RadioHead library for the communication between nrf24l01.
I am sharing the snippet of my code below because the code is too huge.
The problem i am facing here is on the receiver side i am not be able see the data i am sending , it is showing squares and not the proper characters.
my output showing to me is :
name :?!
skill :
Sender Code :
struct DataHolder {
  String name;
  String skill;
};

DataHolder dh;

RH_NRF24 nrf24(10, 9);

//THIS METHOD I AM USING TO SEND DATA FROM SENDER NRF
void sendtonrf(){

 dh.name = "xyz";
 dh.skill = "classA";

 nrf24.send((uint8_t *)&dh, sizeof(dh));

}

receiver code:
struct DataHolder {
String name;
String skill;
};

 DataHolder dh;

 void loop{

 if (nrf24.available()) {

  uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

    if (nrf24.recv(buf, &len)) {

    String str1 = (((DataHolder*)buf))->name;
    String str2 = ((DataHolder*)buf)->skill;
    Serial.println("name :" + str1);
    Serial.println("skill :" + str2);

    }
 }
}

Your problem is that you are working with pointers.  You have a pointer to a block of memory with some text in it, then you take that pointer, get the address of the variable that stores it, convert it to a pointer to an 8-bit value, and send that.  Which of course won't work.
Instead you need to send the content of the memory the pointer points to:
nrf24.send((uint8_t *)strm, strlen(strm));

strm is already a pointer, you don't need to convert it to a pointer with & - that just confuses things and gives you a pointer to a pointer, which in this context is garbage.
A struct made up of String objects will not do what you think it does.  A String object does not contain the string itself. Instead it just allocates an external block of RAM (from the heap) using malloc() and holds a pointer to that memory. If you try transferring a struct which contains String objects all you will be sending is the data associated directly with those String objects, including the pointer to the string content, which is completely meaningless to the remote end.
Instead you will either have to send the strings separately along with their length and some identifier to say what the string is, or rebuild the string content into a fixed size buffer.
Personally I would use a fixed size buffer. In this method you change your struct so it contains two character arrays with a fixed size. For instance:
struct DataHolder {
    char name[10]; // Room for 9 characters + NULL
    char skill[10]; // Room for 9 characters + NULL
};

Then copy your string data into it:
struct DataHolder data;

strncpy(data.name, "Fred", 10); // Maximum 10 bytes
strncpy(data.skill, "ClassA", 10); // Again, max 10 bytes.

Now you can send the struct in its entirety:

nrf24.send((uint8_t *)&data, sizeof(struct DataHolder));

The data sent (and indeed the data held in the Arduino's RAM) will be:
Fred\0\?\?\?\?\?ClassA\0\?\?\?

Where \? represents any possible character (undefined, basically, and depends on how the variable was created - if it's global it'll be all 0, if it's on the stack then it will be whatever was in that block of memory beforehand) and \0 is the standard C end of string NULL character (ASCII 0).
For receiving it's exactly the same. Use the same struct, and go:
struct DataHolder data;

int len;
if (nrf24.recv((uint8_t *)&data, &len)) {
    // Do something with data.name and data.skill
}

Or you can use a buffer and a pointer, which may be safer since you have no chance of overrunning the buffer with a message coming in that is bigger than the data structure size:
struct DataHolder *data;
uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

if (nrf24.recv(buf, &len)) {
    data = (struct DataHolder *)buf;
    // Do something with data->name and data->skill
}

Note the change from . to -> for the struct access since it's now a pointer.
Also note that you don't want your struct to be any bigger than your maximum packet size. To send anything bigger you will have to chunk the data up and send it in little bits.

i changed it. but still getting the garbage but different this time.

Well, you're sending a String but trying to receive a struct. That's not going to work. You have to receive what you send. If you send the content of a character array you have to receive the content of a character array. BTW, a struct of String won't contain the String content, only the objects which don't themselves contain the string content, only a pointer to it.

hi . i cannot share the full code. but i have changed the code above.
Also i really appreciate for the quick response brother.
can you check the code again.
Also i am  very very new to arduino and c,c++ , where i can learn this casting and deep things.

If you want to use pointers, structs, casting, I advice to read a book about C. It does not have to be related to Arduino.

It is not an easy topic. It took me years to master the finer points.

I can agree, I'm a software engineer and still make mistakes with them.

wow. i am feeling so lucky today,
i really appreciate for the such big help
@Majenko : made my day.
i noticed a correction in receiver code.
u have used send command instead of recv.

Well spotted. Copy-and-paste error ;)


text:
Very Basic Arduino Uno Serial.readString() operation
I am very new to Arduino Programming.
I am trying to identify the input string from serial monitor and printing the output to the console accordingly
Code is :
void setup() {
       Serial.begin(9600);
}

void loop() {

   while (Serial.available() > 0 ) {

     String str = Serial.readString();

     if (str.equals("send")) {
        Serial.println("identified");
     } else {
        Serial.println("unknown");
     }

   }

}

Whenever i put send string it is showing "unknown" as the output, which is wrong, and i should get "identified" as the output.
Can anyone guide me here to achieve the result.
Note : I am getting output as i wanted by using readStringUntil function but the strings has a lot of "." in it, hence not useful.

what is your line end setting in Serial Monitor?

both NL and CR.

then check for "send/r/n"

send/r/n not working.

then print it to see. with print, not println

and the baud rate setting in Serial Monitor is 9600 baud?

i added Serial.print(str); below readString , in serial monitor it is showing the propper string whatever i am typing , but still no results.

Let us continue this discussion in chat.

You mean \r\n not /r/n...

@Majenko : tried that too. no result though.

The problem with relying on things like readString is you really don't know what they are doing or how they work. Parse the incoming data manually so you know what it is you are working with.

If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.substring(0) == "send\r\n"){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.indexOf("send") > -1){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}

There are any number of reasons the *.equals test is false. Consider case difference or extra characters introduced from the source of your communications.  Even non printable characters may pose a problem and cause the test to fail.
Consider using *.substring() instead.  This method will return true if the substring is found.  For example:
  String stringOne = "12345 send 1234";

  // substring(index) looks for the substring from the index position to the end:
  if (stringOne.substring(0) == "send")
  {
    Serial.println("identified");
  }
  else
  {
    Serial.println("unknown");
  }

...should always return "identified" because the characters 's', 'e', 'n' and 'd' are found in the correct sequence within the string stringOne.

String str = Serial.readString();
if (str.substring(0) == "send")
  Serial.println("identified");
else
  Serial.println("unknown");

this did not work even.

Odd.  Did you look at the linked to web page to make sure you were using substring correctly?  (This web page?).  Also, I see from the comments that you did print it out the received string and you did see "send" in the received message, correct?  You may just want to comment out the serial read line and try using "String str = "12345 send 1234";" to test if everything is working. Judging for other comments you might quickly try sending (typing in) "space"+"send"+"space" (" send ") to see if that works.

That won't work.  substring(n) just returns the portion of the string starting at position n.  So substring(0) just returns a copy of the string. str.substring(0,4) will return the frist 4 characters of the string  (assuming there at lest 4 chars to return - I'm not familiar enough with this implementation to know what it does for a shorter string - C# would throw an exception).

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

void loop() {
   char inChar[5];

   if(Serial.available() > 0 )
   {
     for (int i=0; i<5; i++)
     {
      inChar[i] = Serial.read();
      delay(10);
     }

     if (inChar[0] == 's' && inChar[1] == 'e' \
                          && inChar[2] == 'n' \
                          && inChar[3] == 'd')
         {
          Serial.println("identified");
         }

     else
     {
       Serial.println("unknown");
     }
  }
}

Reading the String "send" using Serial.readString() command is fine. But somehow it will not work if you use the result for comparing ( e.g data == "send" ...). A possible solution is to use character array (e.g inChar[5]). The size of the array is 1 more than the maximum characters needed.


text:
Thin battery to power arduino micro with nRF8001?
I'm building a project which needs to fit in a wallet. I have an Arduino Micro hooked up to a nRF8001. I attempted three button cells wired in series, which provided a solid 7.5 volts, but only 20mA.
A 9V battery successfully powers it, but that's too big to fit in a wallet. I was considering using an A27 battery, but even that's thicker than I would like.
Is there any battery I can use that's a reasonable thickness, and won't explode on me? Thanks!...

You'd probably be better off replacing both chips with an nrf51822 both running your code, and containing the radio.  Then you can run it on a single coin cell.

I think you should use a 3.7v mini battery that are around 200-300mAh capacity. These batteries are variable on online stores and are very thin. Now as you require 5v there are mini DC-DC boost converters available what you can use with them.

You can use rechargeable Ni-Cd batteries of 3 AAA size cells with wired connection.There are also small 4V rechargeable lead-acid batteries,which are mostly used in led torch.

I think the problem there would be 3xAAA are larger than a 9v battery so its probably going to cause more size issues.  Also NiCad is not good to have in your pocket where coins might be, in fact a I can't think of a battery that is good for use in a pocket without a proper case.

Either of these two are pretty good depending on how long you want it to live and how much current your device draws:
https://www.sparkfun.com/products/731
https://www.sparkfun.com/products/10718
You can still probably power the micro from these even though they're 3.7v. When charged they'll be closer to 4.2v and it will still probably run down to 3.5v anyway.
Or you could just put two in series to increase the voltage

Oof. Are these safe to keep in a wallet that I might fall asleep on? I feel like the heat and weight might be enough to cause one of those nasty lithium battery fires.

I've never had any problems with these batteries overheating in tight spaces. The heat will depend on hw much current you draw from the battery. It sounds like you won't need much.  Still though, I wouldn't suggest sleeping on it.

This is the same battery in smart watched and cellphones. If enclosed they are fine.

I run my projects directly from a 3v CR2032 lithium cell. Bypassing any voltage regulator. You could use something like a I'd get a 3.3v arduino, something like a Arduino Pro Mini. (You can also use your micro, but you'd have to "underclock" them, as the ATMega32u4 isn't necessarily capable of running 16Mhz at 3V.)
By bypassing the voltage regulator, you don't get any of the losses.

Will the button feels provide enough current for everything? The arduino and the nrf8001?

nRF8001 peak current is 12.5mA. Atmega will be around 5mA. Which seems to be fine for a CR2032. Note that you only have 240mAh of capacity.

So in other words, this would be a battery replacement every 12 hours. Fantastic.

That is just peak current. Nominal power is lower, and you can put them both into sleep mode most of the time (depending on your application).


text:
Stepper Motor Direction via Flow Amps
I have a problem with stepper motor direction.
I want to change the direction of the stepper motor rotation, when the stepper motor shaft is stuck.
For example, when I hold the shaft of the stepper motor with my hand, the direction should change.
How can I do it?
Someone told me you should calculate the current, but I don't know how to do this?
My material components:

Arduino
stepper motor gearbox 12 V
ULN 2003A

When motors stuck their current draw increases, you can sense that increase in the current (with any current sense method you see fit) and then change the rotation of the motor.

I now this discuss but I dont now how can I do it I have no idea circuit or cod for it can  you help me more ? i need it

in Face if you have seen the air conditioner splite Opereting system stepper motor it rotats the some way for 360 Degree but when shaft stuck the direction change I want do this

If you haven't any knowledge about electronics I'm afraid you will fail in that project. You first had to learn what current is, how current is measured ( over a shunt or by heating a wire or whatever). You possibly must compute a mean value. You had to learn how to use the right ground potential and so on. And there are issues with the current that is drawn by the stepper before each step to overcome the inertia of the rotor.  But if you're only supossed to change the direction of the rotation at a define location you could use a switch at that location. That's much easier.

I now about electrinics .but now a lot .but you Idea is very nice about swiching at that location but I have no any place for it I wnat works like air conditoner

I do not know anything about the design of your device. But there different possibilities to build a switch by yourself that, might fit in your design. For instance you sense a tiny LED, or a hall sensor and a magnet.

When motors stuck their current draw increases, you can sense that increase in the current and then change the rotation of the motor. The simplest way to measure current is with using a shunt resistor, for sensing high currents, current sensors based on hall effect sensors is usually used. ACS712 is one example.
How to sense current using a shunt?
Basically we're measuring the voltage drop over a resistor (RS), but the voltage drop is too small for Arduino to measure so we need an opamp to "amplify" the input:

simulate this circuit – Schematic created using CircuitLab
The schematic above is the simplest way to measure the voltage drop at "LOW SIDE", there is differential mode and "HIGH SIDE" measurement methods.
The gain of opamp can be set with resistors and this formula:
VOUT = (1 + R2/R1) * V1
The output of opamp then can be calculated to get current using ohm's law:
I = V / R
A simple code to calculate current:
int rawAnalog;
float voltageDrop;
int resistor = 0.1;
float current;

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

void loop() {
  rawAnalog = analogRead(A0); // Read A0 input
  voltageDrop = (rawAnalog * 5) / 1024; // Convert the raw value to voltage
  current = voltageDrop / resistor; // calculate the current
}

Bonus: INA219 is an easy to use high-side I2C module which can measure both current and voltage.

I good idea.can give a circuit for hall effect sensor ?the hall effect sensor must connect to uln 2003 or arduino pin for send commend

This would be a good solution if he uses a "normal" DC-Motor.  A Stepper has at least two groups of coils, each of them has its own plus and minus connection. And the current is not constant while stepping. It even gets more complicated if the stepper works with micro steps.

@PeterPaulKiefer he can measure the overall current at the power source, no need to measure group of coils...

Yes that's correct. You could measure the current the controller needs to supply the motor. But depending on the load there are high peaks. Controller IC can limit that current to protect themselves. If @Rayan_skofw had no experience which such things he/she get's easily frustrated. So I would suggest to him to use switches to check if the rotation is a a defined point and then invert the direction. Not the measuring is the problem, IMHO you can not easily distinguish between the normal stepper starts and the end condition if you only check the current.

@Rayan_skofw for ASC712 you just connect the module in series and there's a Library for it. (open the link there's a tutorial how to wire and use the ASC712).

Thanks all you guys. I want do it now what i learn here

@Rayan_skofw You're welcome, if the answer was helpful please click on that gray tik next to the answer to pick it as correct answer.

How much voltage drop would a shunt circuit like that cause? You spec'd a 100 megohm resistor, so it shouldn't be that bad. You'd need a pretty high powered resistor though.

Could you wire all the motor's coils to your current sensor through high current diodes, and just look for a peak current above some threshold?

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


text:
HC-SR04 and LCD Circuit Problem
I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#define trigPin 6
#define echoPin 7
int led5cm = 8;
int led7cm = 9;
int led10cm = 10;
int ledoor = 11; //ledoor means LED Out of Range
void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led5cm, OUTPUT);
  pinMode(led7cm, OUTPUT);
  pinMode(led10cm, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance <= 5)
  { lcd.println("Distance < 5 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, HIGH);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  } else if (distance >= 5 || distance <= 7) {
    lcd.println("Distance < 7 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, HIGH);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance >= 7 || distance <= 10) {
    lcd.println("Distance < 10 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, HIGH);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance > 10) {
    lcd.println("Out of Range");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
}

Can you please help me solve this problem? Thank you very much!!

All the code in a single line is unreadable. Properly format it. And I don't see any power connections or current limiting resistors for the LEDs.

I'm sorry, i maybe had mistake when pasteing the code.I will edit it.Yes, im forget to add the resistor in the schematic.Only in schematic.

Did you first check if distance was right using Serial.print

No, i'm using LCD screen.Not serial monitor.So, it will be lcd.print not Serial.print right?

gre_gor I double checked the code.The code are properly formated

You have this instantiator for LiquidCrystal_I2C:
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
Where did you get that? Which library exactly are you using? A common one I found only uses 3 values -- I2C Address, Columns, and Rows. What size is your LCD?

+jose can u c I'm using library written by F Malpartida.Link https://arduino-info.wikispaces.com/LCD-Blue-I2C

@deadguy88 I don't know what you are seeing, but this is not properly formatted.

That LCD library is intended for a module with the PCF8574* I2C IO expander. Please give more details about your LCD device.

@jose can u c Yes my LCD has PFC8574AT I2C IO.

Please show us more details about the I2C IO Expander on your LCD. Can you confirm that the pins on the IO Expander is connected to the pins set in your initialization call?
Basically, please re-write your question and/or schematic to show us more, as you have asked why the LCD doesn't display, but you have given nearly zero information about the LCD and how it's connected.
Also, you noted that the schematic omitted the pull-up resistors, but the only way we can help you is if what you tell us is accurate.

To make your LCD work, add code like the following in setup().  (Substitute appropriate values in place of LCDcols and LCDrows, or give them appropriate values via const int ... or enum { ... }; statements.)
  lcd.begin(LCDcols, LCDrows);
  lcd.setBacklightPin(3,POSITIVE); // Might not need this, since info appears to be included in lcd declaration
  lcd.setBacklight(HIGH);
  lcd.clear();          // Clear the display
  lcd.home();

To make the LEDs work better, you may need to change the || connectives in some of the if statements to &&.  An if condition with terms joined by ||, OR, is true if any of its terms are true; with terms joined by &&, AND, all of its terms must be true for the condition to be true.
For example, the condition (distance >= 5 || distance <= 7) is true if distance is 5 or more, or 7 or less; in other words, is always true.


text:
How to use while(1) loop in arduino?
I have been trying to exit from the while(1) loop by getting a value from the sensor and then run the code outside while(1).But the problem is that it does not exit. How may I fix this problem?
See Code Below.......
void setup() {
    pinMode(2,INPUT);
    Serial.begin(9600);
}

void loop() {
    int sensor;
    while(1)
    {
        sensor = digitalRead(2);
        if(sensor == 0)
        {
            Serial.println("inside while loop");
        }
        break;
    }
    Serial.println("Break......");
}

The while(1) loop executes once, every time loop() is called, printing or not, depending on the state of pin2. I would expect this code to print: either "inside while loop" (if pin 2 is false) or nothing, followed by "Break......"; over and over again. Is that what you're getting? Your question is incomplete. Please describe what you expected to see, and what you do see, on the terminal.

The loop function loops (is called repeatedly). Why do you put an indefinite loop inside a function that is called indefinitely?

In the Arduino paradigm, unlike ordinary C programming where there is only 1 entry point called "main()", there are 2 entry points called "setup()" and "loop()".  "setup()" is called only once after booting up.  But "loop()" is called over and over again right after "setup()" is called.  There is no need to create your own infinite loop (for example a "while(1)" statement) as in ordinary C programming.

Is there anyway to come out of while(1) loop inside void loop()

Sorry for the delay, holidays.  Yes, but most do not think this is good programming.  You can execute a 'break" inside the loop and exit the loop.   This Stackexchange question / answer goes into the details.

instead of while(1), one can use the variable name in while and change the value of the variable when you want to exit the loop. part of the code can be modified based on the following concept.
bool condition= true;
while(condition){
if (sensor==0)
condition=false;
This is my suggestion for the above problem.

Used like this
void setup() {
    pinMode(2,INPUT);
    Serial.begin(9600);
}

void loop() {
     bool cond = true;

int sensor;
while(cond)
{
    sensor = digitalRead(2);
    if(sensor == 0)
    {
        Serial.println("inside while loop");
    }
    cond = false;
}

  // like this you can used while inside the void loop()

}

Could you please add some explaination on how this solves the problem.


text:
Arduino Due SAM3X ADC programmable input offset not working
In the datasheet of the SAM3X8E in Section 43.6.9 Page 1327 it clearly states that the SAM3X/A has a programmable offset for ADC input in Single-Ended mode and I believe that the Atmel ASF library also has a function dedicated to configuring analog offset for SAM's ADC (adc_enable_channel_input_offset). However the following lines of code did not work:
  adc_set_writeprotect(ADC,0);
  adc_enable_anch(ADC);
  adc_disable_channel_differential_input(ADC, ADC_CHANNEL_5);
  adc_set_channel_input_gain(ADC, ADC_CHANNEL_5, ADC_GAINVALUE_2);
  adc_enable_channel_input_offset(ADC, ADC_CHANNEL_5);
  adc_set_writeprotect(ADC,1);

Why??

I have very similar question http://arduino.stackexchange.com/questions/32062/arduino-due-adc-gain-adjustment-problem but no answer, unfortunately.