text:
Convert Bitstring to Textstring
I have an Arduino Uno which is going to receive a long binary string.  I know that this string will correspond to English when decoded.  How can I convert the incoming binary string to text, so that I can read it in the Serial Monitor?
Bonus Points: This string will almost definitely have random noise digits.  How would I noise-proof the string, or how could I have the code detect and ignore noise?
UPDATE: It might help if I mention my end goal.  So I have this contained clean space that is locked up to avoid contamination.  It is quite small, and used for growing silicon crystals.  I want to be able to take a greyscale image every hour, and transmit it to a receiver on the other end of the room, through a window.  The window is two half inch panes of glass with an inch of space between them.  I have on hand 2x Arduino Uno, 1x Arduino Beetle, and 1x Raspberry Pi.  The whole text string thing is just for testing purposes so that I can understand what I'm doing.  From what I've read on the subject previously, I need to take the image, convert it to Hex, convert that to binary, transmit it, receive it, convert back to Hex, convert back to an image.  I have 0 experience with Arduino or Raspberry, have a limited idea of how to execute this, and appreciate all the help I can get!

Can you define 'binary string'? And can you explain 'read it in the serial monitor'? You want to receive it by RX or print it to the serial monitor? Or receive it by typing it in the serial monitor? You can noise-proof it by adding CRC data.

So, I'm using the transmitter and receiver pair from here.  The transmitter is transmitting the string corresponding to "Hello World", where the string is generated by converting each ASCII character into its 8-bit binary string.  The string received by the receiver ought to be one long line of binary generated by the conversion code, but with noise.  What I mean by "read into serial monitor" is that I want to decode it from binary back into "Hello World", and print it out to the serial monitor so that I can verify it worked.

Can you run a wire out of the clean space?  Eg, put camera inside, and wire to RPI outside?   ¶ If electronics are inside sealed space, is it at atmospheric pressure and room temperature?  Ordinary Arduino and RPI boards will outgas below atm.   ¶  Might also look into power line modulation to piggyback signals out of sealed space. ¶ If you have to use RF, put receiver a few inches from the transmitter and use wire to get the rest of the way across the room.   ¶ Can you transmit light through the glass?  Eg, put an LED on system inside space, and a phototransistor just outside, etc.

I cannot run a wire out.  We want to have complete containment, and not fiddle with making a hole in the setup, feeding a wire, and sealing the hole.  It will be standard Earth atmosphere and ranging from room temp to a really hot day (~95-100 F).  Due to equipment and room setup, the closest the receiver can be is 30'8".  Light cannot propagate through the glass.  I do like where your head is with using the LED as an Aldis lamp, but that won't work, because all receiver stuff needs to be at least 30'8" away from the containment unit, and that signal could easily be interrupted at such a range

Perhaps you have asked the wrong question. Because there is a library for those cheap 433MHz modules: RadioHead.
Use the RH_ASK mode, and try the 'ask' examples
You might see VirtualWire used a lot with those 433MHz modules. That is the same as RadioHead. The RadioHead is newer and has a few bugs fixed, but it uses also more memory.
The RadioHead library uses a far more superior protocol than anything else, that makes the range better than with other libraries. It also has a (simple) CRC checksum in the protocol. That means that when you receive something, you can be (almost 100%) sure that the data is correct.
Other protocols require that a message is transmitted 10 times, to be sure that it will be received. With the RadioHead library, sending a message just once is good enough.
Those cheap 433MHz modules have a disadvantage: they can only be turned on and off (ASK modulation) en you need a library for the protocol. That means that if the Arduino is doing more things that uses interrupts or code that disables interrupts, then the protocol is disturbed and it will not work very well.
The RF transceiver modules have a chip on the module itself that takes care of the protocol, that is so much better. Sparkfun has a Wireless Buying Guide and Adafruit uses the RFM69 a lot.
Those cheap modules require an antenna, or else the range could be less than the size of the table they are on. Solder a 16cm piece of wire to the antenna pin. Any piece of wire of any length is better than no antenna.

So, I'm actually using VirtualWire already.  I looked into using RadioHead, but I don't think that my project will allow me to have enough memory to use it.  My primary concern is space, because my final physical build needs to fit a theoretical space of 25mm X 25mm X 30mm.  I don't think I'd have room for an antenna, so I should look into a different transmitter.  I'm still not sure how to write a program to convert the incoming binary string to text (or in my case, Hexadecimal, then an image).

With VirtualWire or RadioHead you will receive the same bytes as what you have sent. There is no need to convert something. The typical data transfer rate for those cheap 433MHz modules is about 10 to 100 bytes per second. It is not for transmitting an image.

Oh, I thought they could do images.  Do you have any ideas on what would be the best method for transmitting an image at range?

A string is also a 8-bit 'binary' string ... so I don't think you need to do anything special... if you can read byte by byte, you might have to construct a string adding the characters, or print it directly to the serial monitor (last is even better because you don't have to think about memory).
If the 8-bit binary string does not contain ASCII data (which I doubt), print out the byte values as number and see how it should be converted to a textual character.
Noise is a bit more tricky .. afaik it is possible with some libraries (for the RF) to automatically resend. If that is not good enough, you have to make your own CRC ... calculate a CRC, send it (maybe a few times to be sure there is no noise in the CRC) and check it against the received string; if not received correctly, send it again.
If you have only 1 directional transmitting, than it is more tricky. You can add extra bits to 'fix' noise, or using special schemes for it.
See for more info wikipedia

So, would I just tell it to constantly receive data, and every eighth digit attempt to convert the 8-bit string to a char?

You will get bytes, not bits, and one byte is one character ... so the data you sent with the Wire library (or another) will be the same that you receive on the other end, assuming the connection quality is good enough.

you're welcome (please upvote if the answer helped you)

I did, but I'm <15 rep, so it doesn't show

No problem, you always can do it for all your answers you received when your reputation rises :-)


text:
Are the output pins on the 74HC595 shift register protected against shorting?
In the following schematic you can see that Q1 and Q4 both are connected to a Arduino's Digital Input Pin. So if Q1 is high and Q4 is low, would there be current flowing from Q1 through Q4 (and through the chip) to Ground - or is there already some protection inside?

Are the output pins on the 74HC595 shift register protected from connected voltages in the realms of their own VCC? Or do you need to put a diode in?

I feel like this is a very basic question, which makes it very weird that I didn't find an answer to this, already... :-( Am I looking into the wrong resources? I had a look into the provided datasheet, but couldn't find any information. Didn't get any results from searching for existing posts on Stack Exchange or other sites.

The technical term for the top illustration is "shorting outputs". Since the 595 doesn't have open collector outputs, the chip won't stand a short circuit between its output pins. Use diodes instead, for instance, as st2000 suggests.

In this data sheet it says:

When the output-enable (OE) input is high,the outputs are in the
  high-impedance state.

However on page 3 you will notice that the *OE pin controls all outputs at the same time.  So if you connect 2 output pins and one is high and the other is low and you hold *OE low ... you will likely burn out the driver for one of the 2 output pins if not the chip its self.
If you add diodes to BOTH outputs you are essentially creating a wired or gate.  (You should add a resistor.  See the examples in the provided link.) This is fine as long as you understand how a wired or gate works.

Thank you :-) However, this causes a follow-up question: under 10.2.2 in this datasheet it says "Outputs should not be pulled above VCC." I understood this as: outputs (in LOW) can be pulled up (for example by another output in HIGH) as long as it's not above VCC. If that's not what this sentence from the datasheet means, what does it mean then?

it means that when the output is in a high impedance state (OE pulled high) if you take the pin to a higher voltage than vcc you will damage the IC. if the OE pin is enabled and you try and drive it to any state other than the voltage its alreay at, you are creating a short and would also damage the IC.

@JamesKent Ah, of course... I forgot about OE, again. (It's always pulled LOW in my circuit.) So that makes sense now. Excellent. Thank you very much. :-)

source: Stack Exchange

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

sort: votes


text:
I want to control a single DC motor with an Arduino. Why would I use an Arduino motor shield as opposed to an H-circuit and a MOSFET?
I'm new to electronics. I'm trying to build something that will involve controlling the direction of rotation of a DC motor. A lot of online resources seem to recommend using an Arduino motor shield. But why shouldn't I just use some combination of an H-circuit (to control the direction of rotation) and a MOSFET (to switch power to the motor on and off)?

You can use the H-circuit (and even use it to switch the power on and off), nothing wrong with that, but you have the potential for more errors that way which is probably why the recommendations are to use a pre-built solution

I was just about to edit to my question to also ask if an H-bridge by itself would be enough. I just drew a little circuit diagram that made me think it would be. Thanks for your response.

Using a shield is more convenient since it should just work. Especially for beginners it is frustrating if things do not work as expected and debugging that takes some experience (which you don't have). You can always build your own MOSFET based circuit for that if you like at a later stage when you have more experience.

@Bimpelrekkie I hear what you're saying, but I don't see how using an H-bridge would be difficult (unless the H-bridge was malfunctioning somehow). Maybe I just don't know enough. Thanks for the warning.

Isn't the Arduino "motor shield" one or more H-bridges with drivers? In other words, your two choices are essentially identical. What do you see as the difference?

@DaveTweed Good question. What I see as the difference between an H-bridge and an Arduino motor shield may not be an accurate reflection of the actual differences between those two items. Here are the main differences I perceive (although I may be mistaken): cost, size, and complexity. The Arduino motor shields seem to me to be more expensive, larger, and more complex than an H-bridge. And I wonder what else might be different. If I'm wrong, or if I'm not considering something important, please help me to understand.

The heart of the Arduino Motor Shield is an L298 dual full bridge driver IC. It also has indicator LEDs, current sense amplifiers and a bunch of connectors that you might not need. If you don't need the extras and price is an issue then you could get a basic L298 driver board such as this:- http://www.ebay.com/itm/New-Dual-Channel-Motor-Driver-Shield-L298P-DC-Stepper-Driver-Board-For-Arduino-/292039557649?hash=item43feea0211:g:fRAAAOSwTuJYs4k3

@BruceAbbott - perhaps the original motor shield, but the newer better designs use FET drivers rather than the lossy, antiquated L298/L293.

Thank you @ChrisStratton and Bruce Abbott. I appreciate your discussion about the specific technology used in Arduino motor shields. I will look more into FET drivers.

@lostinthecloud - compare for example the Adafruit Motor Shield v2 to generic older bipolar designs from them, Arduino itself, etc.  This is particularly important if you plan to use batteries.

The major benefit to using a shield vs building the same circuit yourself is convenience. Assuming that your circuit is identical to the circuit on the shield then they should both work in an identical manner (barring any minor variations due to the quality of solder joints or circuit paths). The nice thing about the shield is it is almost plug and play. It has the same footprint as the Arduino and you don't have to design and assemble the circuit on a perf board. Generally, you will end up with fewer wire leads running around making for a cleaner assembly and easier prototyping.

Thank you for your response. I appreciate your points about convenience and fewer wire leads.

A Arduino motor shield is just a H-bridge (plus some other bits), but it's a H-bridge that works.
Drawing a H-bridge and a MOSFET is easy. Building one that works is much harder. Online resources recommend the shield because trying to walk someone through the development of a functional equivalent is complex.

Sure, but the fair comparison is to an H-bridge IC on a shield, and the same IC on a smaller generic or custom board.

Thank you @ChrisStratton for your comment that helps to clarify Heath's posted answer. I am very new to electronics and statements such as "an Arduino motor shield is just an H-bridge" have the potential to confuse me.

Heath's point is that building an H-bridge out of four discrete FETs (or less preferably bipolar transistors) is a lot harder to get right than using a bridge IC.  Generally one would only do it when trying to handle very high currents, or perhaps in a few cases of extremely high production volume if that looked cheapest.

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


text:
Arduino Ethernet shield cannot establish connection
I bought a Chipdot Ethernet shield from Amazon. It does not have any MAC address on it. I connected this shield to an Arduino Uno. I tried to run the DHCPAdressPrinter code from Ethernet library on it, using the default MAC address of this code. And Serial monitor shows

Failed to configure Ethernet using DHCP

I have tried all the MAC IDs one by one as suggested on reviews but nothing worked. Is there any way to configure or assign a MAC ID to the Ethernet shield? Or is there are any way to know the Ethernet shield's  MAC address?
Thanks in advance.

The W5100 chip doesn't have a mac address by itself. You can assign any mac address to it that you want. With Ethernet.begin(mac); you assign the mac address to the W5100 chip.
The official Arduino Ethernet shield comes with a paper with a unique mac address. That is a nice service, but that is just a number, the Ethernet shield hardware is without any mac address.
There has been complaints about wrong resistor values near the ethernet connector. Can you read the numbers on those resistors ? They should be labeled as "510" and not as "511" : Arduino forum about ethernet resistors.
The Ethernet Shield uses more power than most other shields, and the W5100 can get pretty hot. Do you have enough power ? Is the 5V pin still above 4.5V ?
It is possible that your router does not accept the old W5100.
If the resistors are okay, I suggest to try an example with both mac and ip: Ethernet.begin(mac, ip);

I have checked the resistor which has 4 pin and placed on backside of RJ45. This resistor labeled as "511". I also checked the voltage on 5V pin multi meter display shows 3.76 volt below 4.5 volt but the IC W5100 getting too much hot.

That means you have a shield with wrong resistor values. That link to the Arduino forum shows how to add resistors to get the desired value of 50 ohms, or else try to return the shield. The 3.76V is too low. Find a better usb cable or power the Arduino board with a power supply of 7.5V to the power barrel jack. The W5100 does get hot, often too hot to keep a finger on it. Others say that it is "normal", but I have added a heatsink to my W5100. Would you consider buying an Ethernet Shield with the new W5500 ? All you have to do is include ethernet2.h instead of ethernet.h in your sketch.

okay I will look how to change resistor to get desired value. It's not power supply problem.. Arduino uno giving correct voltage from it's 5V pin but whenever I attach this shield the voltage goes down to 3.76 volt. the temperature of W5100 is above normal but not too hot to touch it. still I have not decided to buy new shield.  have faced the same problem with your shield?

No, my Ethernet Shield has the good resistors. The Arduino 5V pin should still be near 5V when the Ethernet Shield is attached. It might work with 3.76V but that will be very unreliable. You really have to fix that. Perhaps the low voltage is the problem ! If your Ethernet cable is short and your router is not too picky, then the ethernet might work, even with the wrong resistors. In my project I have a DC-DC converter to power everything, so I have more than enough power.


text:
How can I know how far a button is pressed?
I want to make a system that can count coins. The problem that I know have is that I need a way to detect the size of the coin.
The idea that I have is a beam that becomes smaller if you a inject a coin. The size of the beam depends than on the size coin. See it as a button that you can press a little bit or very deep.
But how can I know far the button (beam) is pressed?

First of all, you should ask the question that needs to be asked. Now you are asking something else. Could you describe what it is about ? Perhaps with a drawing of the beam and the coins. Is a Coin Acceptor possible ? https://www.sparkfun.com/products/11719 Maybe a beam on one side and a number of light sensitive sensors in a single line on the other side.

The number of coin sizes is a finite number. I think you'd be better off with some coin sorter instead and manage to count coins in each receptacle.

You cannot, to all intents and purposes, know how far a normal button is pressed - they only signal on/off.  I think your analogy of beam===button is so flawed as to be useless.

Why don't you just weight the coins, yes putting muck on the coins, or fakes can defeat it, but so can damaged coins if you are measuring by size.

Following on from Mark's comment, I'm not convinced that you can measure the size of the beam, using a single optical (analogue) device - generally optical switches, like other switches, are binary, either on or off, and as such would use one of the Arduino's digital inputs.
The type of (hypothetical) button that you describe, taking a mechanical analogue (rather than your optical beam example), would require the use of an analogue input pin, and your "switch" would actually be a linear potentiometer, i.e. a slider, or lever, and the analogue input could then measure the input voltage, which would be proportional to the amount that the button (or lever) has been pressed (or moved). However, the usual linear potentiometer is not spring loaded, so the button would not really have the usual expected push button behaviour, unless, of course, you rigged up some sort of spring loaded button, with a long throw, mechanically connected to a linear potentiometer.
An analogue version of this sort of set up, as far as I am aware, does not exist for a optical solution.
What you could use is a series of optical digital (not analogue) switches (or a single light source and a series of receivers), arranged in a line (perpendicular to the base along which the coin is rolled along) in such a way that they can detect the size of the coin*. If the light is broken for a particular detector, then you know that the radius/size/width of the coin is at least the same as that detector's distance from the base.

These optical detectors are then connected to a series of digital inputs, i.e. D5, D6, D7 and D8, and a series of if statements would enable your code to determine the size of the coin.
Assuming that the broken light beam results in a low, then the pseudo code would be something like this:
if D5 = low & D6 = high
 then coin is a cent
if D5 = low & D6 = low & D7 is high
 then coin is a nickle
if D5 = low & D6 = low & D7 = low & D8 = high
 then coin is a dime
if D5 = low & D6 = low & D7 = low & D8 = low
 then coin is a quarter

Obviously you would need a trigger when to take the "snapshot" of the coin passing the detector at the correct time, when it is fully blocking the lights, and not just partially blocking the light beams (which could result in a false reading).

* I have just realised that this is exactly what Jot described in his comment.


text:
How to get different parsed JSON data?
In my recent project, I have to parse incoming JSON data in Arduino and I successfully did it. But it is only for one constant data string.
For example, if my incoming JSON string like:
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

And Arduino code for parsing this data is below:
#include <LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  while(Serial.available() || !begin) {
    char in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      response += (in);
    }
    if(in == '}') {
        break;
    }
    delay(1);
  }
  JsonObject& root = jsonBuffer.parseObject(response);
  String TPS = root["TPS"];
  String MAP = root["MAP"];
  String LOAD = root["LOAD"];
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print(MAP);
  lcd.setCursor(0, 1);
  lcd.print(LOAD);
}

Then the output looks like:
TPS  : 0.40
MAP  : 0.95
LOAD : 14

That's fine, but when the incoming JSON string changes, what should I do?
Suppose the incoming JSON string looks like:
{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

Because I have to handle both incoming JSON strings, I can't replace any part like:
  String LOAD = root["LOAD"];
  String RPM = root["RPM"];
  String INJECTION_TIME = root["INJECTION_TIME"];
  lcd.setCursor(0, 0);
  lcd.print(LOAD);
  lcd.setCursor(8, 0);
  lcd.print(RPM);
  lcd.setCursor(0, 1);
  lcd.print(INJECTION_TIME);

Instead of
  String TPS = root["TPS"];
  String MAP = root["MAP"];
  String LOAD = root["LOAD"];
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print(MAP);
  lcd.setCursor(0, 1);
  lcd.print(LOAD);

Any reason you don't just jsonBuffer.parse(Serial)?

@EdgarBonet Means? I can't understand what you mean? Is this catch Serial data and parse it? Something like that?

My question is: Why did you choose to not use jsonBuffer.parse(Serial)?

@EdgarBonet Actually, I have no idea about this sentence. This is the first time I see something like this means to use "Serial" directly and we can parse incoming string or data.

What kind of JSON do you expect to receive? Always an object with 3 key-value pairs of type string, but unknown key names?

@gre_gor As I mentioned above means an object with 3 key-value pairs of type string. There is no key name.

Finally got the solution. I'm using the extra key name.
So, my modified serial data string now looks like:
{"ActionOne":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}
{"ActionTwo":"TWO","LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

and so now using containsKey() function, just check which one is coming. If ActionOne is coming then according to that serial data we got. And If ActionTwo is coming then according to that serial data we got.
#include <LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false, finished;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;

  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        break;
      }
    }
    delay(1);
  }

  JsonObject& root = jsonBuffer.parseObject(response);

  const char* ActionOne = root["ActionOne"];
  const char* ActionTwo = root["ActionTwo"];

  if(root.containsKey("ActionOne"))
  {
    float TPS = root["TPS"];
    float MAP = root["MAP"];
    int LOAD = root["LOAD"];

    lcd.setCursor(0, 0);
    lcd.print(TPS);

    lcd.setCursor(8, 0);
    lcd.print(MAP);

    lcd.setCursor(0, 1);
    lcd.print(LOAD);
  }

  if(root.containsKey("ActionTwo"))
  {
    float LOAD = root["LOAD"];
    int RPM = root["RPM"];
    float INJECTION_TIME = root["INJECTION_TIME"];

    lcd.setCursor(0, 0);
    lcd.print(LOAD);

    lcd.setCursor(8, 0);
    lcd.print(RPM);

    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME);
  }
}

If you want to read 3 values of a object that you don't know the names of the key, you can use an iterator as shown in the ArduinoJson library's docs.
And as already mentioned in the comments, you can also replace all the serial reading code with just Serial passed into the jsonBuffer.parseObject function.
#include <LiquidCrystal.h>
#include <ArduinoJson.h>

const struct LCDPos {
  uint8_t x;
  uint8_t y;
} lcd_pos[] = {
  {0, 0},
  {8, 0},
  {0, 1},
};

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

void setup() {
  Serial.begin(115200);
  lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(Serial);
  if (root == JsonObject::invalid())
    return;

  uint8_t i = 0;
  for (JsonObject::iterator it = root.begin(); it != root.end() && i<(sizeof(lcd_pos)/sizeof(lcd_pos[0])); ++it, i++)
  {
    lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
    lcd.print(it->value.asString());
  }
}

You will need to make sure, that the values are sent in the order that you want them on your LCD.
EDIT:
I don't have an LCD screen, so I didn't test the code with an LCD, but the code that just dumps the parsed data back to serial works.
//#include <LiquidCrystal.h>
#include <ArduinoJson.h>

const struct LCDPos {
  uint8_t x;
  uint8_t y;
} lcd_pos[] = {
  {0, 0},
  {8, 0},
  {0, 1},
};

//LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

void setup() {
  Serial.begin(115200);
  //lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(Serial);
  if (root == JsonObject::invalid())
    return;

  Serial.println("JSON received");
  uint8_t i = 0;
  for (JsonObject::iterator it = root.begin(); it != root.end() && i < (sizeof(lcd_pos) / sizeof(lcd_pos[0])); ++it, i++)
  {
    //lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
    //lcd.print(it->value.asString());
    Serial.print(i);
    Serial.print(':');
    Serial.print(lcd_pos[i].x);
    Serial.print(',');
    Serial.print(lcd_pos[i].y);
    Serial.print(' ');
    Serial.println(it->value.asString());
  }
  Serial.println();
}

If I send
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

over the serial, it returns
JSON received
0:0,0 0.40
1:8,0 0.95
2:0,1 14

JSON received
0:0,0 2.40
1:8,0 4200
2:0,1 4.87

I tried out your code, but nothing is displaying on LCD.

I don't have an LCD, so I don't know why the LCD doesn't work, but the JSON parsing works.


text:
Reading force from an FSR in Newtons
I hope I'm in the right place to ask, I couldn't find anything so I ask here, please tell me if I missed some relative topic.
I was following this tutorial : https://learn.adafruit.com/force-sensitive-resistor-fsr/using-an-fsr#in-depth-code-for-analog-fsr-measurements
and the only difference is that I have a potentiometer instead of a 900K resistor. I put it to 14350 Ohms because it fits the tutorial just above the last one, on top of the same page.
So here is the thing : I want to know the force in Newtons but the values I end up with are clearly wrong. A medium touch on the FSR is already > 3 Newtons, and it changes a lot when I turn the potentiometer to a higher resistance (and changing the value of that pota in the code too) : same force applied, different value of that force on the screen.
I know nothing about elecs so I would also like to know more about this part :
// Use the two FSR guide graphs to approximate the force
if (fsrConductance <= 1000) {
  fsrForce = fsrConductance / 80;
  Serial.print("Force in Newtons: ");
  Serial.println(fsrForce);
} else {
  fsrForce = fsrConductance - 1000;
  fsrForce /= 30;
  Serial.print("Force in Newtons: ");
  Serial.println(fsrForce);
}

Where does the /80 and -1000 then /30 come from ? Why is it a different operation and not just only different values ?
I'm using the same FSR but with 3.3V. I have the same graph as this one : https://learn.adafruit.com/force-sensitive-resistor-fsr/overview#how-to-measure-force-slash-pressure-with-an-fsr
I would really appreciate clear and simple explanations. Thank you by advance !

Looking at the graph and assuming fsrConductance == Resistance on the graph, then if you say that the fsrConductance is 7000, according to the above you should get 200 Newtons force, but the graph says 100 so there is something not right.  Is there something outside the sample of code that modifies fsrConductance?

I haven't changed fsrConductance, it's still fsrConductance == 1000000; like in the tutorial. It's in order to have our value in microOhms and conductance = 1 / resistance.

i do my projekt and i think i have the same Problem of you, i just want to ask you, did u get it the solve for Reading force from an FSR in Newtons ???? thanks

Sparkfun also sells FSR's and they explain it better: "Use them to sense if it’s being squeezed, but you may not want to use it as a scale".
On that Sparkfun page is also a datasheet. It's inaccuracy is 25%, and that is only when the force is applied evenly. When someone presses it with a finger, the inaccuracy is 50% or more.
The quick-and-dirty calculation in the Adafruit example is just for fun, it is not serious measuring the force in Newton.
There are two different calculations, for 'fsrConductance' above and below 1000. When it is above 1000, the 1000 offset is substracted to start the calculation at zero. The difference in calculation is that for one the value is divided by 80 and in the other divided by 30. It's just a rough calculation to get some kind of force value.
To measure weight or force, you need a load cell.

Hmmm I see now, thank you, that explains a lot ! It sounds so easy and obvious written like this.


text:
Arduino micro not recognized
I have an Arduino micro for some time and everything always worked well. Today, when I was uploading a code on this board using Arduino IDE, I accidentally started the Arduino Board update and the upload failed. After a while I retried again and again and again but upload always failed. Now my PC doesn't recognize my board and, looking at Windows Device Manager, when I connect my board, appears this screen:

What should I do? Do I have to reflash bootloader?

You have a bad sketch installed. Press reset just before upload starts.

to expand on that, whats worked for me in the past is press and hold the reset button while the sketch compiles, and only release the reset button once the IDE is trying to upload. that way it should never get out of the bootloader, so should immediately upload the new sketch

I tried again and again resetting it before uploading, after uploading, during uploading, twice, keeping resetted,... but always the IDE says that the board is not connected. Every time I reset, the led blinks once but nothing happens. What should I do?  @Majenko

You may want to reinstall the bootloader - not to repair the bootloader, but to erase the sketch. A major drawback of the bootloader is that it has no proper manual way of forcing it to run.

Ok and what should I do? Thank you for your time!

Are you sure it is a "micro"? Can you show a photo or give a link to the board? When it is a board with a atmega32u4 microcontroller than a bad sketch can indeed lock it. For example sending a lot of data to the serial port without delay in the loop(). Pressing the reset button (and releasing it at the right time) needs some practice, it has to be at exactly the right time. If nothing helps then you could burn a new bootloader in it. I had to do that a couple of times with a bad sketch for a arduino leonardo, micro and pro micro. Use a programmer or arduino uno as isp to burn a new bootloader.

So I was facing this issue for the past few hours and this is how I managed to get it to work.
After reading similar issues on knockoff NANOS,  I downloaded and installed this as many knockoff NANOS uses a different Serial CHIPSET.
After that, on the IDE side, just press compile to ensure your code is good to go. And then when you hit upload, wait for it to finish compiling and the second it says UPLOADING, hit the reset button. It should upload now and be available in your COM port.

I had this issue a while back and in order to fix it as suggested above I had to re flash the boot loader using a 2nd Arduino as an ISP. I used this page as a guide:
https://schou.dk/linux/arduino/isp/
Before connecting the wiring I first updated the UNO with the "ArduinoISP" Sketch, connected the wiring, then flashed the boot loader.

Opps, just realised this was asked 1 year, 9 months ago... oh well hopefully someone finds it helpful

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


text:
More than 4 MCP23S17 on 1 SPI bus
I would like to use 7 MCP23S17 as output expanders on one SPI bus. Every IC has its own address from 0 to 6. The first MCP23S17 can be written with no problem. The second chip did not work properly. The CS pin of the MCP23S17 is set like at the all other 4 ICs.
Does anybody have experience with more then 4 MCP23S17 on SPI? Could anyone help?
#include <SPI.h>
#include <MCP23S17.h>

MCP A(0, 10);
MCP B(1, 8);
int d = 250;

void setup() {
  A.begin();
  B.begin();
  for (int k = 1; k <= 16; k++) {
    A.pinMode(k, OUTPUT);
    B.pinMode(k, OUTPUT);
  }
}

void loop() {
  //////////// ON THE LIGHT ONE BY ONE  FROM BEGGING
  for (int f = 1; f <= 16; f++) {
    A.digitalWrite(f, HIGH);
    delay(d );
  }
  for (int f = 1; f <= 16; f++) {
    B.digitalWrite(f, HIGH);
    delay(d );
  }
  ////////////  OFF THE LIGHT ONE BY ONE  FROM BEGINNIG
  for (int f = 1; f <= 16; f++) {
    A.digitalWrite(f, LOW);
    delay(d);
  }
  for (int f = 1; f <= 16; f++) {
    B.digitalWrite(f, LOW);
    delay(d);
  }
}

Perhaps you have a wiring, logic, or programming error in your address decoding.   Please edit your question to include a Minimal, Complete, and Verifiable example of code and a  circuit diagram.

view now sir my question

Which library are you using?

Also do you know how the address pins work?

Use my library. It had an example that does exactly what you want. https://github.com/MajenkoLibraries/MCP23S17

The diagram shows only one SS pin going to both chips.  Is that intentional?  If that's the case, then you only need to send things out once since all the chips will receive the same thing.

Have you got the Solution.
Ravi

 MCP A(0, 9);
 MCP B(1, 8);
 MCP C(2, 7);
 MCP D(3, 6);
 MCP E(4, 5);
 MCP F(5, 3);

CS on pin 10 is often used for Ethernet
CS on pin 4 is often used for SD

How is this supposed to solve the problem? As I can see, he is not using an Ethernet or an SD shield.

Hi gre_gor, adress and chipselect 6 time different...

Assuming that the adressing is correct and all the modules work fine individually, there are some things you can do:

try to disable the slave select of the modules that aren’t require to communicate at a certain time, there are examples for that
add a bit of code where you define chip select as an input for all but one and see if you can communicate with that one. Do that for all of them
remove MISO pin from all but one and see if you can communicate with that one. Do that for all of them
use a tri-state buffer through which you connect the MISO pin and use chip select for enabling the buffer. This buffer puts the MISO pin into a state of high impedance when a certain module is not used for communication and prevents fata from being lost


text:
Constructing my own serial command syntax to control arduino
I know this is a basic question, but as a hardware electronics guy and not a programmer I cannot seem to fathom how to do this - so any examples of code would be greatly appreciated:
I want the arduino to spit out some initialization chatter on startup - (ok, done easy).
Then I want it to listen for serial commands, they can all be same length if that helps but I want them to be strings. i.e. identifier followed by value
Command --- Result
PWR_TRUE --- Power on device
PWR_FLSE --- Power off device
REP_FREQ --- Print frequency over serial
SP000752 --- Set power value to 752
SP016675 --- Set power value to 16675
Obviously the commands are two types, the first two being booleans and then integers, but I cant seem to find any examples not working off a single ascii character value, which is useless to me. I need more information and then from the message be able to break it down into something the arduino does.
An example of how to import whole commands and either do something, and / or chop the command up to get the value out, would be most useful.
Many thanks in advance :)
EDIT/UPDATE:
I now seem to have found a solution thanks to Edgar as given in the comments. However I now have another question relating to updating the variables so as to effect the loop, as well as performing actions upon receipt of commands (which itself now works)
LINK HERE

There are several parts to this process: Collecting the input; locating the command and the argument (value), validating each of them (is there such a command? Is the value valid?); and finally, acting on the result. What part(s) are you having trouble with?

If you just want an example, you may take a look at this Simple Arduino command line interpreter.

Hi JRobert, sorry I missed the comments section... Essentially I have my output code for each relevant function done, and i currently have seperate arduinos doing about 8 small mundane tasks for a single item. Now I want to combine them and use software to send commands over serial to either update variables the arduino is using or command it to execute various pieces of code.
I will have a look at that Edgar, thank you

Edgar that program seems to do the trick nicely, will have a play and see if I can add my required commands :) - thank you

Hi Edgar, adapting your linked script worked well, I would mark it as the answer but I cant as its a comment - but thank you greatly! :)

as the answer below was deleted, I thought I would provide you with just the links to my post about how it works and the code: the blog is here: https://dannyelectronics.wordpress.com/2017/06/25/worlds-simplest-serial-display-pic16f/. the code is here: https://github.com/dannyf00/Serial-Display.

the piece you want to pay attention to is process(). Very briefly, it takes the serial input, if it is a valid data piece, it updates a circular buffer; if it is a valid command ('\n' or '\r'), it updates the display. Consult the post that has been deleted for more details. Best of luck.

Expanding on my comment... I wrote a simple command line interpreter
that you can use as a base, or an inspiration, for your own interpreter.
In order to not make a link-only answer, I will put here an annotated
and simplified version.
The incoming characters are handled by loop(). They are stored into a
static buffer until a carriage return (CR = '\r') is received. When
the CR is received:

the buffer is NUL-terminated in order to make it a proper C string
it is handed to the exec() function for interpretation
the variable storing the command length is reset to zero for the next
command

Here is the code:
while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;  // length of line received so far
    int data = Serial.read();
    if (data == '\r') {
        buffer[length] = '\0';     // properly terminate the string
        if (length) exec(buffer);  // give to interpreter
        length = 0;                // reset for next command
    } else if (length < BUF_LENGTH - 1) {
        buffer[length++] = data;   // buffer the incoming byte
    }
}

The exec() interpreter function uses strsep() to split the
command line into a command verb and subsequent parameters. It then
compares the command verb with all supported commands in a long if...
else if sequence, like this:
static void exec(char *cmdline)
{
    char *command = strsep(&cmdline, " ");

    if (strcmp(command, "mode") == 0) {
        int pin = atoi(strsep(&cmdline, " "));
        int mode = atoi(cmdline);
        pinMode(pin, mode);
    } else if (strcmp(command, "read") == 0) {
        int pin = atoi(cmdline);
        Serial.println(digitalRead(pin));
    } else if (strcmp(command, "write") == 0) {
        int pin = atoi(strsep(&cmdline, " "));
        int value = atoi(cmdline);
        digitalWrite(pin, value);
    } else {
        Serial.print(F("Error: Unknown command: "));
        Serial.println(command);
    }
}

This one supports the three commands:

mode <pin> <mode>, meaning pinMode()
read <pin>, meaning digitalRead()
write <pin> <value>, meaning digitalWrite()

The full version is here: Simple Arduino command line
interpreter. Compared to the version in this answer, the
main differences are:

it echoes the characters it reads, and does so in a way which is
friendly to terminal emulators:

it echoes CR as CRLF
it handles BS (backspace) and echoes it as BS + space + BS

it uses strcmp_P() instead of strcmp(), with the PSTR() macro,
in order to keep the constant strings in Flash only
it supports more commands, including "help".

You need to read the serial input into a string(char[]) or String.  You then need to parse that string to read a series of acceptable characters and then convert that into an action.
This is semi-pseudo code (not compiled, not tested, not complete)
bool quit = false;
const int MaxCommand = 10;
char command[MaxCommand];
while (!quit)
{
   int index[0];
   bool wholeCommand = false;
   bool invalidCommand = false;
   while (!wholeCommand && !invalidCommand)
   {
      while (!Serial.available())
        ;
      command[index++] = Serial.read();
      invalidCommand = CheckInvalidCommand();
      wholeCommand = CheckWholeCommand();
   }
   if (invalidCommand)
   {
      Serial.print("That's an invalid command");
   }
   else if (wholeCommand)
   {
      if (strcmp(wholeCommand, "PWR_TRUE") == 0) // 0 means it matches
      {
         power(true);
      }
      else if strcmp(wholeCommand, "PWR_TRUE") == 0) // 0 means it matches
      {
         power (false);
      }
   }
}

However That's the hard way to do it.  A much easier way is to utilities the user's CPU a bit more and get them to type data in a more computer friendly method.  After all users are easier to program, particularly with a base ball bat.
Make you language fixed length:

POWER TRUE |FALSE
REPOR FREQ
SETPW NUMBER

For instance use 5 letters for the command and then until the end of the line for arguments.
Probably the easiest way of manipulating strings for a newbie is to look at the String object class, but the C library string functions maybe the only way to truly get what you want (strcmp, strlen, strtok, strcpy, etc)

EDIT
If you are struggling to code something on the Arduino then what I do is try and knock it up on Visual Studio.  In this case you will need a simulated Serial object.
/// Code to simulate a Serial object on a Windows PC - Not Arduino code!!!
#pragma once
#include <afx.h>

class CSerial
{
public:
    CSerial () {}
    virtual ~CSerial () {}

    void begin (const int& baudRate) {}
    void flush (void) {}
    int available (void) {return 1;}
    unsigned char read (void) {return 42;}

    void print (const char* data) {_tprintf(L"%s", data);}
    void println (const char* data = NULL) {_tprintf(L"%s\n", data);}
    void print (const int& data) {_tprintf(L"%d", data);}
    void println (const int& data) {_tprintf(L"%d\n", data);}
};

static CSerial Serial = CSerial();

You will need to change read() and available() so that they return meaningful data.  You could do this be adding a char[] to the class that is prepopulated with data, such as "POWER TRUE\nREPOR FREQ\nPOWER FALSE" and then use an int as an index into that.

Not having much luck implementing it within my sketch yet, but thank you for the heads up, getting lots of errors to debug that are probably my own doing. The issue I cant get my head around is if i do not send the value with the command and have the arduino do the lifting, how does it know which variable its changing?
I want the arduino to monitor something as failsafe and update values over serial. I am trying to make it user friendly, but at the same time what seems to be a simple goal is becoming seemingly impossible to implement. :(

Read until you see the end of line character '\n' then parse the string you have read.  If the string doesn't contain a space then the command is invalid, ignore the line (show error?) and start reading again.  Is that what you mean?  It really isn't difficult (I appreciate it doesn't feel like that), it might be easier to do with pen and paper, write down what you want to do, break that down into small chunks and then implement each of those chunks as a function.  It will be easier to debug.

If you are on Windows, download visual studio from Microsoft and use that to code and test.  You will need to code a serial object that mocks/fakes the functions you require, but its not difficult.  See edited answer for a starting point.

Perhaps you should consider using https://github.com/j123b567/scpi-parser
It's an API library that allows you to build an 'instrument' that uses a recognized standard 'SCPI' as the communications protocol. It makes your device compliant with an industry standard, and can be implemented using tested code. Your example protocol is pretty SCPI-like already.

Thank you for the suggestion, something I should look into for sure. The code looks a little harder for me to disipher as a noob but I will try and work it out.
Do you happen to know if SCPI is mandatory or just good practice in industry? Thanks

It's far from mandatory; god knows I've had to deal with a a bunch of devices that use their own 'prtocol', and invariably, they are terrible. Probably simple for them to code, but far from simple to handle as an end user. To be able to simply say 'SCPI Compliant' will explain a lot to many people.

Is your device interface intended to interact with humans or with code? If you don't have to cater to human foibles such as forgiveness in commandline editing, it gets easier.


text:
Trigger countdown with 433MHz transmission
I would like to use an arduino to read 433 MHz transmission from multiple Soil Moisture Sensors. Since I can never be sure all transmissions reach the receiver I'd like to set a countdown from the moment the first transmission is received. If another transmission is received, the countdown starts again.
After a defined amount of time (e.g. 10 Minutes) without any more signals or if all signals have been received (e.g 4 Sensors) the receiving unit should stop and come to decision based on the data it got to the point.
For transmitting and receiving I am using the <RCSwitch.h>library.
The loop of the receiving unit and one Sensor looks like this:
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
void Setup(){
Serial.begin(9600);
mySwitch.enableReceive(4);
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();

if (value == 0) {
  lcd.clear();
  Serial.print("Unknown encoding");
  }
  else {
  Serial.print(mySwitch.getReceivedValue());
  Serial.print("%");
}

The full code includes some differentiation mechanism for all sensors but I figured that might not be relevant for my question.
Question:
What's the best way to do this without a real time clock module. As far as I know I can't wait by using delay(...)since then I won't receive any data while the processor waiting.

You say The full code includes some differentiation mechanism for all sensors so I'll assume there's some function GetSensorId() that returns 0 to NUM_SENSORS - 1.
So, you need to keep track of a) how many sensors have reported in and b) time since the last report. You can't just count how many sensors have reported in since there may be a chance one could report in more than once. So I would use an array:
// Assume you never receive 0 from sensor.
const int NO_DATA = 0;
const int NUM_SENSORS = 4;
int sensor_data[NUM_SENSORS];

void setup() {
    // Initialize array
    for (int i = 0; i < NUM_SENSORS; i++) {
        sensor_data[i] = NO_DATA;
    }
}

Also, a variable to keep track of time of last message:
uint32_t last_message_time = 0;

So, in loop():
void loop() {
    // Check for data
    if (mySwitch.available()) {
        int value = mySwitch.getReceivedValue();
        if (value == 0) {
            lcd.clear();
            Serial.print("Unknown encoding");
        }
        else {
           // Determine which sensor sent the data
           int sensor_id = GetSensorId();
           Serial.print(value);
           Serial.print("%");
           // Save the data and the time of the message
           sensor_data[id] = value;
           last_message_time = millis();
       }
    }
    // See if all sensors reported
    byte sensors_reported = 0;
    for (int i = 0; i < NUM_SENSORS; i++) {
        if (NO_DATA != sensor_data[i]) {
            sensors_reported += 1;
        }
    }

    // When 0 sensors have reported in, do nothing
    if (0 != sensors_reported) {
        // Otherwise, at least one sensor
        // check the time
        uint32_t elapsed = millis() - last_message_time;

        // If have all data or time's up, do something
        if (NUM_SENSORS == sensors_reported || elapsed > SENSOR_TIMEOUT) {
            // Do something

            // Reset state
            for (int i = 0; i < NUM_SENSORS; i++) {
                sensor_data[i] = NO_DATA;
            }
        }
    }
}

Sorry for the long delay .. it took me some time to try everything . It seems to work just the way i wanted. Thank you very much.


text:
Arduino Uno power input - is 5 V at 1 A enough?
I have a Arduino Uno board and phone power bank
Power bank details

Capacity - 8000 mWh
Input  - DC 5 V and 1 A
Output - DC 5 V and 1 A

Can I give the power to Arduino Uno using this power bank, through the Arduino Uno USB?

Already answered https://arduino.stackexchange.com/questions/39041/powering-an-arduino-with-more-than-5-v/39043#39043

I dont see why not - YES you can!
I regularly use usb powerbanks to power projects for testing. so long as you dont ask for too much current (unlikely but project specific) you will be fine!

Short answer:  Yes.
It depends on how you are feeding the power into the Uno and what you are trying to do with it.
My Unos use right at 0.35 amps, as measured by my USB volt/amp meter, until I begin adding things like DHT-22 temperature sensors and maybe a DS3231 RTC, then it will go up a bit.  I can generally just run from USB power.
Feeding power via USB is not a long-term solution in general, since most other USB sources are current-limited to 500 mA.  You could end up building a circuit that works fine on your power supply but not when running on just computer power.
Through testing using metered laboratory power supplies feeding into the barrel connector I am confident that 5V/1A is OK for light work.
And if you are POSITIVE that it is EXACTLY 5V then you can run it directly  into the 5V pin and avoid the regulator, which drops the voltage some.
(Of course, without the regulator you put the board at risk.)
Note that If you are trying to run an anemometer you need 9-12V for power for it.
Also, if you want to run a 432 MHz serial radio you will likely need more than 1A to make them work since they need a couple of hundred milliwatts just for the radio.  1A might work, but USB power certainly will not - (they won't even try to work with just USB power).
In any case, it sounds like you are set up nicely to fire the thing up and start programming.
Have fun!

Rendeverance , SDsolar    Thanks a lot for your information

By the way, the Uno has a really cool way of telling you if it needs more power - it quits working.  Ha!  But it won't hurt it to try.  1A should be good.


text:
How can I update global variable within a loop from outside the loop?
I have this code, but its not working. If I type "ReportFRQ 1" (or 0) it reports back that FrqON variable has changed but the behaviour of the loop doesnt. Basically I am trying to switch parts of the loop on and off using variables, which are updated by serial command.
The main body of the code was kindly provided by another answer as a way of commanding the arduino remotely with custom commands. I can get the arduino to do various things, but updating the behaviour of the loop by activating and deactivating different variables does not seem to work...
Any ideas? Thanks
#include <avr/pgmspace.h>
#include <FreqCounter.h>

#define BUF_LENGTH 128  /* Buffer for the incoming command. */

unsigned long int frq;
unsigned int frqON;

static bool do_echo = true;

/* Execute a complete command. */
static void exec(char *cmdline)
{
char *command = strsep(&cmdline, " ");

if (strcmp_P(command, PSTR("help")) == 0) {
    Serial.println(F(
        "echo <value>: set echo off (0) or on (1)\r\n"
        "freq: reports current frequency"
        ));
} else if (strcmp_P(command, PSTR("echo")) == 0) {
    do_echo = atoi(cmdline);
} else if (strcmp_P(command, PSTR("freq")) == 0) {
       FreqCounter::f_comp= 8 ;             // Set compensation to 12
       FreqCounter::start(10);            // Start counting with gatetime of 100ms
       while (FreqCounter::f_ready == 0)         // wait until counter ready
       frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
} else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);

} else {
    Serial.print(F("Error: Unknown command: "));
    Serial.println(command);
 }
 }

 void setup()
 {
Serial.begin(57600);
Serial.println("Frequency Counter");
}

void loop() {

/* Process incoming commands. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;

    int data = Serial.read();
    if (do_echo) Serial.write(data);
    if ((data == '\b' || data == '\177') && length) {  // BS and DEL
        length--;
        if (data == '\177') Serial.write('\b');
        Serial.write(" \b");
    }
    else if (data == '\r') {
        if (do_echo) Serial.write('\n');    // output CRLF
        buffer[length] = '\0';
        if (length) exec(buffer);
        length = 0;
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;
 }

 if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

    /* Whatever else needs to be done... */
 }

while (FreqCounter::f_ready == 0) If that is supposed to be a loop with no body you need while (FreqCounter::f_ready == 0); Or, to make it even more clear: while (FreqCounter::f_ready == 0) /* noop */; Either way, you need the semi-colon or empty braces: while (FreqCounter::f_ready == 0) {}

Sorry, can you please elaborate what effect that would have upon my code? If it can make it better obviously I want to but I would like to learn more - as this seems to work with the changes in the answer below... Thanks in advance

The next line frq=FreqCounter::f_freq; will get executed each iteration of the while loop - it will be the body of the while loop. In this case, there may be no side-effects, but that may not always be the case. Also, if the condition FreqCounter::f_ready returns true on the first iteration, that line will never be executed.

You have multiple problems here. First one:
You have a global variable:
unsigned int frqON;

However in your exec function you're creating a variable of the same name and writing to it. This doesn't change the global variable.
else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       //creates new local variable "frqOn" which overshadows global variable
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);
}

To solve this and change the global variable, simply omit the int decleration.
Also your if check is wrong:
if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

When you do if(frqOn = 1) you set the variable frqOn to 1. You however want to compare the values, i.e. use the comparison operator ==.

Many thanks for looking at my code - all fixed now thank you greatly!
I have taken onboard your tips and will apply them going forward (as I am only learning arduino, I am a hardware guy / engineer trying to branch out and digitise his projects)
Thanks again :)


text:
Using PWM signal to decrease power of laser over time
I'm trying to turn a laser on and off with an external button. When I press the button, the laser should turn on. When I release the button the laser should turn off. However, I don't want the laser to turn off immediately. I want it to turn off linearly over 500 ms. I'm using PWM to alter the strength of the laser over time. However, will my laser power increase and then decrease in the extremely short time segments due to PWM fluctuation? Will it even be able to execute this reduction of power?

I dont know your circuit but...
Do you effectively want to use an RC filter to reduce PWM fluxuations so that the laser sees an analog voltage which will translate to a power (presumably)? - that will avoid the pulsing of the laser, but I did believe that the pulsing at full voltage was neccersary in most laser drivers - please post a schematic... Anyway if you want this to be less of an issue if an RC filter is not for you you could increase the PWM frequency (google is your friend) on the arduino...
To have it turn of slowly if your using analog, the RC filter could possibly have large enough capacity to slow the laser turn off. It will also effect rise time so suitable values for R and C will need to be found to suit. Otherwise you could dial down the PWM gradually before hard power off in the arduino software, by initiating a loop which gradually reduces power with time.
Somewhere to start anyway :)

This is my code to gradually reduce power over time:
void loop() {
int stateButton = digitalRead(onButton);
if(onButton ==1){
digitalWrite(Laser, HIGH);

}
else{
for(int i = 255; i>=0; i--){
analogWrite(Laser, i);
  delay(500/255);
}

}           Would this loop through continuously? Would the power descend always loop through the descent even though I didn't press the power button?
}

Sorry my coding is not great so without formatting I find it hard to read your code.
I would do it differently myself, using an if statement which ran the pwm loop when you have activated its variable.


text:
How to select hardware for my Arduino board?
As I embark on my first Arduino project, I have lots of questions. Specifically, what considerations should I make when selecting equipment, and what are the critical parameters to safe operation?
Some elaboration upon my questions can be seen below. However, outlining general principals of equipment selection would be highly useful.
I have an Arduino Uno. The Uno has an input voltage of 6-20 V, and operating voltage of 5 V as from the tech specs. Does this mean that I can select any sensor with less than 20 V output to send data to my Arduino?
I am interested in using a sensor like this
 Texas Instruments HDC1080 High Accuracy Digital
Humidity Sensor, which has a supply of 5.5 V. If my logic is correct, this output should be fine. I should know whether or not I need to buy some sort of shield based purely upon the output pins of the sensor, correct? I know I have 6 analog and 6 PWM/digital pins on the Arduino, so the digital signal should be capable of being processed by my Arduino. However, the interface type on the sensor product is I2C, but I am unsure as to what this means or if it needs to be a consideration.

For sensors, display and other accesories, prefers those with I2C (TWI) interface. They make things easier, because all of them use the same pins A4 & A5, so you will never run out of pins.
Also, always look for 3.3v/5v compatibilidad, because things are moving to the 3.3v zone.

One question you have (3rd paragraph) brings a caution to mind. Your inputs to the Arduino are typically going to be 5v based, either digital or analog, although I may be phrasing this slightly loosely. A sensor not of the type you reference would provide a digital signal (Low/High relative to ground) or analog, which would be limited via external circuitry to 5v or lower. I think there's a good chance that if you find and use a sensor that pumps 20v into your Arduino, the smoke might be released.
I've read over the sensor you've linked. It was fascinating reading. It appears that the device is focused on being connected to a PC with USB and a Windows interface, but permits direct register access for specific data.
You'd want to research the best way to connect an i2c device to your Arduino, and I'm certain there are plenty of libraries for that. A good place to start is the reference on the "official" Arduino web site for i2c. This same page references use of the library, calling/polling the device and reading/writing data.
What I read in the volumes of the data sheets and user guides for the device you linked appears to cover everything you need to know and a tremendous amount of information you may not need.
It looks like a fun project and well engineered, at least from the sensor reference.

To be clear, you are saying that although the arduino specs say that my input voltage is up to 20 V, I really should stick to near 5?

Your input voltage for powering the Arduino may be as high as 20v, but the signals the unit can safely handle should be limited to 5v and there's a possibility that some devices will restrict this to 3.3v, but my brain cells are on hiatus at the moment and I'm not confident about the last statement. Excessive voltage to power the Arduino will also be shed as heat via the regulator circuit.

I think you are correct that some boards like the arduino pro have a smaller limit of 3.3v, but  what is input voltage supposed to mean if not the signal voltage that you can feed into the board?

One quick add here. I did a search for maximum power for Arduino and the search results return a maximum of 12v for the Arduino Uno. Most of the projects I've built have used either six or nine volts to power the board. Twelve volts may not create excessive heat, as the board is rated to handle that level.

"what is input voltage supposed to mean if not the signal voltage" The input voltage in this case refers only to the power supplied to the Arduino board for powering the MCU and will be regulated down to 5v. Excess power will be dissipated by the regulator as heat. From the point of view of the MCU, both its operating voltage and its input signals are expected to be 5v. (This is a slight simplification; the MCU could, on a differently designed board, be run at somewhat lower voltages.)

For your first project, power the Arduino Uno with the USB cable and use everything at 5V.
There are tutorials which guide you step-by-step to make something. The Adafruit tutorials are very good.
The HDC1080 is a sensor that works at 3.3V and at 5V. That means you can use it with the 5V Arduino Uno without problem.
This Tindie HDC1080 module points to a HDC1080 library on Github. I suggest you try to make that work.
If you can not get data out of the sensor, then you should start with something very simple. A few leds (with series resistors) or a LDR light sensor is fun to start with.
As soon as you start using higher voltages (for example 12V) you might consider buying a spare Arduino Uno, because the Arduino Uno will be blown when 12V touches one of the pins.
Be also careful with sensors that can only handle 3.3V and not 5V. Since the Arduino Uno runs at 5V, a pin of the Arduino could feed 5V into the sensor and damaging the 3.3V sensor.


text:
If this the way to generate a BEEP for a second
This buzzer needs to generate an audible sound for one second.  The Buzzer is inside a function that is called by a loop that continues to run. It is possible to stop the loop for this one second.  PWM to a piezo disk is what I had in mind.  The coding has been simplified to: Stating the PWM     // #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
  // set timer_0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
  // The prescaler is a 3-bit value stored in the three least significant bits of the Timer/Counter register: CS02, CS01, and CS00.
        TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
        //  TCCR0B = _BV(CS00) | _BV(CS01)
        //Register first 5 bits   B11111000  logical 'OR' Divisor  = B00000011   and stop is with: TCCR0B = 0;  Is that all that I need?      #include
      #include
      #include
      #include
      #include
      #include
      #include
    class TimingISR
    {
    public:
        TimingISR();
  char lead_char, unit_sec, tens_sec, num_min;
  int int_unit_sec, int_tens_sec, int_num_min;
  int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
  bool Colon, PointFlag;
  char data_char;
};

// these are all Clobal Variables
  int pin_Clk = 2; //  or 3 for IC2
  int pin_DIO = 3; //  or 2 for IC2
  int PIN_RELAY = 4;  // controls power on/off to 'cook'
  int PIN_Beeper = 5; // PWM beeps when finished
// Main() not included in this transmission, limit is 2 programs
// in case you recognize the above, I now have functions instead of GOTO's in the MAIN()
//*********************************************************************************
// http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/
// Arduino timer CTC interrupt example
// www.engblaze.com

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

//#define LEDPIN 2  will flash on & off once a second if a LED is used
Timer()
void setup()
{
    //pinMode(LEDPIN, OUTPUT);

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 15624;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

//*********************************************************************************
ISR(TIMER1_COMPA_vect)     // once a second code    Counting down,
   void){  // can only get here if lead_ char is a 'c' or a '1' i.e. 'cook' or 'def'

       If ( Colon = On ) Colon = OFF; else Colon = ON;  //blink
       // on TM1736 4 digit 7 second LED display
    {  if  ( Count_Seconds = 0 )  // Done cooking,  Beep On for one second
// https://arduino-info.wikispaces.com/Arduino-PWM-Frequency
       // set timer 0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
        TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
// https://electronics.stackexchange.com/questions/164834/stop-timer-set-new-value-and-start-again-avr-interrupt
        TCCR0B &= ~(0 << CS00);   // set the CS02, CS01, and CS00 bits in TCCR0B
        TCCR0B &= ~(0 << CS02);
        TCCR0B &= ~(0 << CS03);
        //Write 'DonE' to the TM1736
        lead_char = 'D';  num_min = 'o'; tens_sec =  'n'; unit_sec =  'E';
        Colon = OFF; brightness = 7;//  Full Brightness // for a few seconds
DisplayAll()  // Main() has a character to number converter  // DisplayAll() has an extended Segment table
    }
     {
      if  ( Count_Seconds = -1 ) //  Beep OFF
           TCCR0B &= ~(1 << CS00);   // // clear the CS02, CS01, and CS00 bits in TCCR0B
           TCCR0B &= ~(1 << CS02);
           TCCR0B &= ~(1 << CS03);
     }
       if (  Count_Seconds < -11 )  cli();          // disable global interrupts //stop the interrupt timer
return(0);
       else
          Count_Seconds = Count_Seconds - 1  // don't restart the timer
 { ( if   Count_Seconds < -10 || Count_Seconds > 0 )
          brightness = 4; counterValue = 0; resetCounter; Count_Seconds = Count_Seconds -1
 }
 }   End of Timer
// ----------------------------------------------------

Well, does it generate one or doesn't it?   It's unlikely to be the "best" way, but why ask the question without stating if it meets you expectation or not?

Please explain, in your question, why you think that this is the way to generate a beep, and why you are asking if it is (what are your doubts)? What does it actually do, and why have you done it this way? It certainly seems a pretty low level way of achieving your goal. If you provide some explanation in your question, you will probably get some upvotes, but as it stands it is just an impressive block of code, but with no description (apart from the comments. Did you write it yourself, or did you find it on the web?

What's wrong with digitalWrite(x,HIGH); delay(1000); digitalWrite(x,LOW); ?  This seems like using a sledgehammer to swat a fly.

-1 - I see that you have attempted to edit your question, yet managed to make it even more unintelligible. Please take the time to format it correctly, so that it is readable. Sorry, I am not being mean, but please learn how to correctly present your question, using the formatting tools available in markdown, instead of hoping someone else will format it for you.

You have pasted this code together from a couple of samples, I even recognise some of it, but I think you really don't understand what its doing.
If I want to learn how to fly a plane I am not just going to jump in the pilots chair and push the throttles wide open.  Its the same with learning to code, and if you try and run this code it will do nothing.
To answer you question, no.
Try doing something really simple and annoying and wire a buzzer up to one of the pins and load this code:
static const int BuzzerPin = 5;
void setup()
{
  pinMode(BuzzerPin, OUTPUT);
}
void loop ()
{
  digitalWrite (BuzzerPin, HIGH);
  delay (500);
  digitalWrite (BuzzerPin, LOW);
  delay(500);
}

Then once you work out how that works, move on to PWM to work out how that works and then finally try interrupts (if that's what you really want).
(Oh and yes the code is virtually blink.ino which you get with the IDE.)


text:
Would this substitute for an Interrupt timer?
class Pseudo_Interrupt {
  //only cummulative time is important, exact interval is not
  // Class Member Variables
  // These are initialized at startup
  long OffTime = 1000; // milliseconds of off-time
  // These maintain the current state
  unsigned long previousMillis; // will store last time updated

  void Update() {
    // check to see if it's time for an Interrupt
    unsigned long currentMillis = millis();
    if ((currentMillis - previousMillis >= OffTime) {
      //Time to execute the one second code
    }
  }
}

You are almost there. You have to set previousMillis to currentMillis (inside the if-statement) for the next interval. The previousMills and currentMillis must be unsigned long. The 'Offtime' can be a signed integer, or signed long, but if you make that a unsigned long as well, then everything is unsigned long which makes the code more clear and the compiler doesn't have to convert variables.

The whole idea is sound, but I would make a few changes:

as explained by Jot in a comment, you have to update previousMillis
inside the if statement. You have two choices:

set it to currentMillis, then OffTime will be the minimum time
between the pseudo-interrupts
increment it by a constant amount, which I would call period, then
this will be the average time between pseudo-interrupts; this is
more similar to how real timer interrupts work

add a constructor for:

making the period user-selectable
making the action of the timer user-selectable via a callback
initializing previousMillis

With those changes, the class will look like:
class Pseudo_Interrupt {
    unsigned long period;
    unsigned long previousMillis;
    void (*callback)();

public:
    Pseudo_Interrupt(void (*callback)(), unsigned long period)
        : period(period), previousMillis(millis()), callback(callback)
    { }

    void update()
    {
        if (millis() - previousMillis >= period)
        {
            callback();
            previousMillis += period;
        }
    }
};

For a steady period (increment previousMillis with a constant), it can create a burst, for example when setup takes a long time. In that case I set previousMillis to millis at the end of setup. It prevents a burst when the sketch starts and setup takes a long time.

Latest Version:  7/6/17
//--------------------------------------------------------
class Pseudo_Interrupt {

{   // These maintain the current state of the timer
public:
volatile unsigned long previousMillis;   // will store last time updated
volatile unsigned long lateMillis = 0;       // how late was it
volatile bool CallOneMinute = false; //facilitates while loops,
}
// to prevent a callback set previousMillis = millis(); periodically within the 'period'
// to start the callback set previousMillis = millis() - period; lateMillis = 0;
volatile unsigned long currentMillis;
static const unsigned long period = 1000;     // milliseconds of off-time delay
volatile unsigned long delta;
    void (*callback)();
public:
    Pseudo_Interrupt(void (*callback)(), unsigned long period)
        : period(period), previousMillis(millis()), callback(callback)
    { }

    void update()
    {       currentMillis = millis();
            CallOneMinute = false
            delta = currentMillis - previousMillis - period
        if (lateMillis + delta >= 0)
            lateMillis = delta;
            CallOneMinute = true
        {
            callback();   // with correction to keep net correct cumulative time
            previousMillis += ( period - lateMillis );
    }
};
//----------------------------------------------------------

Your test if (lateMillis + delta >= 0) is always true. The volatile keyword is useless here.

Yes, if you advance previous millis by 1000 once that comparison is true.
Setting previous millis to current millis is the wrong approach as it will accumulate timing errors.
edit:
here is a simple piece that hopefully will do what you are trying to do.
//pseudo timer isr
//return 1 if the timer overflows MYTMR_PR
uint8_t mytmr_ovf(void) {
    static uint32_t last_time=0;        //previous time
    uint32_t current_time;

    current_time = millis();            //take current time
    if (current_time - last_time >= MYTMR_PR) {
        last_time += MYTMR_PR;          //update last time
        return 1;                       //indicate overflow
    }
    return 0;                           //indicate no overflow
}

as I suggested earlier, the code is written so that the timer is long-term accurate.
Hope it helps.
edit 2: here is the above code running on a PIC24F, with MYTMR_PR set to 100 (=100ms)
//user loop
void loop(void) {
    //looping around
    if (mytmr_ovf()) digitalWrite(LED, !digitalRead(LED));   //flip the led
}

I'm guessing you typed this on a cell phone....

@dannyf, I just read the "only cummulative time is important, exact interval is not". You are right, increment with constant will make it work with the same accuracy as the crystal of the microcontroller/processor.

A function called by your program can do some, but not all, of what an interrupt function does. If you call it frequently enough, you can get timely execution of your "one second code". How frequently you must call it depends on how precisely an execution interval you need. That may require your mainline code to spend more time polling the timer than you can afford; it depends on your particular circumstances.
A true interrupt function will be called nearly immediately on the occurrence of whatever event is set to trigger it. Until then, no time will be taken from your mainline code.
Whether that is that is an effective substitute depends on your particular situation.
The code you supplied is not syntactically correct and does not compile. Nested functions are not include in C or C++, and in the 'if' statement, the parentheses are unbalanced.

Nested functions are not include in C or C++,... it is compiler specific.

Regardless, the code did not compile in the Arduino IDE.

that still doesn't make your original statement correct

No, it is not compiler specific; it is standards specific. Some compilers may implement extensions to the language. That does not make them part of the language.

I have since put the following in a continuous fast loop. When the program gets to it, it executes.   The one second is a little erratic, but the total cumulative is approximately correct.
long OffTime = 1000;     // milliseconds of off-time

// These maintain the current state of the timer
long previousMillis;   // will store last time updated
long lateMillis;       // how late was it

//----------------------------------------------------------------------

currentMillis = millis();     //correct for millis() overflow
if (currentMillis - previousMillis < 0 )
    currentMillis = currentMillis + 32768;
{
    if (currentMillis - previousMillis >= OffTime - lateMillis )

        // Assume the difference is longer than 1000 milliseconds
        // because the sample time will be late but not by much
        lateMillis = currentMillis - previousMillis - OffTime;

        // Thus, cumulative time is essentially correct
        //Time to execute the one second code here
        do some code
    else
        return;
    }
// ----------------------------------------------------
}  //  End Of Run Repeatedly

Your handling of the millis() overflow is misguided. You should just let it roll over through zero, and make all your timing variables unsigned. Actually, the way you avoided having to handle this in the code from your question was correct.


text:
Powering potientiometer/button with a digital pin
When I read articles/tutorials about the Arduino Uno, the potentiometer and button always get power from the 5 V pin instead of from digital pins.
May I know whether the two components above can be powered by digital pins?
What is the situation that the components must only get power from 5 V pin instead of digital pins?

First thing Digital I/Os are designed for operation not giving power to other devices. digital I/Os Fan out and source current is low(40mA) it's may not sufficient for all devices.  As per your question you can power button and some low power devices making that digital pin OUTPUT and HIGH pinMode (pin, OUTPUT) and digitalWrite (pin, HIGH)

You can likely use an I/O pin as an output to "power" fairly high-impedance devices such as pullup resistors for buttons, or even potentiometers of moderate to high total resistance.
A reason you might wish to do so would to be able to stop the device from draining power while the entire system is in a low-power sleep mode, or to otherwise disable it beyond merely ignoring its input.
However, it's worth noting that powering an analog device such as a potentiometer from an I/O pin is likely to inject noise and full scale voltage uncertainty into the signal so derived, as the output voltage under load may be neither the same as the supply rail, not "quiet".
And, of course, you must not attempt to use an I/O pin to power lower-impedance (aka more "power hungry") loads via an output pin.  Generally, active devices should not be powered in this way - especially ones such as radio transmitters, other microcontrollers or complex logic functions, ultrasonic transmitters, and definitely not motors, relays, or solenoids.


text:
Stable temperature sensor under voltage fluctuations
I'm looking for an inexpensive temperature sensor which is non reliant on the input voltage to return an analog reading back or some sort of digital signal. Accuracy is not very important, for instance +/- 4 C is fine. The lm35 I have been using jumps from 25 to 70 degrees regularly with changes in circuit load.
My other option is to add a separate voltage regulator, but I am trying to avoid that if possible! Thanks!

Switching to digital temperature sensors such as DHT22 or BMP sensors would be a great idea as output will be less fluctuated and it is often independent of minor fluctation.

The DS18B20 is a temperature sensor with a digital interface (1-Wire). It works at 3.3 to 5V and the cable length can be a number of meters. It is accurate to 0.5°C.
The DS18B20 is probably the most used temperature sensor for Arduino projects. Its price starts at less than a dollar/euro. You only need the DS18B20, a pullup resistor of 10k and a digital pin.
In the Arduino IDE, go to the Library Manager and search for 'onewire'. Install the "OneWire by Jim Studt, Tom Pollard, ... Paul Stoffregen, ...".
Then search for 'dallas' and install "DallasTemperature by Miles Burton, ...".
The OneWire library on its own can read the temperature of the DS18B20, but the DallasTemperature makes it easier to use.
Look for the examples of the DallasTemperature in the Arduino IDE to start with the DS18B20.
The 1-Wire is a bus, you can add more DS18B20 sensors to the same wire. The DallasTemperature library has two options. Select either a sensor by index, or by its ID. Every DS18B20 has a unique ID inside the sensor.
Sometimes an analog temperature sensor has specific advantages, for example a ntc temperature sensor or a thermocouple sensor. For normal indoor or outdoor usage, the digital temperature sensors are far more easier to use.
Why measure only the temperature ? If you want the baromic pressure and humidity as well, the BME280 has it all. Its temperature accuracy is not very accurate, it is only ±1°C.


text:
Fading red to white to blue continuous loop on ws2812 LED strip
I'm a big noob when it comes to writing a sketch and have set myself a task for an upcoming 4th July project, which has come to a halt.
I'm trying to set a strip of 30 LEDs to fade from red to white to blue through FastLED on a Wemos D1 mini. I also wanted it to flash each colour after the 3 colours have faded and continuously loop these.
I have searched many different forums and managed to get the fade to go from red to blue, but can't for love nor money add the white in-between.
Can someone point me in the right direction?
#include "FastLED.h"
#define NUM_LEDS 30
#define DATA_PIN D4
#define COLOUR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {

    FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

    //start from red
    for( int colorStep=0; colorStep <= 255; colorStep++ ) {

        int r = 255;
        int g = 0;
        int b = colorStep;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }

    //into blue
    for( int colorStep=255; colorStep >= 0; colorStep-- ) {

        int r = colorStep;
        int g = 0;
        int b = 255;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }
}

If you correct your spelling and add some punctuation, to make it easier to read, you may get an answer.

Also, post what code you have.

Have you managed to make it turn white on its own, no fading.

Here is a sketch i got and im unsure how to add the white although i can get it to white on its own using a sketch i found using rgb code.

not sure how to import sketch to this as im new but i edited my question sorry abut the font change

https://arduino.stackexchange.com/editing-help

Also check a FastLED example.

Thank you for your help i should be able to sort it now gre_gor much apreciated

Think of a color as a point in 3d as defined by its r g b attributes
Think of two points here, one is your starting color in that 3d space, and another your ending color.
Figure out the path you want to take from the starting color to the ending cokor.
Chop it up in a few steps and use your code to walk the path.
Done


text:
Arduino Mega 2560 with SIM808 module
I have a SIM808 module like this: https://www.banggood.com/SIM808-Module-GPS-GSM-GPRS-Quad-band-Development-Board-For-Arduino-p-1063106.html
The output header has 5 pins: GND/RX/GND/TX/VCC and I connected them as:
GND/VCC to a LiPo battery, 7.4V@1000mAh
RX->pin 14 (written on it TX3)
GND->to arduino GND
TX->pin 15 (written on it RX3)
and uploaded this code
#include <SoftwareSerial.h>

SoftwareSerial GSMSerial(15,14);    // RX, TX

void setup()
{

  GSMSerial.begin(19200);
  Serial.begin(19200);
  Serial.println("START");
}

void loop()
{
  if(Serial.available())
    GSMSerial.print((char)Serial.read());
  else  if(GSMSerial.available())
    Serial.print((char)GSMSerial.read());
}

But I'm not getting anything on it (when sending "AT" or anything else).
Any help is appreciated.
Thank you!

Don't use SoftwareSerial on the HardwareSerial pins.  Instead of this:
#include <SoftwareSerial.h>
SoftwareSerial GSMSerial(15,14);    // RX, TX

Just do this:
#define GSMSerial Serial3


text:
External ADC reading zero while input is zero
Using ADS1115 (or any other external ADC), how its possible to read zero instead of random floating values while no any signal at the ADC's input pin?
The ADS1115 is driven by an op-amp buffer as follows.

The op-amp's + input is sometimes connected to a pH sensor, sometimes left unconnected.

Signal is op-amp buffered pH sensor signal so its impedance is near by zero I think.

Ok. But what will going on when input is connected? I'm asking because I want to understand before trying.

You get the output impedance and the 10k in parallel, so if the output impedance is considerably lower than 10k then the 10k will have virtually no effect on the signal.

That's an interesting point - I assumed the poster was asking about when nothing was connected. @user30878,  could you clarify please? Are you asking how to get 0-readings when nothing is connected to the ADC, or are you saying you get fluctuating readings when you have the opamp connected but nothing connected to the op-amp inputs? (Or something else?)

Op-amp's output is always connected to ADC input but nothing connected to op-amp's input in my case. By fluctuate  I mean randomly floating values.

OK, then your problem is at the input to the op-amp. Please add a circuit diagram, including what's connected to the input of the op-amp, and then we can answer without guessing.

Simple op-amp configuration, non-inverting and unity gain mode (voltage follower).

Any input biasing? Please add a diagram.

Not any else component!  This is it http://www.electronics-tutorials.ws/opamp/opamp17.gif

The behaviour you are seeing is what happens when you have high-impedance inputs.  Basically, if you don't drive them, you get random values.
Unfortunately in your case, where the sensor you are using has no output current to speak of, I don't think there's anything you can do about this electronically.
You'll have to solve the problem in some other way if you really need to be able to disconnect the sensor.  A mechanical solution would be a connector which shorts when disconnected.  Switched headphone connectors do this, for example - when you pull out the jack, they make a connection so that the speakers can be switched on.

You mean 100 times larger resistor than sensor? It would be 100 mega Ohm then.

In fact I don't need to get zero. I just want to get rid off random values.

What is the ouput impedance of the pH sensor? I have no idea how they work...

It can be go to 1 tera ohm.

Yes. There is nothing added to this circuit. http://i395.photobucket.com/albums/pp34/teriyakithunder/pHprobe.jpg . Just the output goes to ADC input.


text:
Serial Monitor Stops Working
I am using a DIY colour sensor (RGB LED and LDR) and a servo to make a skittles sorter. I am testing out just the colour detection now and printing the RGB values to serial. It worked fine until I added servo code. Now it stops printing to serial after about 4 cycles. Not sure why this is happening. I have tried using other programs besides using the Arduino IDE but the same issue.
I am using a NodeMCU with Arduino code:

#define S0 4
#define S1 0
#define S2 2
#include <Servo.h>
Servo topServo;
int frequency = 0;

void setup() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  topServo.attach(14);
 Serial.begin(9600);
 Serial.print("Start");
}

void loop() {
  topServo.write(125);
  delay(500);

  for(int i = 150; i > 80; i--) {
    topServo.write(i);
    delay(5);
  }
  checkcolours();
  delay(500);
}
void checkcolours(){
 //RED
digitalWrite(S1,LOW);
digitalWrite(S2,LOW);
digitalWrite(S0,HIGH);
frequency = analogRead(17);
int R = frequency;
Serial.print("R= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.print("  ");
delay(100);

//GREEN
digitalWrite(S0,LOW);
digitalWrite(S2,LOW);
digitalWrite(S1,HIGH);
frequency = analogRead(17);
int G = frequency;
Serial.print("G= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.print("  ");
delay(100);

//BLUE
digitalWrite(S0,LOW);
digitalWrite(S1,LOW);
digitalWrite(S2,HIGH);
frequency = analogRead(17);
int B = frequency;
Serial.print("B= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.println("  ");
delay(100);
returnservo();
  }
void returnservo(){
  topServo.write(30);
}

Are you sure you want to use pin 0 for S1? it seems that is the RX from the serial

Oh I didn't know that. It is actually pin D2 on the NodeMCU which maps to pin 0 for the Arduino IDE, could this be the issue?

I'm not sure, but I think it's very easy to change the number and change the wire for a small test

Great, ill check and let you know! Thank you so much :)

(I don't promise anything, just an idea, otherwise I would put it as answer)

It didn't work, i even tried swapping usb cables and used a different PC.

I'm sorry ... I hope someone else has a good answer

Isn't there a set of GPIOnn constants that you could use?  I have had a look and I can't see anything obvious with you code.  It might make it easier to see if you wrote a function change (int s0, int s1, s2, char* name) and move all the writing code into it, so you called that three times rather than replicating the code.  i.e. change(LOW, LOW, HIGH, "B= ");

I had tried your code in my nodemcu and it works fine. did you check the error log when serial stops printing?

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


text:
SIM800C developer board "SIM not inserted"
I bought this SIM800C development board (vendor unknow):

I conected it to an Arduino and put a brand new SIM card in it. This is the model of SIM I'm using:

Problem is, development board doesn't detect SIM card:
at+cfun=1,1
OK
at+cpin?
+CME ERROR: SIM not inserted
at+csmins?
+CSMINS: 0,0

This is the scenario:

6 pin SIM in a 6 pin SIM card holder.
SIM works fine in a cel phone. Send/receive voice call/sms.
Older, working SIM from various providers doesn't get detected either.
Every other non-SIM related aspect works.
No reboots, no flickering.
Board takes care of regulating voltages and signal levels.

I put an oscilloscope probe on the SIM_VDD pin (against board ground) and got this on every power-on:

Two 1.8v and two 3v pulses. That's all.
Please, note that I have no access to all SIM connexions (multi layer PCB).
How do I solve this problem?

In this project I'm using a nodeMCU for green-house control and a SIM800C for remote access. This is very IoT to me.

And only people in the IoT field have real experience with SIM800C fails.

How are you powering the board?

You might ultimately have IoT plans, but your question has nothing to do with IoT.  And the idea that only IoT people have awareness of this is absurd beyond reason.

@TisteAndii. The board is powered with a 10V - 1.5A power supply. Yes, it is less than 2A, but I'm not transmitting or receiving anything.

Best you try with a 2A supply to rule out the possibility that your supply cant yield enough current. Maybe pass the 10V supply through a buck first. Your SIM looks like it was shut off from power after initial attempts to power it failed.

The print on the PCB and product description at sellers site states it is GSM/GPRS board. The  module on the board comes from SIMCom. This particular SIM800 module seems to have following capabilities as per SIMCom:

Compliant to GSM phase 2/2+
GPRS multi-slot class 12/10
Quad-band 850/900/1800/1900MHz

I think at the best you can only use a 2G SIM card on this board. Any 3G/4G SIM will not work.
Thanks for those images in the problem description, it gave me relevant keywords to search.

I tested with an old SIM (no 2G, 3G or 4G marking ), circa 2007, and same result.

According to several Internet sources, you can mix 2G/3G/4G SIM cards with 2G/3G/4G cel phones. I think the same apply to this board.

@LookAlterno, here's the generally supported combinations.
4G phone supports 4G/3G/2G SIM.
3G phones support 3G/2G SIM.
2G phones support only 2G SIMs.
Backward compatibility is the norm. The cellular modems are built to be backward compatible.

This is a hardware problem.
We have experience the same issue in the company I'm working for and after a short discussion with a SimCOM Engineer we conclude it was a soldering issue. The problem may lies in the PCB or inside the SimCOM module. In both cases some part/parts are not soldered or the solder contact is broken. If the problem is outside you may fix it by inspecting the parts. If it is inside the SimCOM module there are very little you can do with the usual tools.
Just to be clear I quote a little bit of the discussion
Original question to SimCOM:

A)We apply a zero pulse to PWR-key pin as you can see in the channel-1(yellow line)
and immediately the SIM800c module wakes up, the net and status led pins
become active (one led on the other blinks).

B) After a short time <1.5sec the SIM800c deploy a signal to SIM_VDD pin
(channel-2 - blue line)

Now in some boards the SIM_VDD pin goes to 1.8V as it appears in the
first of the 4 pulses and stay there. This situation is true if there is
a SIM card in the slot and the SIM800c is working properly. In that case
we can proceed and register to the network, send SMS etc...

In some boards though, as you can see in the screenshots, the SIM800
seams not to recognize the SIM card and tries again with 2 more pulses in
3V and one last one in 1.8V. The behavior is like there is no SIM-card in
the slot. Just to be clear. The SIM card is the same in all tests.
VBAT=3.9V, SIMVDD produced fine at 2.8V etc... The boards are identical
and no further code with AT commands is running.

Quite final answer from SimCOM:
It must be a soldering issue then. Did they followed recommended Solder
Reflow Profile?
https://www.elecrow.com/download/SIM800C_Hardware_Design_V1.02.pdf page 46

Please ask them where they measured signal from the scope pictures. From
the SIM card pins? If no, can they repeat that on them and send pictures.

This happened to me too with a SIM808 module on my own PCB. I would get those same 4 pulses on SIM_VDD and then nothing. I got the same +CME ERROR: SIM not inserted error with any AT command that had to do with the SIM card.
After futzing for wayyy too long, it turned out I had soldered the SIM slot on backwards! I am using the SIM8051-6-0-14-01-A holder and it has locating pins, but they're symmetrical. As a result, my SIM card was connected backwards and wasn't working.
Flipping it around fixed everything. Good luck!


text:
Trying to send serial data to computer over network from Arduino Yún
Using Console.write() to send data to my computer over network, which works when I use the serial monitor. However, I'm using PLX-DAQ to receive Serial communication and input it into an Excel document. The problem with that is that PLX-DAQ only has the option to listen over physical ports.
Is there a workaround to this?
If it helps, the computer is a Windows machine.

Do you have the data in the ATmega32U4 (Arduino Leonardo alike part) or in the OpenWrt linux part ? If you have the data in the ATmaga32U4, then connect it to a computer via a usb cable en use the Serial functions. There are usb cables of 10 meters long and they allow even that a few are concatenated. I don't know if a Windows serial driver exists that accepts  data transmitted by Console.write(). I doubt if the Arduino Yun is reliable enough for that. You could have two Arduino boards, one connected to the computer, and communication between them with RF or UDP.

I can send the data through a USB cable, but the whole point is to send the data over a network. Also, I'd prefer not to buy any extra hardware. Thank you though.

Perhaps some kind of "serial over IP" with a virtual serial port on the computer. But I have never used something like that.