text:
Arduino pro mini not compiling after changing fuse to 128khz
I used Arduino UNO as ISP to change the fuse setting of Arduino Pro Mini. Using avrdude cmd, I successfully changed it to 8MHz setting. Due to curiosity, I decided to try changing it to 128kHz. But that ends up me being unable to further program it. The Pro Mini still works but just cant change fuse through avrdude cmd, burn bootloader and upload. Does 128kHz really leave atmega328p like that?
On one computer, the below error appears.
avrdude: stk500_recv(): programmer is not responding

On another computer, the below error appears
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check
Wrong microcontroller found. Did you select the right board from the Tools > Board menu?

There are actually more errors because I trial and error different ways to solve it, i.e Nick Rammon's Atmega_Board_Programmer, cmd command with varying parameters (baud rate, programmer), inserting capacitor on UNO. But I dont remember every one of them because the not in sync:resp=0x.. differs from time to time
There is one method which I have not try, high voltage programming mode. I would try it out if it was detachable but atmega328p on Pro Mini is SMD. Is it possible to high voltage program on Pro Mini? Ultimately I am stuck.
Ignoring what I have done, I would once again like to try out every method you guys recommend. Hopefully everything can be step by step and the thing I want to know most is the setting of 'Board', 'Processor' and 'Programmer' in Tools.
I would give my best response possible to you guys who is willing to help me out. Thank you

Thanks to Ignacio, I found an answer. If anyone ever burn the fuse to 128kHz, got stuck there and wish to revert back to normal speed, download this sketch. Note that I am using Arduino UNO as ISP and Arduino Pro Mini as the target board
If you read the comment in the sketch carefully, you will see How to proceed:. The below is what I did.

Remove any pin connection on Arduino UNO
Plug Arduino UNO to PC
Open the downloaded sketch and uncomment #define LOW_SPEED
On Arduino IDE Tools menu, make sure settings are: Board: Arduino/Genuino UNO, Programmer: AVRISP mkII and upload the code
After uploading, unplug Arduino UNO from PC
Connect Pro Mini to UNO, making sure there is capacitor between reset and ground pin on UNO
Plug Arduino UNO to PC
Open CMD and type avrdude -P com5 -b 19200 -c avrisp -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDA:m -U efuse:w:0x05:m. Change com5 to your UNO com port. The fuse are default Pro Mini setting.
You should see avrdude: safemode: Fuses OK <E:05, H:DA, L:FF>. Unplug UNO from PC
Remove pin connection on Arduino UNO
Plug Arduino UNO to PC
Now comment #define LOW_SPEED and upload the code.
After uploading, unplug Arduino UNO from PC
Connect Pro Mini to UNO like before and plug to PC
On Arduino IDE Tools menu, make sure settings are: Board: Arduino Pro or Pro Mini, Atmega328 (5V, 16MHz),Programmer: Arduino as ISP
Burn Bootloader and it is complete

Apologies for lengthy and repetitive steps. Many solutions skip many steps which leaves me in doubt. So I do not want that to happen to other people. Though I won't go into the details of setting up avrdude CMD in step 8.

At that clock rate each programming clock cycle must be at least 3 system clock cycles, which means that the programmer either must use a much slower SPI rate, 42kHz or less, or it must provide an external pulse train to clock the device manually. Modify the ArduinoISP sketch to either use a slower clock or to provide an external clock to the target.

ArduinoISP sketch to slower clock: changing #define BAUDRATE 19200 to #define BAUDRATE 1200?
Is it possible to provide external clock to Arduino Pro Mini? If so, how should I connect it?

No clue. But that sounds like the speed it communicates with the host, not the target.

I have just used this code and upload to UNO with setting: Arduino/Genuino UNO,AVRISP mkII. Then I unplugged UNO from laptop, connected Pro Mini to UNO with capacitor connected, plugged to laptop and change setting to: Arduino Pro or Pro Mini,ATmega328 (5V, 16MHz),Arduino as ISP. Then I press Burn bootloader.
This error occur: avrdude: Device signature = 0x000000 avrdude: Yikes!  Invalid device signature.          Double check connections and try again, or use -F to override          this check.

i love you. from your tip, i found the code that slows down communication with target which i thought baudrate was the one.


text:
Arduino nano and wemos sd shield
Is it possible use Arduino nano with wemos sd shield? If I can, how to I connect sd shield to arduino and what modification I need to do on library setting?

What's a Wemos SD shield?

No, you can't. The WeMos boards operate at 3.3V, and so does the SD card. If you want to use a 5V Arduino with a 3.3V SD card, you'll need voltage level shifters.
The schematic of the WeMos SD shield will tell you what SD connections go to what pins. Then just google how to use an SD card with Arduino to connect those pins to the correct Arduino pins.

source: Stack Exchange

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

sort: votes


text:
How to load Image in Arduino?
In my recent project, I want to load Image in my Arduino. Is there any library available that can be used for loading Image in Arduino. Give some suggestion. Thank you!

You mean a picture? Sure: convert it to C source code and #include it. Gimp will export in C source format, or there's plenty of websites around that will convert an image for you if you ask Google. However: what are you trying to achieve? An Arduino isn't good at image processing!

Yes there is a library to load the image to Arduino called as "TFTLibrary".
Loads an image file from the SD card into a named instance of PImage. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. Images can be smaller or larger than the screen resolution (160x128), but there is no method on the Arduino for image manipulation. The images should be sized before you put them on the SD card. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. It is possible to load 24 bit bmp image only.
Syntax:
screen.loadImage(name);

Details available on Arduino website:
https://www.arduino.cc/en/Reference/TFTLoadImage

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


text:
How to connect a 5V submersible motor to Node MCU?
I connected the D1,D2 pins of the the Node MCU to the positive and negative of a 5V submersible motor. I wrote the following code, its getting uploaded without any errors but the motor is not working. I tested the condition of the motor by connecting to a battery,it does work.the code:
void setup() {
  // put your setup code here, to run once:
    pinMode(D1,OUTPUT);
pinMode(D2,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(D1,HIGH);
digitalWrite(D2,HIGH);
}

A diagram of how things are physically connected would be very helpful here.

all pins are PWM on ESPs... You need to switch the load with the GPIO; DON'T drive the motor from the outputs themselves. a relay or nchan mosfet would work well.

You need an appropriate motor drive circuit, and an appopriate power source.  Motor power should never pass through the MCU board, and a "9v battery" is only suited to unusually low current motors, and even then not at all economical.

I think you have got two issues here.
Firstly, as mentioned in the comments, you are driving the motor off the data pins so it will be getting less than 20mA which is almost certainly not enough to break the stall.  You need to use the digital pins to switch a MOSFET, transistor or relay (Electrical switch) and then that will switch on a larger supply directly from a "battery pack".  Have a Google for 'transistors' or 'relays' and see how they work, then you should get what I mean.
Secondly you seem to be using the pin names D1 and D2. There are a number of Node MCU boards out there but they all seem to have one thing in common and that is the pins labelled D1 and D2 on the board are generally not D1 and D2 in the code.
https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=924
If this is you board then unless you have a header file that does this for you, you should be using GPIO_5 and GPIO_4 for D1 and D2 (respectively).
Oh and the last thing, make sure you sub is leak proof :)


text:
Output 12-25V from Arduino Mega
I am currently building my first Arduino project : a car that you can control from your computer. I have my Arduino Mega that outputs 3.3 or 5V and my stepper that receives 12-25V, how can I make my Arduino digitally write something to that stepper?

https://www.arduino.cc/en/Reference/Stepper

Use an H-bridge motor driver. They can use arduino signals to control higher voltages without damaging the arduino. Check out the  L298N from gearbest. It's cheap but will probably do the trick if you're not using too much current.
It can supply about 1A through each gate at 5-30V.
this video should help explain it. (I haven't watched the video but it seems like it got good feedback).


text:
High Precision Temperature Sensor LMT70 connection to arduino mega
How can I connect an LMT70 temperature sensor (4Pins) to Arduino Mega board for atmospheric temperature measurement. LM35 sensor has got only 3 pins and connections are known. But LMT70 high precision sensor got 4 pins. How to connect it to arduino mega board
Please help.
Thank you.

Every electronics component has a document that describes it. It is called a "datasheet".
This is the page for the LMT70: ti.com LMT70
The red text is for the datasheet as pdf document, or else you can use the tab "Online datasheet", and the datasheet can also be found under the tab "Technical documents".
According to the datasheet it works with 5V, you can use it with the Arduino Mega (which is a 5V Arduino board). Connect the analog output of the sensor to an analog input of the Arduino Mega.
If you don't use the T_ON, then the datasheets says: "Tie this pin to VDD if not used". That means you can connect T_ON to 5V.
Do you have the chip (the sensor) only, or do you have a module with the sensor on it ?
Since the sensor has an anlog output, the accuracy depends not only on the sensor but also on the Arduino and the Arduino voltage reference. If you need a highly accurate temperature measurement, then you better buy a digital temperature sensor. For example the Si7051.
I suggest to use the 2.56V Internal Analog Voltage Reference.
The sensor has 1375.2mV output at -55°C and 302.8mV at 150°C.
const float aref = 2.56;  // adjust it to the actual AREF voltage
int adc_value = analogRead(A0);
float voltage = float(adc_value) * aref / 1024.0;

float t1 = voltage - 302.8;  // get rid of voltage offset
float t2 = t1 * (150.0 + 55.0) / (1375.2 - 302.8); // match range
float temperature = 150 - t2;  // negate and offset.

When you measure the AREF pin with a good multimeter and fill in the correct voltage in the calculation in the sketch, then you can get 1°C accuracy for the temperature. Perhaps you can get near 0.5°C accuracy, but no more. The sensor is more accurate than the Arduino Mega.

In situations like this, you always start with reading the device datasheet, understand how it works, how to communicate with the device, and then write your code to implement that communications protocol.
That strategy always works, regardless of the specifics of a given device.


text:
Arduino acts odd when disconnected from computer
I'm building an self-navigating robot with an arduino, an ultrasonic sensor, and two DC motors. I'm currently within the process of coding the robot but I've discovered I have an unusual problem; whenever I run the project via the USB cable operations run fine, however once I take the cable out and run the system on batteries alone performance diminishes.
I have checked the code thoroughly, however I don't understand how this could be an issue that's coding related. I also (as part of the testing) built a basic program which only operated the motors, and was able to run this via USB and via batteries alone with no difference in performance.
So what possible reasons could there be for a drop in performance? I have included a link to a youtube video I had taken of it earlier below to maybe give a better understanding of how performance diminishes:
https://youtu.be/Tp5LtOKBKHw
(Also it could be important to note if I take the cable out while motors are currently moving performance stays at where it should be)
Thanks!

Can you show us the sketch you are using? Are you using Serial to write to the serial monitor?

What are you using to power the board? Looking at the video, it looks like the motors are using more current than the batteries can supply, which causes the voltage to drop, which causes the arduino to reset (brown-out reset). You can see the following sequence in the video: Arduino turns on motor; voltage drops and Arduino resets (motors also turn off); Arduino bootloader does it's 3 second timeout; and the again start the motor, etc. etc. PS Starting a motor takes more current than when it's running. That is probably why unplugging the USB doesn't immediately reset the Arduino.

Ahhh I see, so that's why it's fine when it's running but it can't get started! A brownout makes a lot of sense, thanks. The motors are being powered by 4 AA batteries connected in series, these batteries also power the arduino so I might swap in a 9V battery for the arduino and see if that impacts it

Yeah, 6V is barely enough to power the Arduino voltage regulator. 7.5V or 9V would be better. If the voltage droops at all at 6V the Arduino’s regulator doesn’t have enough to work with. Using a separate 9V battery connected to the Arduino’s barrel connector would be a good idea.

The recommended minimum to the voltage regulator is 7V, so 6V is already lower than you want to go.

What seems is that you are facing an power shortage while working with on board power supply.
While running DC motors and Arduino on same battery set your Arduino is not getting enough power.
Try switching to a better power supply which can maintain a constant EMF, as eventually you'll always run out of power.
Try an adaptor to use wall socket current.
This way you'll not lose any functionality of Arduino project.

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


text:
Can the TimedAction library be used to call functions of an object
Currently to use TimedAction for a function a program would look like so:
#include <TimedAction.h>
void functionX();
TimedAction funtionTimed = TimedAction(1000, functionX);

void setup()
{

}

void loop()
{
functionTimed.check();
}

void functionX()
{
 //run function
}

My question is say I have an object class with some functions I would like to use with this TimedAction library. How would this be written?

You can't. The TimedAction class doesn't support the function prototype required for your undefined class (it has to match your class, so can't be written).
You have to call a normal function which then calls the class function, or you have to have your class function as static so it doesn't include the class in the function prototype.
class foo {
    public:
        static void runMe() {
            // blah blah
        }
};

TimedAction funtionTimed = TimedAction(1000, foo::runMe);

However, TimedAction is pretty simplistic and you don't really need it.  You can just write a function to only run every so often:
class foo {
    private:
        uint32_t _runMeTimestamp;
    public:
        void runMe() {
            if (millis() - _runMeTimestamp < 1000) return;
            _runMeTimestamp = millis();
            // blah blah
        }
};

foo myFoo;

void loop() {
    myFoo.runMe();
}

Those two lines of code, plus a variable to store the timestamp in, are all you need to make a function run at periodic intervals.

Thanks, yes I had been using it to call a normal function which then calls the class function, was just curious if I could reduce redundancy

Protip: You can re-write the library to use std::function instead of raw function pointers. You can then use lambda expressions or std::bind to call into a member function of a particular object. This would be the C++ way to do it.

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


text:
Using the TimedAction library
I need to make use of the TimedAction library for a project. The Arduino website gave an example of how to use this library which you can see here:
#include <TimedAction.h>

//this initializes a TimedAction class that will change the state of an LED every second.
TimedAction timedAction = TimedAction(1000,blink);

//pin / state variables
#define ledPin 13
boolean ledState = false;

void setup(){
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,ledState);
}

void loop(){
timedAction.check();
}

void blink(){
ledState ? ledState=false : ledState=true;
digitalWrite(ledPin,ledState);
}

This example however does not work, the Arduino ide gives back an error stating that the blink function is declared outside the scope. What is the correct way to implement this?

try moving the void blink() function code to before the timedAction declaration

Or try adding void blink(); right before TimedAction timedAction = TimedAction(1000,blink);

Ahhh, that's all it took to work! Thank you, I feel like such a fool for not thinking of that!

you can use ledState = not ledState; or ledState =  ! ledState;  instead of ledState ? ledState=false : ledState=true;   ....  the compiler prduces the same code for all three, i think

@Gerben care to convert your comment to an answer? Some additional information: The above code did compile in Arduino IDE 1.6.5-r5 and older but with the change to the arduino-builder tool in 1.6.6 the automatic function prototype generation inserts the blink prototype in the wrong place (https://github.com/arduino/arduino-builder/issues/50).

Regular C programs require putting the function declaration before the place you are using it. Arduino does this for you. Except in this case, where it doesn’t place it high enough. No need to feel bad. It’s Arduino that is trying to be clever, but fails.


text:
function returning String-Array
i'm still new to arduino and also to C++ and have a short question.
What i want to do is to write a function (in my case to parse the query-string of an URL) to get the parameter names and values (varying number of parameters).
My function looks like the following:
String function readParams()
{
   String params[x]; // x: number of params

   // fill params[0]... params[x] with parameter names

   return params;
}

void loop()
{
   // do some stuff

   String params[x] = readParams();

   for(int i=0; i < x; i++)
   {
      debug(params[i]);
   }
}

What is the correct return-type for the readParams() function in this case?
And how to access the params in the main (loop) -function?
I hope the code makes it clear what i want to do.
Thanks,
Marius

I'm inclined to agree with Majenko that you shouldn't use String in the first place, but if you want to, you can pass by reference:
const int numParams = 2;

void readParams(String (& params) [numParams])
  {
  params [0] = "foo";
  params [1] = "bar";
  }

void setup()
{
  Serial.begin (115200);
  String params [numParams];
  readParams (params);
  for (int i = 0; i < numParams; i++)
    Serial.println (params [i]);
}

void loop() { }

An easier thing is to make the parameters a global variable.

what if number of parameters is not known in the beginning ? how would you initialize numPaams then ?

Typically you would use new and make an array of whatever it is you want to make multiple copies of. Or you could consider the STL (Standard Template Library) which supports things like vectors.

Some tips:

Don't use String.
Use char * and slice the string in-place.
Pass a pointer to an array of pointers and fill that with pointers to the portions of the string you have sliced.
Return the number of entries in the array you used.

I do something similar in my CLI library.  I use a custom "getWord" function, but similar can be done with strtok().
You can read more about working with C strings here.


text:
Handling arduino output current
I need to power an actuator that requires 12 volts and consumes between 5 and 10 amperes depending on the weight it is charging. Therefore I bought a power supply of 12 volts and 10 amperes.
My intention is to send in the arduino output the 12 volts and the current provided by the power supply.
The options that I have thought are the following:
a) Connect the power supply to the arduino input pins and send the voltage and current from the power supply to the actuator through the arduino output (I know I could do it directly to the actuator, but I am interested in doing it through of arduino since it will involve programming code to put conditionals)
My doubt with this option is if I do not damage the arduino by connecting that power source with that amperage. If there is no problem, my question is if I could handle the current of the power supply at the output or the current could only be handled by what arduino gives that would not be much.
b) The other option that I think is simply to send a flag to the output and then this flag activates the power supply in some way and then I could use the 12 volts and the 10 amperes to connect them to the actuator.
I would like you to guide me on the alternatives I have thought about and tell me what would be the right thing to do, or if you know some other way in which you should do it.
Thank you very much in advance
Cheers

sounds like the arduino will make a  great fuse .... you cannot send 10A of current through the arduino ... research how to control motors with the arduino

Think "Relay". Google that plus the magic "Arduino" keyword and you'll see lots of results that give you some nice circuits.

@Majenko I was just checking that on the internet, my question now is whether it would be better to do it with transistors because the relay is mechanical and could be damaged and have a short lifespan, besides if I could do it with transistors considering these voltages and currents? Thanks :)

As others have said, an Arduino pin can't handle 12V, and can't handle anywhere near 10A of current directly. A digital pin on an Arduino is limited to 20mA, or 1/500 as much current as you need, at 5V, which is less than half the voltage you need.
If you try to connect 12V to a pin on an Arduino pin you will almost certainly destroy that pin, and may destroy the entire Arduino. If you try to source or sink even 1/100 of the current you are talking about through an Arduino pin, even at 5V, you will also probably destroy that pin and possibly the entire Arduino.
This sounds like a good application for a power MOSFET transistor. With that much current you'll need to put a heatsink on the transistor.
Here's one that would work:
https://www.sparkfun.com/products/10213
You'd use a logic pin from the Arduino to control the gate on the transistor, and the transistor would switch 12V at high current with very little resistance.
If the actuator is inductive, you'll need to protect the transistor with a suitably large "flyback diode" to protect it from the reverse current (or "back EMF") you get from an inductor when you remove power from it:
https://en.wikipedia.org/wiki/Flyback_diode

It seems a good solution.Now Im going to research how to control the current and voltage levels with the mosfet. Thanks :)

I see I need to connect the 12V power supply to the mosfet and the lineal actuator, If  I am correct?. And then i Would need another independent source of 5V for the arduino, or I can use  the same power supply of 12 V by reducing  with a voltage reducer, if this is the case what happen with the current of the source that is 10A, There is no problem since arduino will  only consume the current it needs?

PD I am using a lineal actuator.

The Arduino has a built-in voltage regulator. You could feed 12V into the barrel connector on the Arduino and it would regulate that down to the 5V it needs. As long as your power supply is strong enough to drive your actuator and the Arduino without too much voltage droop it should work, although as the actuator turns on and off there will likely be significant variation in the voltage supplied to the Arduino. You should probably add filter capacitors to the feeds to both the actuator and the Arduino to even out the voltage.

Duncan's  answer is how I would do it as well. Indeed that is how I did do it as well.
Having said that the challenge I had to work out was how to mix the voltages. For me, this was the hardest part of the project as I had little idea about current and voltage.
I also wanted to use just one power supply.
So what's the problem? The LED strip requires 12V@1Amp. Which is, I think the upper limit for what can be supplied to arduinio's power jack. Also the arduino can only supply a small current at 5v to switch the relatively massive 12V 1A led circuit.
The MOSFET was the answer (after multiple failed attempts). MOSFETs are apparantly safe for connection to Arduino as there is apparantly no electrical connection between the base (where the arduino connnects) to the other two pins (where the power flows). The articles I read say that the base is insulated from the rest of the circuit by a piece of glass!
Anyway, Here is my  Motion activated stair lighting project. I am not an electronics expert, but FWIW, this has been running flawlessly 24x7 for almost 12 months now.

Hey thanks a lot for your answer, and  also for sharing your project :), Cheers.


text:
Arduino Mega with SIM800L running Modbus TCP/IP
I'm trying to set up an Arduino Mega with a SIM800L module and trying to get Modbus TCP running on said Mega. I've set Modbus TCP over wifi and serial before but I used libraries for those. The problem is, I can't find a suitable library for SIM800L that has Modbus support in it. The project is supposed to get Modbus TCP to places without wifi, using a static IP enabled sim card. My question here is, am I missing something? While working with ESP8266 and Serial, I was able to find a ton of libraries to work with, but SIM800 series returns nothing for me.
Thanks!

In 99% of cases, problems with SIM800L came for voltage supply. With wrong voltage supply of without enough power, it doesn't work at all, or (worst case!!) it works for sending or receving 2 or 3 sets of data then start to loose data...

It's already working. Voltage supply isn't the problem. I suppose you didn't exactly read the question. My problem is that I can't find a library that supports Modbus and SIM800 module. Thanks for the tip anyways!

Well the problem for me is Modbus TCP libraries I have been using requires you to have a MAC ID or an IP adress in their implementation while I don't need any of those while using a SIM800 if I am correct. How am I going to get past that?


text:
Lost with Nano and i2c
I've been struggling with some code that was failing to "begin()" any devices on my i2c bus. I've uploaded a scanner program from arduino playground which lists the addresses of any i2c modules found.  With a single sensor connected the whole arduino freezes but when I unplug the wires from the a4 and a5 pins it continues. Plug them back on and it locks. I've tried with the SDA / SCL wires reversed as I've seen mention of things being backward.
Anyone know what I'm missing?

Maybe missing pull-ups?

So I've watched a video on pullups and what they do but I can't find anything about specifically what I need to do on the Nano. Am I using internal pullups on the 5v pin connecting the I2C devices or am I changing something on A4 or A5?

I don't know if the nano has internal pullups, just try adding extra 4k7 as it's a simple thing to do

If it still freezes, determine the voltage on scl in a stucked state. If possible, monitor scl with an oscilloskope

Sorry, my electronics knowledge is limited let alone integrating with microcontrollers.So far I've managed to build this device with all my modules plugging straight onto sda/ scl and voltage pins with little theory required. What do I connect with the 4.7k ohm resisotor to, is it between the voltage pin (in this case 3.3v) and SCL?

Yes, you connect one resistor between sda and vcc, the other between scl and vcc

can you please share the code

As I remember, the Arduino Nano runs with 5V, so why do you write about 3.3V. Does the device work with 3.3V? You cannot simply mix different supply voltages

@chrisl I have 5 devices connected to the Uno. One requires a minimum of 5V, the others are on the 3.3V and all are working.

@Vaibhav Any code where I try to run .begin directly on devices type instances fails regardless of which device I have connected. But the current code where I'm trying to scanning for whatever is connected and display the address of the devices is from here https://playground.arduino.cc/Main/I2cScanner/

@StephenYork OK can you share the schematic of your project.

@Vaibhav How will a schematic help? Like I said I had a single sensor connected...I I have the nano plugged into a breadboard with pin terminals off the A4 (SDA) and A5 (SCL) pins and pins terminals off the 3v and gnd pins.  I then plug my TSL2591 onto those terminals, VIN to the 3v, GND to GND, SDA to SDA, SCL to SCL. When I run the scanner it locks up. When I disconnected the SDA and SCL it continues running. This is identical wiring to how it was on the Uno. Why on the Uno do I not need pull up resistors yet on the nano it seems I do? As I understand it they're the same core hardware

@StephenYork actually it doesn't about nano or UNO. Unlike UART or SPI connections, the I2C bus drivers are "open drain", meaning that they can pull the corresponding signal line low, but cannot drive it high. Thus, there can be no bus contention where one device is trying to drive the line high while another tries to pull it low, eliminating the potential for damage to the drivers or excessive power dissipation in the system. They might be internally pulled up in hardware or you need to do it externally.

did you test the pins with digitalWrite?

I give up, people just keep asking bogus questions over and over. This is clearly not a valuable forum to ask anything on. I literally cannot make it any clearer. NO I didn't test digital write, my code works on the uno, not on nano... so why given it's the same chip and everything's connected the same with the same code?


text:
Change Arduino Uno clock from 16MHz external to 1MHz internal
I've got a project where I need to program an ATmega328P on an Arduino Uno board, then transplant it into a custom PCB - however, this board does not have an oscillator installed, and so I need to run the microcontroller off its internal clock.
My goal here is to be able to code my software with the Arduino IDE, insert a factory-fresh ATmega328P straight from the tube into the socket on the Arduino Uno board, then move the device from the board to the PCB without any changes along the way. What's the best way to go about this?

don't recall where, but i've seen a board def for a bare 328 set to run at 8mhz w/o xtal; maybe it will allow 1mhz as well...

That will not work. To change the clock source, you'd need to change the fuses. I don't know of any way to do this while the chip is inside the UNO.
Secondly, a factory fresh 328P won't work in an UNO board, because it doesn't have the correct fuses, and doesn't have the bootloader programmed.
I'd suggest placing the 328P chips in a breadboard; connect the ISP pin to the UNO, and use the Arduino-as-ISP to change the fuses, and upload your program.
PS why run at 1Mhz. The internal oscillator runs at 8Mhz. By default the divide-by-8 fuse is set, so it runs at 1Mhz out of the factory, but you can unset this fuse.
PPS use this website http://www.engbedded.com/fusecalc/ to generate the right fuse settings for your project.

This would set up the factory fresh device to work as an Arduino, right? That is, I could put the newly programmed chip into an empty Uno, program it, then move it onto a custom PCB?

You can easily change the fuses using something like the sketch described in my answer - you just connect to the ICSP pins (MOSI/MISO/SCK/RESET).

Kind of, but you don’t want to do just that. You can program the 328 with your sketch directly, while it is in the breadboard. No need to take it out of the breadboard and put it into the UNO.

You can set the fuses to run on the internal oscillator easily enough. You can still run at 8 MHz which the IDE supports (choose Lilypad in the IDE) and then the delays, serial prints, etc. will still work properly.
As for programming a new chip, you can use an Arduino as ISP, an external ISP programmer (available cheaply from eBay), or see my page about uploading hex files which just needs a few hook-up cables, and a $15 SD card adapter like this:

You upload the sketch onto your Uno to make it into a programmer. Then you compile the code for your target chip and get the .hex file that the compiler produces.
Example setup:

The hex uploader sketch also lets you change fuses.
The AVR Fuse Calculator page will help you with getting the correct fuse settings.

This is perfect - I assume the Lilypad is pin-compatible with the Uno?

The Lilypad is just an Atmega328P clocked at 8 MHz, so that is fine for compiling from your point of view. It's the same processor, so in that sense, yes it's pin-compatible.

Even better is that I have an 8MHz ceramic resonator on hand, so even though the Lilypad schematic specifies an external clock source, I've got that covered without having to order extra components!

I usually use the internal oscillator which generates 8 MHz. No extra parts needed.

I've heard horror stories about fuse bits, so the further I stay away from those, the better. I also don't have to explain to my professor why my board has an empty slot as well...

Lots of commercial boards have empty slots. :) You can say it is for future expansions. As for the fuse bits, there are only a couple of disastrous changes you can make, and the code in my hex uploader program specifically disallows those. See here in the code.


text:
Can I program a 20MHz Attiny85 with the 8MHz Internal Clock option in the Arduino Software?
I'm looking at using the ATTiny85 for a project, but have run into a snag. After following the tutorial found at https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide, I've installed the necessary files to be able to program an ATTiny85; however, the options given under "Clock" are 1MHz and 8MHz internal, as well as 8, 10, and 20MHz external.
Normally this wouldn't be a problem, except Digikey has no in-stock 8MHz flavored devices in the package I need (SOIC-8, don't have a reflow setup to use the QFN package).
If I buy the 20MHz version, will I be able to program them with the Arduino IDE set to the "8MHz Internal" clock option?

What do you mean by the 20 MHz version exactly? Are you suggesting that the Attiny85 comes in different speed grades? Where is the documentation supporting that?

Digikey has no in-stock 8MHz flavored devices - can you provide links to these devices that supposedly come in different speeds?

Here's the list I had narrowed down to: https://www.digikey.com/products/en/integrated-circuits-ics/embedded-microcontrollers/685?k=attiny85&k=&pkeyword=attiny85&pv16=7409&FV=1f140000%2Cffe002ad&quantity=0&ColumnSort=1000008&page=1&stock=1&pageSize=500 I believe these to be pre-set from the factory for the various clock options - but will it matter when I try to program them with the Arduino software? That is, is it expecting a specific clock speed that these aren't set to out of the box?

See my amended answer.

I think you have the wrong end of the stick here. The Attiny85 is not a chip that comes in different speed versions. The datasheet mentions that it can run at 20 MHz. That doesn't mean you can buy a "20 MHz version". By selecting the appropriate clock option in fuses you can run at 20 MHz (or higher). From the datasheet:

High Frequency PLL Clock
There is an internal PLL that provides nominally 64 MHz clock rate locked to the RC Oscillator for the use of the Peripheral Timer/Counter1 and for the system clock source.

I believe these to be pre-set from the factory for the various clock options - but will it matter when I try to program them with the Arduino software?

That list is weird, it doesn't specifically say they are pre-set to any speed. Personally I would regard that list as meaning that the higher speed ones are manufactured to better tolerances, if indeed it means anything at all.
Maybe when they manufacture them they do a quick test at various speeds, and ones that don't run at 20 MHz are put into a different batch.
The datasheet specifies the default clock settings, it would be weird if Atmel made them with different settings unless you placed a massive order.
As for programming them, by default they don't come with a bootloader, so you would need to use ICSP programming anyway. You would need (in any case) something like the AVRISP device (which connects via USB to your computer, and the other end goes to your chip to be programmed). Or you can make up something like my AVR hex programmer which lets you put a hex file from the IDE onto a MicroSD card, and then use that to program the ATtiny85.
In all of these cases you can change the fuses to do what you want, including the clock options you prefer.
There is a board you can buy which is a pre-made gadget using the code I mention above, where you just press a button and the chip is programmed, which would be helpful if you are doing a lot of them.

I believe your theory to be correct as the ones with a higher MHz rating appear to be more expensive. Thanks!


text:
Is there a way to disable modules like ADC without a sleep mode?
I'm working on a binary watch project. I want my circuit to live off of batteries for as long as possible, so I want to decrease the power consumption of my chip.
I'm using a barebones ATmega328P-PU with two 74HC595 shift registers. The ideal situation would be to keep the CPU, clock, flash, and I/O going so my program can continuously count the time on its own, but disable everything else that I'm not using, such as the ADC, BOD, TWI, timer1 and timer2, USART0, etc.
I took a look at the ATmega328P datasheet for the sleep modes, and it seems as though they all disable the CPU/Clock. Is this true? And if so, are there ways to disable the modules without enacting a sleep mode?

You do not want to keep the CPU running on a battery-powered project! You should use a timer for keeping the time, and let the CPU sleep. Ideally, you would connect a 32,768 Hz crystal to TOSC1/TOSC2 and have Timer 2 work in RTC mode. I have a clock running since June 2012 on the same pair of AA cells using this low-power technique.

You could use sleep_mode_idle. You can also try running at a slower speed. But that won't save a whole lot. I'd second the idea from Edgar, in using a 32kHz cystal to run timer2 in asynchronous mode, and put the MCU in SLEEP_MODE_PWR_SAVE.

Certainly there is.
  // disable ADC
  ADCSRA = 0;

You can disable lots of internal modules like this:
  power_all_disable();  // turn off all modules

See my page about power saving.

Majenko commented that turning off the ADC, while leaving the processor running was pointless. The real way to save battery power is to sleep, and it is possible to do that and still keep track of the time.
On my page about timers there is code to use a 32.768 kHz clock crystal to sleep and wake every second, which you could then use to alter the display on your watch.
Code from that page:
#include <avr/sleep.h>
#include <avr/power.h>

const byte tick = 3;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

void setup()
 {
  pinMode (tick, OUTPUT);

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 32 * 1024  (32768)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  31;              // count to 32 (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_adc_disable ();
  power_spi_disable();
  power_twi_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_usart0_disable();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

  }  // end of setup

void loop()
  {

  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);

  // sleep, finally!
  sleep_cpu ();

  // we awoke! pulse the clock hand
  digitalWrite (tick, ! digitalRead (tick));

  }  // end of loop

Whilst asleep, the processor uses very little power. In the example sketch I measured 1.46 µA current consumption, when the output was LOW, if running from 5V power supply, and 1.1 µA if running from 3.3V power supply.

Example setup:

I have two decoupling capacitors (the blue ones). A pull-up resistor on Reset.
A 32.768 kHz crystal between pins 9 and 10. A 22 pF capacitor between each leg of the crystal and ground.
A current-limiting resistor and a LED. It works, and toggles at 1 Hz. When asleep (LED not on) it draws 1.46 µA as mentioned above.

Thank you for the quick response! I added these to the void setup() part of my code, recompiled/loaded and tested it, but there was no change in the power draw of my circuit. It's sticking around 0.39mA. Is this normal?

I only tried out the top suggestion (as well as power_adc_disable();), since I don't want to power off everything, as the bottom line of code suggests.

The ADC contributes about 0.00001% to the total power draw. The saving is swamped by the CPU consumption. Turning off just the ADC is pointless.

Have you tested that? According to my measurements turning off ADC results in almost 1/1000 times power consumption.

With that there the power consumption drops a large amount, down from 335 µA to 0.355 µA! (that is, 355 nA)

Of course, I'm assuming you take other reasonable steps, like not using a power LED, not using a USB chip, not using a voltage regulator, and going into sleep mode. But once you have done all that, the ADC uses quite a lot of power.

Comparing ADC on to ADC off when asleep, i.e., the CPU not running, yes the ADC uses "a lot". But compare that to when the CPU is running and that "massive" drop is swamped by the huge amount the CPU is using.  The OP specifically (if completely incorrectly) doesn't want to go to sleep. So switching off the ADC in that situation is pretty pointless.

Also, for a "binary watch" project I suspect that the MCU is only using a small fraction of the overall power, and the LEDs and shift registers (how big is this "watch"?!?!) will use considerably more than the MCU, and a billion times more than the ADC is using...

@Majenko: Regarding the power consumption of the LEDs. I remember a long time ago owning a digital watch with LED display. The display was active only while a specific button was held down. Inconvenient, but that's how you could get reasonable battery life despite the LEDs.

@EdgarBonet You were posh then ;) For about 2 years, when you became old-fashioned overnight :)

I've added code to show how you can keep track of the time with a 32.768 kHz crystal, and still have low power consumption.

Thank you, @NickGammon! Question, what purpose does making the crystal count to 32*1024 serve?

Well, since it oscillates at 32768 Hz, counting to 32768 will mean you get one interrupt per second.

@NickGammon I set up a mock circuit to test out your code, and the ATmega sticks at about 200uA. The only line I changed was digitalWrite(tick, HIGH) and I connected that pin to an LED. It seems like it's stuck in sleep mode though, because the LED never turns on. I have the 32.768kHz crystal connected to XTAL1/XTAL2. Is this result I'm getting correct?

I made up the test again to check it works OK. See amended answer. Yes, it works. You need a 22 pF capacitor between each leg of the crystal and ground. I got 1.46 µA of current draw at 5V input, and 1.13 µA if running from 3.3V.


text:
How to measure CO2, Ammonia and Detect Smoke using MQ135?

Setup Info:
MQ135 + Arduino+16x2LCD+ESP8266+ThinkSpeak.
Hi All, I have just bought a MQ135 . I started arduino basics with LED blinking , interfacing and then started with my real project.
e
I have seen in the data sheet of MQ135 that it can measure Ammonia, Sulfide,CO2 and Benze steam. It can also be used to detect smoke and alert.
But in the Arduino uno Serial monitor, I can see only one value 408.
Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm
Also, my friend suggested to calibrate this sensor for which I found really good material and started with 24 Hours on test after dumping a code to read data from it.
Now I read 1836 which was 1795 , about half an hour back.
Kindly reply and let me know what info or input is required from My side.
This is my first of my many uno projects to come.
Regards,
Sillicon
https://forum.arduino.cc/index.php?topic=535401.msg3649205#msg3649205

you already posted at forum.arduino.cc .... why are you posting again here?  ..... you have not asked a specific question.

Yup, I intend to notify the same and look for unique solution to solve this problem

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

This sensor does not differentiate between the various gases that it is sensitive to.

I dont recollect but I have seen coders showing off different values of CO2 , Ammonia on a 16X2 screen using MQ135.

If you’ve seen it, show it.

https://www.youtube.com/watch?v=GT8dNNRWNOY   Visit this please

I watched the video. The fact that values are displayed for different gases does not mean the values displayed are accurate. There are values shown for "Smoke" and for CO when it's clear nothing is being burned/combusted.


text:
LED strip problem... getting red when expecting white with lots of pixels. Fine with 1 pixel
I have an Arduino Uno.  I bought this LED strip:  https://www.amazon.com/gp/product/B019DYZNO6/ref=oh_aui_detailpage_o08_s02?ie=UTF8&psc=1
Starting initially using FastLED library. When I tried to set the entire strip to white (255,255,255), it was coming out red. Any color close to white was coming out red.
I thought maybe there was an issue with the library, so I tried the neopixel library. Same thing until... If I just set one pixel to 255,255,255 and don't set any other, it comes out white!  If I set about 10 pixels, they still look white. As I set more pixels, they start to loose their whiteness and become red.
I want to say that maybe this was a power issue... but I tested this both when it was running off my PC and running standalone with a power supply (supplying 5V).
Any suggestions??  I also thought that maybe it's a bum strip, but I also bought https://www.amazon.com/gp/product/B01AG923GI/ref=ask_ql_qh_dp_hza and did the same experiment, and am getting the same results...

How much current does your external power can supply? These LEDs can be very power hungry. For my strip each LED uses 30mA when completely white. This would result in 4.2A for a 140 LED strip like yours

do you have the recommended capacitor and resistor between the strip and MCU?

For future searchers, this same problem can also give a Green colour when trying to set the neopixel grid to white.

According to https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels a Neopixel can consume 60 mA at full brightness white.

Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue). In actual use though, it’s rare for all pixels to be turned on that way. When mixing colors and displaying animations, the current draw will be much less. It’s impossible to estimate a single number for all circumstances, but we’ve been using 1/3 this (20 mA per pixel) as a gross rule of thumb with no ill effects. But if you know for a fact that you need every pixel on at maximum brightness, use the full 60 mA figure.

So your 144 Neopixels would require 8.4 amps. You would need a pretty solid power supply to supply that much.
One way of confirming that would be to measure the voltage in to the Neopixel strip (at the strip end) when it is displaying all white. I'd be surprised if it measures 5V.
The Amazon page you linked says:

Voltage: DC 5V
Power: 0.3W ± 0.01% per LED

That agrees with the figure of 60 mA (0.060A * 5V = 0.3W)

To put it another way, your power supply would need to supply 43.2W (144 * 0.3W). None of the bench power supplies I have here can put out 43W (or 8A), nor any of the wall-warts. You may have a really massive one, but you haven't specified what sort of power supply you are using.

I run them with a power supply (one that is working as expected, but still have it connected to the PC/USB?

Yes, there is a technique for doing that (similar to powering motors etc.).

You have one low-current supply to the Arduino (this could be your USB port even).
You have a high-current supply to the pixels/motor/whatever. This would require thicker cables.
You connect the grounds of both supplies so that they have a common ground reference.
The data line (the pixel information) is sent from the Arduino to the Neopixels

The one power supply can do both roles, just connect the wires together at the power supply end (this automatically connects the grounds, of course).
This way, the heavy-duty current does not go through the Arduino board.

If you are using the USB port for logic power you still connect the grounds like this:

I'm using the power supply recommended by the LED folks on the Amazon page which is a 5V, 10A.  https://www.amazon.com/gp/product/B01M0KLECZ/ref=oh_aui_detailpage_o08_s00?ie=UTF8&psc=1   Now... I haven't taken out my multimeter and doublechecked that that's what I'm getting out of it... but problems with current make sense.

Sounds reasonable, but at that current you might be losing voltage over the wires. Measuring the input to the strips, at the LED end would confirm that.

You might need to apply power to both ends of the strip (if that is practical) because there might be a voltage drop over the length of the strip itself. Especially if the white colour deteriorates progressively (ie. white at the start, not so white at the end).

I just measured the output voltage of the supply... getting less than 3V. :(
My multimeter doesn't seem to be working for Amps. So my next question... can I run this strip of light off the Uno when it's connected to my PC? I'm guessing not since there's only a 5V and 3.3V output. I did try with the 5V and am also getting the same issue... white for a few pix, no white for lots of pix.

The strip needs 5V to operate correctly. With 3V it won't work as intended. Also you cannot drive your strip from your PCs USB, since they only provide up to 500mA, so far not enough current for the strip when turned on. In doing so you can also damage your Arduino or USB port of the PC. When the LEDs are of it is possible. Try measuring the voltage output of your power supply without anything connected, to ensure that it really outputs 5V. If not the seller send you a wrong product.

like I said, I measured and am not getting the expected 5V. So I guess that's my problem. Thanks for the tips on not running it off PC/USB. Next question is... can I run them with a power supply (one that is working as expected, but still have it connected to the PC/USB?  I want to take input from the PC...

See amended answer for how to do this.

My multimeter doesn't seem to be working for Amps - measuring amps requires a different technique. Don't just bang the leads onto the two wires, you don't measure amps that way. Try Googling "how to measure current with a multimeter".


text:
How to solve problem AT+INQ ERROR (1F), AT+INIT ERROR(17) on Bluetooth Module HC-05?
i have problem with accessing at-command in module Bluetooh HC-05.
i just follow all tutorial to activate at-command like this,
http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-in-slave-mode/
or in this video
https://www.youtube.com/watch?v=Vr4cdpsoVEo&t=31s
and just read some explanation and implemented to my problem
HC-05 Bluetooth AT+INQ command not working
but i just still get same error.
i cant use AT+INQ command, always get ERROR(1F).
AT+INIT get ERROR(17).
i have module HC-05 with version 3.0-20170601
This is my code i use it.
#include <SoftwareSerial.h>
SoftwareSerial BTserial(8, 9); // RX | TX`

const long baudRate = 38400;
char c=' ';
boolean NL = true;

void setup()

{
   Serial.begin(9600);
   Serial.print("Sketch:   ");   Serial.println(__FILE__);
   Serial.print("Uploaded: ");   Serial.println(__DATE__);
   Serial.println(" ");

BTserial.begin(baudRate);
Serial.print("BTserial started at "); Serial.println(baudRate);
Serial.println(" ");
}

void loop()

{

// Read from the Bluetooth module and send to the Arduino Serial Monitor
if (BTserial.available())
   {
       c = BTserial.read();
       Serial.write(c);
   }

   // Read from the Serial Monitor and send to the Bluetooth module
if (Serial.available())
   {
       c = Serial.read();
       BTserial.write(c);

    // Echo the user input to the main window. The ">" character indicates
    the user entered text.
    if (NL) { Serial.print(">");  NL = false; }
    Serial.write(c);
    if (c==10) { NL = true; }
   }

}

check this out ... https://stackoverflow.com/questions/23221336/hc-05-bluetooth-rssi-not-working-with-arduino

Ty for comment sir. I just read and implemented your guide But my problem still not solve. I wondering my firmware. Because I have Bluetooth version is 3.0. and other tutorial have version is 2.0

Do other AT commands work? what arduino are you using?

Yap i just use all AT-COMMAND. Just AT+INQ get error. I use Arduino uno.

thank you for this wonderful post Presidenten ,but i am having issue, "AT+STATE" shows inquiring ..if i power up my bluetooth device (not hc05) it doesnt show any address...what am i missing..please help...

I have a HC-05 with 3.0-20170601 that I managed to bind to a slave last night. It turns out that the v3 has two AT-modes.
The first is when you hold the button while you connect power. The led will blink slowly and you can connect at 38400 baud. But this is like a configuration mode, where AT+INQ is not available.
In this mode I did these commands:
AT
AT+UART
AT+RMAAD
AT+ROLE=1

(Press and hold the button)
AT+RESET

(Release the button after device restarts and led is slowly blinking)
AT+CMODE=1
AT+INQM=0,5,5
AT+PSWD="9999"

AT should give OK as answer to know connection is working
AT+UART will show configured baudrate. Default is 9600.
AT+RMAAD clears all saved connections
AT+ROLE=1 sets it as master
AT+RESET restarts the device to change to master
AT+CMODE=1 accepts all kinds of devices
AT+INQM=0,5,5 inquires in standard mode, with 5 max connections or 5 secs
AT+PSWD="9999" sets the pin code 9999, change to the pin you need
After this it is time to update the arudino code. In your case you should update line 4 from
const long baudRate = 38400;

to
const long baudRate = 9600;

...or what ever value you might have set the baud rate to. Then reflash your arduino.
Now enter the very irritating second AT command mode.
Power up without holding the button. You will get the fast blink speed. When its powered up, press and hold the button. The led will continue blinking fast, but while the button is pressed you can now connect to the device on the configured baud rate. So open the serial monitor and type AT to verify.
Remember that the mode is only active while the button is pressed. So keep it pressed. I had a small clamp I put on there.
Then I entered these commands:
AT+STATE

AT+STATE will show current state, should be inquiring
Then power up the slave device and the adress should start popping up. It will be something like xyz:xy:xyzw,931F00,7FFF
The first part is the address you want (xyz:xy:xyzw)
Change : to , and get xyz,xy,xyzw
Check that you connecting to the correct device
AT+RNAME?xyz,xy,xyzw

Then bind
AT+PAIR=xyz,xy,xyzw,5
AT+BIND=xyz,xy,xyzw
AT+LINK=xyz,xy,xyzw

The AT+LINK command gave me FAIL as output. But it did not matter.
I restarted and did not press any button before or after. Just normal start.
After 5-10s serial data showed up in my serial monitor.
Modules are bound. And will automatically connect at power up. If not you might have the wrong pincode. Make sure to change 9999 above to 0000 or 1234 or what ever it may be. When I hade the wrong pin I still got OK from the AT+PAIR and AT+BIND commands... It didnt work for me until I entered the correct pin.
Sorry for long post, but I wanted to be thorough since info about HC-05 v3 is very scarce on the internet right now.
A reference to all commands can be found here:
http://www.electronicaestudio.com/docs/istd016A.pdf
(Link valid 2018-08-13)

Extending the Presidenten's answer, the easiest way to program HC-05 is to sonnect a wire to EN on the chip and set the UART console to 9600.
Then pull the EN high, send commands, wait for OK (after each one), and drive EN down.
You now have a chip in data state.

I have two modules:
(A) HC-05 with firmware version 3.0-20170601
(B) HC-05 with firmware version 2.0-20100601 (ok)
I have the same problem: when the AT command "AT+INQ" is sent on (A) module, the response is always "ERROR:(1F)". This error code seems not be reported in any document or specification available on internet. This BT module have firmware version (AT+VERSION) 3.0-20170601. Also I have noticed that command AT+INIT on (A) module returns always ERROR:(17), this error normally can be ignored if the command has been sent already (Initiate SPP lib), but the first time should be return "OK" as on (B) module.
The (B) module with firmware version 2.0-20100601 works ok with the following commands (set PIN34 high at power-up, or press button on module and keep pressed during commands):
AT+RMAAD -> delete all paired devices list
AT+ROLE=1 -> Set master mode
AT+RESET -> reset module to enter into master mode
AT+CMODE=1 -> Permit connection with any device
AT+INQM=0,5,9 -> Set Search parameters(Query mode standard, 5 devices, 9secs)
AT+INIT  --> Init SPP profile mode (first time response: "OK")
AT+INQ  --> Start search devices (return device list after some seconds)
The differences between two modules are:
On AT+INIT the (A) module return always ERROR:(17), the (B) module return "OK" first time and ERROR:(17) if the command is sent twice.
On (A) module the command AT+INQ return always ERROR:(1F), the (B) module return the list of the BT devices.
Also the (A) and (B) modules are physically different. The (B) module have some components (resistors/capacitors) between the two big black chips, the (A) module no.
Also I noticed that on (A) module the AT+CLASS? return "1f00" value (default?). The correct value should be "0" as (B) module ? Anyway setting AT+CLASS=0 on (A) module the result is always the same.
In slave mode (AT+ROLE=0) both modules works fine.
With (A) module I'm unable to use it as "MASTER" and connect it to any other slave BT modules because did not perform devices search. (INQ fails).
I think that in 3.0 firmware is needed to set other(s) parameter(s) in order to start SPP profile correctly (INIT) and then avoid ERROR:(1F) in INQ command (search).
Someone already solved the problem ?

So the conclusion about my problem is the firmware on HC-05. Firmware with 3.0 make AT+INQ will be not work. Ty very much for your answer. This is problem make me Stack on a month. Your answer very useful to me.

So your HC-05 with firmware 2.0 have push button or not?

Yes, it have the push button. The HC-05 is soldered on ZS-040 board that have the push button connected to PIN34. If you press the button at power-up, the module will enter in AT-COMMAND mode (38400bps, CR+LF) and it is possible to setup and view configuration of the module as MASTER o SLAVE by using AT commands. Some similar modules (HC-06) doesn't have the button because they are SLAVE only.

Okay. Ty very much brother.

Sir, can I buy your HC 05 with Firmware 2.0?

I have the same version module HC-05.
This mode (INQ) is enabled for default and it's impossible switch it off. Seems that manufacturer removed this command in that version.
Another point, that it works only on default 9600 bod/s regardless of settings AT+UART=... and only in standart AT mode (key pin pull high after power on device).
Once connected to other module only one way to return to "inquiring" that I found is full reset it by command ORGL, and reconfigure it class and role.
Don't touch IAC settings - that also causes improperty working.


text:
HX711 Ridiculous speeds
I'm using a SparkFun HX711 board and an Adafruit AdaLogger (M0) Featherboard. I have cut the trace on the back of the HX711 to get a faster data rate (should be about 80 sps). I did this by reviewing the spec sheet and confirming with this post (Github link for faster rates).
Before I read from the board I get startTime from micros() and immediately after I get get the scale data, I call micros() again and record the endTime. I then write this data along with the load cell data to an SD card. Then to check the time, after the experiment is over in excel I take 1/((endTime - startTime)*10^-6) to get the approximate number of samples per second.
My issue is that apparently, I'm recording at a max of around 6000 SPS but commonly around 600 SPS. Which, would be awesome if I wasn't so sure that it was a lie. I was hoping someone could take a look and see what I'm doing wrong? I used this same code on a different M0 with an unmodified HX711 and was getting around 10 SPS. The only thing different (I thought) was cutting the trace on the back of the board to enable the higher rate.
In the GitHub link above, they do mention that you can get a faster rate if you splice in a faster crystal with a cap to bridge pins 13 and 14. I have not done this, but perhaps the faster processor on the Feather might be playing some of a role in this?
VCC and VDD are both connected to 3.3V and GND is connected to the ground pin on the Feather. Pin 11 is connected to DAT and Pin 10 is connected to CLK
#include <SPI.h>
#include <SD.h>
#include "HX711.h"

#define FILE_BASE_NAME "FAST" // max six characters
#define DOUT_one 11   // Red
#define CLK_one  10   // Orange

const uint8_t CS_PIN = 4;
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;

char fileName[] = FILE_BASE_NAME "00.csv";

float calibration_factor_one = -7050; // needs to be calibrated still

File file;

long startTime=0;
long endTime =0;

String dataString = "";

double scale_one_value = 0.0;

HX711 scale_one;

void SetUpSDCard(){
  if (!SD.begin(CS_PIN)) {
    Serial.println(F("begin failed"));
    return;
    }
   while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }
   file = SD.open(fileName, FILE_WRITE);
  if (!file) {
    Serial.println(F("open failed"));
    return;
  }
  Serial.print(F("opened: "));
  Serial.println(fileName);
  }

void SetUpLoadCell(){
  Serial.println("Remove all weight from scale");
  scale_one.begin(DOUT_one, CLK_one);
  scale_one.set_scale();
  scale_one.tare();

  long zero_factor_one = scale_one.read_average(); //Get a baseline reading
  Serial.print("Zero factor: ");
  Serial.println(zero_factor_one);
  Serial.println("Load cell one initialized");
  scale_one.set_scale(calibration_factor_one); //Adjust to this calibration factor
  }

void LogData(){
  startTime= micros();
  scale_one_value = scale_one.get_units();
  endTime = micros();

  dataString = String(startTime) + "," + String(scale_one_value) + "," + String(endTime);
  file.println(dataString);
  file.flush();
  }

void setup() {
  Serial.begin(9600);
  SetUpSDCard();
  Serial.println("Remove all weight from scale");
  SetUpLoadCell();
}

void loop() {
  LogData();
}

Then the saved data that is on the SD card is as follows, this is just the first 20 lines.
3383895,    0,      3384049
3401786,    0,      3401938
3411851,    0,      3412004
3421850,    -0.02,  3422004
3432012,    -0.03,  3432164
3442074,    0.01,   3442226
3452118,    0,      3452269
3462299,    0,      3462450
3472441,    0.03,   3473497
3483434,    0.03,   3485070
3495011,    0.02,   3496638
3506580,    0.01,   3508211
3518576,    0.03,   3519785
3529783,    0.02,   3531353
3541282,    0,      3542924
3552831,    0,      3554495
3564476,    0,      3566070
3575900,    0.01,   3577638
3587476,    -0.01,  3589209
3599068,    -0.03,  3600782

You're not measuring how many samples you do in a second, instead you're measuring the amount of time it takes to retrieve one sample from the HX711.
You store the time, retrieve the next sample, then store the time again. Then you spend a comparative age storing that data to the SD card, during which time the HX711 is taking any number of other samples.  By the time you eventually get around to reading from the HX711 again it's already ready to give you a sample.
You need to factor in the amount of time it takes to write to the SD card to have any kind of meaningful results - that is, the total amount of time that it takes to execute a loop(), or more simply: how long since the last time your logData() function has been run.
The actual sampling time of the HX711 will probably pale into insignificance compared to all the rest of your sequential code.

oh god. lmao. Yup.. That is exactly what is going on! I feel like a moron hahaha

To measure data sampling rate, measure elapsed time to fill an array with 10 (or better yet - 100) measurements.
N = 100;
t0 = millis();
for (i=0; i<N; i++){
    s[i] = get_sample();
}
samplingTime = (millis()-t0)/N;

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.


text:
Why no brackets after Interrupt routine inside attachInterrupt
I'm just curious as to why there are no brackets at the end of the ISR when attaching and assigning the interrupt command?
 attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
 ...
 void blink() {
    state = !state;
 }

In, attachInterrupt, I would have expected "blink" to be written as "blink()", with the brackets, not just the name of the function, sort of like how you would normally call the function blink() from your loop or setup functions (or elsewhere). So, what's going on here, and are there other scenarios where you might use a function without the brackets after it?

Who on earth would want to close this? It is a good question.

Moderators can see the users who voted to close this question.

It is right, that you are putting brackets after the function name if you are calling it. But with attachInterrupt() you just want to give it the information, which function to call in case of an interrupt. With the brackets the compiler would think you want the function to be executed and the result/return value being given as parameter to attachInterrupt(). But the execution here should only happen in case of an interrupt. The attachInterrupt() function/the corresponding ISR need to know, what to call in case of an interrupt. Just the information/address of the function.
Maybe you have already heard of pointers. That are variables that hold the address of a different variable. They are pointing somewhere else in the memory. blink (without the brackets) is basically a function pointer. Leaving the brackets away tells the compiler, that you want the address of the function, not executing it. You are providing the function parameter by reference this way, providing the address, not the value.
If you like/need you can use that principle yourself by defining your own function pointer variable. For example this
void (*myCallbackFunction)(int);

which is a function, that takes an int as parameter and returns nothing (void). You can then set the function pointer and call it as a normal function
void blinkXTimes(int times){
    for(int i=0;i<times;i++){
        digitalWrite(pin, HIGH);
        delay(500);
        digitalWrite(pin, LOW);
        delay(500);
    }
}

void setup(){
    pinMode(pin, OUTPUT);
    myCallbackFunction = blinkXTimes;

void loop(){
    myCallbackFunction(3);
    delay(5000);
}

We are calling myCallbackFunction(), but it is a function pointer, that points to blinkXTimes(), so that will be executed.

So, what's going on here, and are there other scenarios where you might use a function without the brackets after it?

The above principle is super useful for writing libraries with user callback functions. Another example (besides attachInterrupt()) is the Wire library. There the receive and request interrupts need to interact with the library user to deliver to or request data from him. For this the Wire library lets you set your own callback functions. Refer to the examples of that library.
Another application would be building a Finite State Machine with a function pointer (basically calling different functions on each loop iteration depending on the state, which is represented by the function pointer).
That are the two big application I know of. The first one is more common. Though function pointers are just a tool. They can be used for many things.

This was phenomenally helpful!!!

Just nit-picking, but giving a pointer as an argument for a pointer parameter is still passing by value. In C++ there is just one way to pass by reference: If you have a reference parameter like void f(TYPE & p);.

Unfortunately a lot of these terms are overloaded. The C standard used the term "referenced type" for T in the T * construction, but C++ doesn't use this term there.  However, the application of unary * operator to a pointer is still literally called "dereferencing" a pointer in C++.  Admittedly, that terminology for use as passing-by-way-of-pointer-value is more confusing in C++ than it was/(still is) in C. But, it is commonly used and understood in context, even by C++ programmers, if otherwise imprecise. For anyone that hasn't encountered this usage yet, well, now you have.


text:
Can I run arduino on Windows Embedded Compact 2013?
I'm actually working on a robotic project for which I'm planning to use arduino to drive the wheels.For this, I want to send signals from my Onboard embedded computer (which has Windows Embedded Compact 2013 OS) to arduino. Is this possible? If not possible, what are the other alternatives?

I think the title of the question is misleading. When you say "Can I run arduino" it would lead people believe you're asking whether you can run the Arduino IDE (which I don't know). But later you explain that you actually only want to send signals to the Arduino. This doesn't require the Arduino and is certainly possible. If you wanted a better answer you would need to explain what sort of communication you plan to use for these signals (serial, SPI, I2C, etc.).

What OS is running on two different devices exchanging messages/signals, does not matter. What matters is the protocol.
You can use a lot of different ones:

Wireless:

IR (infrared)
RF (radio), like 433 MHz, 2.4 GHz
WIFI (internet)
Bluetooth

Wired

SPI
'simple wires' / Wire library
Serial
USB (not on most Arduinos)

This list is not complete, just some examples.
Arduino supports all above (except USB fully), I don't know what Windows Embedded Compact OS supports.

Actually, the only thing an ordinary Arduino easily supports for interaction with a typical modern PC is USB.  That will present on both ends as a serial port, but in terms of what you connect with a cable, it is USB.

strictly speaking the answer is correct, but would be clearer if it was changed to say Serial + USB Serial as the 3rd option and Native USB (not on most arduinos) as the 4th


text:
"Active LOW" relay board Pin configuration
I bought a 5 V Relay Board: LINK (Aliexpress) and just realised it's "Active LOW".
I want to control a water pump via a Arduino Micro.
I tested it and as far as i understand the workings of this relay, putting the pin to LOW activates the little LED on the Relay Board and switches to the NC position where I connected the water pumps ground wire.
I don't feel very comfortable with that because normally those relays are activated by setting the pin to HIGH.
I tried to connect the ground wire of the pump to the normally open position but than, if I disconnect the Arduino to simulate a malfunction the pump keeps running.... this doesn't happen with the first configuration.
So my Question: Is it a problem to use the Relay Board in the way described above (Pin to LOW switches Coil to NC Postion).
Is there a way I'm not seeing to get the Board to switch the Coil if a pin is set to high.

Is there a way I'm not seeing to get the Board to switch the Coil if a pin is set to high .... why would you want to change the board? .... changing the arduino sketch is way easier

yeah you're right I just thought about maybe some kind of "jumper" configuration or powering the whole board via an Arduino ping or stuff like this

I don't quite understand what kind of problem you expect. Could you draw a schematic and explain what you think could happen?

That relay module is driven by optocouplers. You are just driving and LED, and that is connected though a resistor to VCC.
In the past it was common to use active low for driving things since an N channel MOSFET could typically sink more current than a P channel one could source. Also in the days before CMOS there was really only low-side (sinking) switching, so active low was the norm.
These days it's not necessary, but it's still common because that is how it's always been.
So yes, active low is both common and accepted.


text:
Merging of two functions
This is my Arduino code that checks the water Level of two different water reservoirs via 2 water Level Sensors A and B:
#define Water_Level_A 5;
#define Water_Level_B 6;

boolean Water_Level_Check_A(){
boolean Result = digitalRead(Water_Level_A);
return Result;
}
boolean Water_Level_Check_B(){
boolean Result = digitalRead(Water_Level_B);
return Result;
}

void setup() {
    Serial.begin(9600);
    pinMode(Water_Level_A,INPUT);
    pinMode(Water_Level_B,INPUT);
    }

void loop() {
if (Water_Level_Check_A() == LOW){
--> Water Pump A
}
if Water_Level_Check_B() == LOW{
--> Water Pump B
}

What's the best way to simplify this code so that I only need one Water_Level_Check function so that the distinction between A and B and Water_Level_A and Water_Level_B is made within the function and the loop part looks like this:
void loop() {
if (Water_Level_Check_(A) == LOW){
--> Water Pump A
}
if Water_Level_Check_(B) == LOW{
--> Water Pump B
}

How about giving the function the pin number to read from as a parameter? In this case you would write if(Water_Level_Check(Water_Level_A) == LOW)

I think what you're asking for is something like this:
boolean Water_Level_Check(uint8_t level_pin){
   boolean Result = digitalRead(pin);
   if( level_pin == Water_Level_A ){
      // manage pump A here
   }
   else if( level_pin == Water_Level_B ){
      // manage pump B here
   }
   else {
      Serial.println("Water_Level_Check: unknown pin number.");
      // or some other way of dealing with a bad-pin-number bug.
      return -1;
   }

   return Result;
}

for the level testing function, which will simplify you loop function to:
void loop() {
   (void)Water_Level_check(Water_Level_A);
   (void)Water_Level_check(Water_Level_B);
}

The (void) expression before each call is a "cast to void", telling the the compiler to consider the function's boolean return value to have been intentionally "voided", i.e. you intended not to read it, and not to give an error message.

Functions like
boolean Water_Level_Check_A(){
   boolean Result = digitalRead(Water_Level_A);
   return Result;
}

Are really overcomplicated. You're just calling one function and returning that value, so it can be simplified to
boolean Water_Level_Check_A(){
   return digitalRead(Water_Level_A);
}

Or just the expression
digitalRead(Water_Level_A)

whenever you need it.
So all you're doing is calling digitalRead() on a pin number and check if the result is low. If you really want to move this to a different function then you could give it the pin number argument and directly invert the result so that a true from this function means that some action needs to be done.
boolean Water_Level_Check(int sensorPin){
   return !digitalRead(sensorPin);
}

And then call it as
void loop() {
   if (Water_Level_Check(Water_Level_A)){
       //--> Water Pump A
   }
   if (Water_Level_Check(Water_Level_B )){
       //--> Water Pump B
   }
}

The boolean Water_Level_Check_A() I'm using in my code also includes the Powering On and OFF of the Water Level Sensor. That's why I used the function in the first place. The code here is just the minimal example for my question on how to change A and B in the function. The return !digitalRead(sensorPin) looks cleaner than my approach :-) Thanks


text:
Synchronizing http GET and POST request
My project aims to send HTTP GET request to web page(using Arduino UNO and ESP8266-01) then receive response, extract wanted values from response and react with(for example turn on LED1,LED3) then resend led's status to another web page to be inserted in mysql database using HTTP POST in order to make sure that Arduino received the command and executed successfully (in an infinitive loop).
Each request HTTP GET or HTTP POST works fine alone, but when trying to do that in a sequence HTTP GET then HTTP POST inside the loop I got bad result shown in serial monitor like unknown strange characters.
Here is my loop :
void loop() {
  if (millis() - lastTimeMillis > 40000) {
    lastTimeMillis = millis();
    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();
    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"" + server + "\",80");
    delay(1000);
    printResponse();
    String cmd = "GET /ard/sensor.php HTTP/1.1\r\nHost: localhost";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);
    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }
    if (ESP8266.available()){
    Serial.write(ESP8266.read());
    }
  Value1=(digitalRead (LED_PIN1));
  Value2=(digitalRead (LED_PIN2));
  Value3=(digitalRead (LED_PIN3));
  Value4=(digitalRead (LED_PIN4));
 data = "Value1=" + Value1 + "&Value2=" + Value2 + "&Value3=" + Value3  + "&Value4=" + Value4;
  httppost();
}

And here is

httppost()

void httppost () {

    ESP8266.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");
    if( ESP8266.find("OK")) {
    Serial.println("TCP connection ready");
    }
    String postRequest =
    "POST " + uri + " HTTP/1.0\r\n" +
    "Host: " + server + "\r\n" +
    "Accept: *" + "/" + "*\r\n" +
    "Content-Length: " + data.length() + "\r\n" +
    "Content-Type: application/x-www-form-urlencoded\r\n" +
    "\r\n" + data;
    String sendCmd = "AT+CIPSEND=";
    ESP8266.print(sendCmd);
    ESP8266.println(postRequest.length() );
    delay(5000);
    if(ESP8266.find(">")) { Serial.println("Sending.."); ESP8266.print(postRequest);
    if( ESP8266.find("SEND OK")) { Serial.println("Packet sent");
    while (ESP8266.available()) {
    String tmpResp = ESP8266.readString();
    Serial.println(tmpResp);
    }
    ESP8266.println("AT+CIPCLOSE");
    }
    }
}

When uploading this code it seems like only HTTP POST works fine in a loop while HTTP GET having a trouble. So how to make them both work fine in a loop?
Thanks in advance

do you like AT commands? I do not. Use a library https://github.com/bportaluri/WiFiEsp or program the esp8266 with esp8266 Arduino core package https://github.com/esp8266/Arduino#installing-with-boards-manager

Why does one use AT+CIPSEND=4,<N> and the other AT+CIPSEND=<N>?

@Gerben This is the first time I deal with Arduino, may you explain more please ?

Try removing the 4,, or try adding it to both.


text:
Parsing HTTP get response to extract values
Basically I created a web page to control 4 channel relay, then I made an HTTP get request from that page and got the following response:
Linked

T+CIPSEND=4,50

> GET /ard/sensor.html HTTP/1.1
Host: localho
SEND OK

+IPD,4,351:HTTP/1.1 200 OK
Date: Sat, 07 Apr 2018 01:22:58 GMT
Server: Apache/2.4.9 (Win32) PHP/5.5.12
Last-Modified: Sat, 07 Apr 2018 01:17:13 GMT
ETag: "72-56937eec1c277"
Accept-Ranges: bytes
Content-Length: 114
Content-Type: text/html

<p> Relay1 = 1#  </p> </br>
<p> Relay2 = 0#  </p> </br>
<p> Relay3 = 0#  </p> </br>
<p> Relay4 = 1#  </p> </br>
OK

OK
Unlink

Now I want to store Relay1 status (which is 1 here) in a variable, also all other Relays in order to control them high or low
Note : # is supposed to be the separator
and here is my code:
    #include <SoftwareSerial.h>

const int LED_PIN = 13;

String ssid = "ABC";
String password = "a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {

  Serial.begin(9600);
  ESP8266.begin(9600);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

  ESP8266.println("AT+RST");
  ESP8266.println("AT+CIOBAUD=9600");
  delay(1000);

  if (ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  ESP8266.println(cmd);

  delay(4000);

  if (ESP8266.find("OK")) {

    Serial.println("Connected!");

  }

  else {

    connectWifi();

    Serial.println("connect to wifi");
  }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1\r\nHost: localhost";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());

Byte R[ ] = ESP8266.read () ;
Serial write (R[ ]);

//    if (readString.indexOf("Relay1=1">0))
{
    Serial.write("found");
}
  }

}

Any suggestions ?

why do you send it as html like text? send 1001

First of all, I would avoid using the String class, because of the
memory fragmentation issues that come with it. The most obvious solution
is probably to store the result in a character array, then parse the
array, with strstr() or sscanf(), to extract the values you want.
However, this requires storing the whole response in RAM, which is
expensive. A better option is to parse the string as it comes, character
by character, using a kind of finite state machine.
Here is how I would do it. First, I assume you know what you want to do
with these values. Since I don't, I will instead use this dummy function
to just print the values out to the serial port:
static void parse_relay_callback(uint8_t index, uint8_t value)
{
    Serial.print("parsed: relay ");
    Serial.print(index);
    Serial.print(": ");
    Serial.println(value);
}

You will have to replace this with whatever is appropriate for your
application.
Then here is the parser:
static void parse_relay(char c)
{
    static const char templ[] = "RelayI = V#"; // I: index, V: value
    static uint8_t pos, index, value;
    char expected = templ[pos++];
    if (expected == 'I' && c >= '0' && c <= '4')
        index = c - '0';
    else if (expected == 'V' && (c == '0' || c == '1'))
        value = c - '0';
    else if (expected == '#' && c == '#')
        parse_relay_callback(index, value);
    else if (c != expected)
        pos = 0;
}

You just feed it one character at a time, with something like:
while (ESP8266.available())
    parse_relay(ESP8266.read());

Feeding the parser with your response example gives the following on the
serial port:
parsed: relay 1: 1
parsed: relay 2: 0
parsed: relay 3: 0
parsed: relay 4: 1


text:
SD.h causing constant reboot
I have a nice sketch running which monitors a few things and displays output on an OLED display. Now I want to save the data to an SD card, but with or without the card module attached I'm getting constant reboots when I add 1 single line of code:
#include <SD.h>

Any idea what may be happening?

Uno? you run out of SRAM. what is the memory usage report before Upload?

On an Uno or similar small board just including the SD library consumes a quarter of your memory.

Yep that's it, far out :)
I'm also running an SSD1306 display. TIme to optimise. Thanks

Ah. Common situation. There's loads of questions here about "SSD1306 and SD unable to allocate buffer"

There is a "text only" SSD1306 library somewhere that doesn't need an internal buffer to save memory. Can't do graphics, of course...

The following libraries are probably used:

SD Card, using a buffer of 512 bytes (see also the comment of DataFiddler below).
SSD1306 OLED library, using a buffer of 1,024 bytes
Serial, using a buffer of 128 bytes (64 for RX, 64 for TX, see comment of Majenko below)

Since there is only 2,048 bytes of SRAM in an Arduino, this leaves 384 bytes. If you actually READ a file you are already above the maximum.
Your own global variables also will consume a considerable amount of SRAM.
Than, if you execute your sketch, parameters and local variables are stored on the stack (in SRAM), so even if your program starts well, it might/will run in problems when calling functions.

Don't forget 128 bytes for Serial (64 TX, 64 RX) if Serial is being used...

@Majenko Thanks ... I updated my answer.

SD needs 512 bytes for the directory structure, and another 512 bytes later, when it opens a file.

Ta. I've been doing a lot of reading around memory usage and restructured a little to reduce the number and length of string literals. What I find surprising is that the Uno only has 2k but the Nano has 8k. That's a little counter intuitive. Unfortunately my brand new Nano has a broken Micro SD port and overloads my PC and bus shuts down. Gotta get a replacement under warranty so I can finish this project off. Will still optimise the code though.

What was really doing my head in about it is I'm using Visual Micro add for Visual Studio to do my coding and it's not as obvious about the warnings. I switched to Arduino IDE and the warnings were far more obvious.

The percentage is only the percentage BEFORE running, while running more memory is needed.

Btw, also consider using an STM32F103C8T6 (ARM) development board, they are dead cheap, they run Arduino Uno (check if your needed libraries are supported); they have 20 KB SRAM. Also you can consider using external SRAM but you need to either rewrite your own code using that SRAM or rewrite libraries (probably even more time consuming).


text:
Shield SIM808 EVB V3.2 charge a Lithium battery?

hello friends do you know if, can this shield (SIM808 EVB V3.2) charge a lithium battery directly or i need additional hardware?, I know that module has conection for battery but it can charge it?

The module does not include a charging circuit for Lithium-ion cells.

EDIT
According to the SIM808 Hardware Design document, Page 28, the SIM808 module does integrate Lithium-ion cell charging.
It states that the battery should have it's own overcharge, over discharge, over current protection, and reverse-polarity protection.

When I connect the power supply, at the  "Li-ion" terminals there is a voltage of 3.88 v, I think it may be enough to charge lithium cells without problem and the SIM808 shield has an AT command "AT + CBC" which provides information about the battery charging, that is why my question, if I need additional hardware? (protection circuit for Li-ion cells)

It would seem I am incorrect and will correct my answer. Documentation on this module was hard to find, but I have now find this document: https://seeeddoc.github.io/Mini_GSM-GPRS_Plus_GPS_Breakout-SIM808/res/SIM808_Hardware_Design_V1.00.pdf#page=28 which documents lithium-ion battery charging.

attached image about
AT+CBC Command https://www.dropbox.com/s/2gaid1urp8wvk2j/Screenshot_2019-04-17-11-09-26.png?dl=0

@CarlosBravo every LI-ION Battery comes with protection circuit that protects it from overcharge and over discharge

@Vaibhav this is not true. It is possible, and rather easy to purchase raw cells, either in LiPo packs or 18650 cylindrical form which have no protection circuitry. You can/should never assume any LiIon cell has any protection unless you can verify that it's present. It should be readily visible in some way.


text:
Nothing gets sent to Arduino from Processing
I have a problem where I kwow that my bluetooth module (HC-05) is connected to a processing sketch, but nothing ever gets sent from the processing sketch,why?
No error messages but the info never gets sent over because I never see it in Arduino, where it would be printed to the Serial Monitor.
Full Processing Code:
import processing.serial.*;
import controlP5.*;

Serial myPort;
ControlP5 cp5;

int slider1 = 0;
int slider2 = 0;
int slider3 = 0;

void setup() {

  size(800, 800);
  cp5 = new ControlP5(this);
  PFont roboto = createFont("Roboto-Bold.ttf", 1, true);
  ControlFont font = new ControlFont(roboto, 28);
  Controller Aslider1 = cp5.addSlider("slider1")
    .setPosition(85, 100)
    .setCaptionLabel("Red")
    .setRange(0, 255)
    .setWidth(191)
    .setHeight(50);
  cp5.getController("slider1").getValueLabel().setFont(font).align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);
  cp5.getController("slider1").getCaptionLabel().setFont(font).align(ControlP5.RIGHT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);

  Controller Aslider2 = cp5.addSlider("slider2")
    .setPosition(301, 100)
    .setCaptionLabel("Green")
    .setRange(0, 255)
    .setWidth(191)
    .setHeight(50);
  cp5.getController("slider2").getValueLabel().setFont(font).align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);
  cp5.getController("slider2").getCaptionLabel().setFont(font).align(ControlP5.RIGHT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);

  Controller Aslider3 = cp5.addSlider("slider3")
    .setPosition(517, 100)
    .setCaptionLabel("Blue")
    .setRange(0, 255)
    .setWidth(191)
    .setHeight(50);
  cp5.getController("slider3").getValueLabel().setFont(font).align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);
  cp5.getController("slider3").getCaptionLabel().setFont(font).align(ControlP5.RIGHT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0);

  myPort = new Serial(this, "COM5", 9600);
}

void draw() {
  background(255, 100, 100);

  fill(255);
  stroke(1);
  rectMode(CENTER);
  rect(width/2, 350, 200, 75);

  fill(0);
  textSize(32);
  text("Send", width/2 - textWidth("Send") / 2, 350 + 10);

  if (mouseX > width/2 - 100 && mouseX < width/2 + 100 && mouseY > 350 - 75/2 && mouseY < 350 + 75/2) {
    if (mousePressed) {
      fill(100);
      stroke(1);
      rectMode(CENTER);
      rect(width/2, 350, 200, 75);

      fill(0);
      textSize(32);
      text("Send", width/2 - textWidth("Send") / 2, 350 + 10);
    } else {
      fill(170);
      stroke(1);
      rectMode(CENTER);
      rect(width/2, 350, 200, 75);

      fill(0);
      textSize(32);
      text("Send", width/2 - textWidth("Send") / 2, 350 + 10);
    }
  }
}

void mouseReleased() {
  if (mouseX > width/2 - 100 && mouseX < width/2 + 100 && mouseY > 350 - 75/2 && mouseY < 350 + 75/2) {
    fill(100);
    stroke(1);
    rectMode(CENTER);
    rect(width/2, 350, 200, 75);

    fill(0);
    textSize(32);
    text("Send", width/2 - textWidth("Send") / 2, 350 + 10);

    println(hex(color(int(slider1), int(slider2), int(slider3))).toString().substring(2));
    myPort.write(hex(color(int(slider1), int(slider2), int(slider3))).toString().substring(2));
    myPort.clear();
  }
}

Full Arduino Code:
#include <SoftwareSerial.h>
#include <Adafruit_NeoPixel.h>

const int PIN = 6;
const int NUMPIXELS = 30;

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial mySerial (rxPin, txPin);

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

unsigned long currentMillis;
unsigned long loopMillis;
unsigned long waitMillis;
int interval = 100;
int waitInterval = 0;
int redBrightness = 0;
int greenBrightness = 0;
int blueBrightness = 0;
bool wait = false;
bool goToRed = true;
bool goToOrange = false;
bool goToYellow = false;
bool goToGreen = false;
bool goToAqua = false;
bool goToPurple = false;

String hexValue;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mySerial.begin(9600);
  pixels.begin();
  pixels.show();
}

void loop() {

  if (mySerial.available() > 0) {
    hexValue = mySerial.read();
    Serial.println(hexValue);
    if (hexValue != "shiftN" || hexValue != "shiftY") {
      shiftMode = false;
      // value is a hex
      redBrightness = hexValue.substring(0, 2).toInt();
      greenBrightness = hexValue.substring(2, 4).toInt();
      greenBrightness = hexValue.substring(4, 6).toInt();
    } else {
      if (hexValue = "shiftY") {
        shiftMode = true;
      } else {
        shiftMode = false;
      }
    }
  }

  pixels.show();

  setColor(redBrightness, greenBrightness, blueBrightness);

}

void setColor(int red, int green, int blue) {
  for (int i = 0; i < NUMPIXELS; i++) {
    pixels.setPixelColor(i, red, green, blue);
  }
}

Thanks for the help, cheers!
https://discourse.processing.org/t/nothing-gets-sent-to-arduino-from-processing/13654
https://stackoverflow.com/posts/57679763/edit

how do you know that the module is connected to Processing?

@jsotal it blinks twice and then repeats


text:
How do I start a task and have it run for a set amount of time?
I have a project where I need to turn a 24V solenoid on for a set amount of time, then have it turn off. I am rather new to Arduino and not certain how to do this or really where to start. Ideally the time would be displayed on a LCD screen as well but this is purely aesthetic. Any advice, help, examples ect would be appreciated. Thanks!

start with example sketches that blink an LED  ..... these can be found in the arduino IDE

The online example has explanation: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

Use millis();
Record millis() in a long variable like below when the solenoid starts
StartTime = millis();
to switch off solenoid after 60 seconds you may do
if ( (millis() - StartTime)/1000 ) >  60
{
   // switch off solenoid
}

enjoy coding.
There are other ways as well to achieve this... but this is being easiest  and you don't have to wait caused by using delay();

Division is a very expensive operation on many Arduinos. It is thus better to write if (millis() - StarTtime >= 60000).

Hmm.. Good to know that..
But would you explain what do you mean by "Expensive" does it draw more power?

The AVR MCUs do not have hardware support for division, which is thus done by software, bit by bit, and costs quite a lot of CPU cycles. Power consumption should not be affected, unless you care about it. If you do care, you most likely keep the CPU in sleep mode most of the time, and wake it up only when there is work to do. Then, all the cycles you burn doing non-essential operations keep the CPU awake for longer, and cost energy.

Hmm... ok . Thanks  for the information Edgar !!


text:
nodeMCU - when DC is active on pin the do this
i have a nodeMCU v3(esp8266)
and what i want is: when i send  DC 5v or 3v to a pin=D1 (idk if its possible to send 5v directly to pin) then to activate the D0 for 20Seconds
like this:
 if (D1==Sends signal){
    digitalWrite(pinD0, HIGH);
      delay(20000);  //pinD0 is active for 20 seconds

  }else{
     digitalWrite(pinD0, LOW);

  }

you can connect 5v to the gpio through a red LED or a level shifter, then just use digitalRead()

my question is:
if i can ping a D0 pin  from another device  and nodemcu to activate D1 pin for 20 seconds if recived ping(signal) in pin D0


text:
nodeMCU - 2 loops at a time - one continuously and second every 10 seconds
i have nodeMCU v3(esp8266) so i need to make 2 checks
1 check is the pin D1 which needs to be done continuously  and another check is web link check every 10 seconds,
problem is coz when i put delay then it stops the first check
void loop() {

 if (digitalRead(pinD1)==1){
       digitalWrite(pinD0, HIGH);
       delay(20000);
 }else{
       digitalWrite(pinD0, LOW);
 }

      loop2();

}

void loop2(){
   if (json1=="ON"){
    digitalWrite(pinD0, HIGH);
      delay(20000);
}else{
     digitalWrite(pinD0, LOW);
               delay(10000);

  }
}

loop2()  is not a loop, it is a subroutine or a function .... why don't  you give it a descriptive name like updateD0()?

Rather than using delay, use millis() and a variable to check if the some time has expired
void loop()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (digitalRead(pinD1)==1){
            digitalWrite(pinD0, HIGH);
            check = now + 20000;
        } else {
            digitalWrite(pinD0, LOW);
            check = now;
        }
    }
    loop2();
}

void loop2()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (json1=="ON"){
            digitalWrite(pinD0, HIGH);
        } else {
            digitalWrite(pinD0, LOW);
        }
        check = now + 20000;
    }
}