text:
How to control a DRV8266 motor controller with an ESP8266?
https://github.com/sparkfun/SparkFun_MiniMoto_Arduino_Library/tree/V_1.1.0
Will this library work on an esp8266?   If not is there any way I can get this driver to work on the ESP?

As Ignacio kindly pointed out (+1), the answer to my original question is no.

The following code works to control a Sparkfun Minimoto board, though, or more generally the DRV8830.   Just connect GPIO5 to SCL and GPIO4 to SDA.   On some variants the default SDA/SCL pins are different though -- you can always use any pins (except for GPIO0, GPIO2, and GPIO15 -- see my recent post on using these pins) for your I2C bus and just call wire.begin(sda,scl) where sda and scl are the pin numbers you want.
#include <Wire.h>

#define MOTORA_WRITE 0x64
#define MOTORA_READ 0x65
#define CONTROL_addr 0x00
#define FAULT_addr 0x01

void setup() {
  Wire.begin();

  drive(20);//enter values from -63 to 63, where negative values are reverse
  delay(100);
  coast();//releases the motor
  delay(100);
  brake();//brakes the motor

}

void loop() {
  // put your main code here, to run repeatedly:

}

byte tsState = -99;//used so redundant calls of any of these methods don't do anything -- only new calls will trigger communication with the motor controller
void drive(int speed) {
  if (speed != tsState) {
    tsState = speed;
    // Write to the Fault Register to reset it
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);

    // Write to the Control Register
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue;
    regValue = (byte)abs(speed); // Find the byte-ish abs value of the input
    if (regValue > 63) regValue = 63;
    regValue = regValue << 2; // Left shift to make room for bits 1:0
    if (speed < 0) regValue |= 0x01; // Set bits 1:0 based on sign of input.
    else regValue |= 0x02;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}
void brake() {
  if (tsState != -98) {
    tsState = -98;
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue = (byte)63;
    regValue = regValue << 2;
    regValue |= 0x03;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}
void coast() {
  if (tsState != -97) {
    tsState = -97;
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue = (byte)0;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}

No, since it uses AVR defines. Convert the code that uses these defines to the equivalent ESP8266 code instead.


text:
Specified folder/zip file does not contain a valid library
I am trying to use this library.
But when I try to import the .zip file (of the directory) downloaded from GitHub, Arduino IDE says "Specified folder/zip file does not contain a valid library"

This problem really annoying. i can't add any library except from Arduino ide it self. even the most common library not even work, it seems to be a glitched or something.

That's because it contains two libraries, and the IDE doesn't know how to handle that.
Because of this repository structure, you will need to do a manual installation.
Extract the zip file manually and copy the libraries folder into your Arduino sketchbook folder. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.

To be more exact: Copy the content of the libraries folder into the Arduino/libraries folder in your system

@chrisl Nah - just copy the folder. If it doesn't already exist it will do after copying it. If it does exist the OS will just merge the folders together, effectively copying the contents.

source: Stack Exchange

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

sort: votes


text:
Can I make a 455Khz Sine Wave with the Arduino UNO?
Can any one help me, I need to make a sine-wave of 455Khz for use in aligning a Super 7 - AM Radio.
I looked into buying a function generator but I have an Arduino UNO. Can this do the tasks?

No, but realize you don't need a sine wave - a square wave will work too, as it's unlikely that the IF can be mis-tuned to the third harmonic (though you might be confused by that coming in through the front end).  Also, you might be able to use an integer fraction of 455 KHz.  If you wanted to be really, really, clever you could probably use an Arduino to make a sort of PLL synthesizer by dividing the internal oscillator to 455 KHz and having software adjust its calibration so a further division matches some other slow speed reference source.  But there are inexpensive chips you can buy...

The Arduino does not has a DAC (digital analog converter), so you cannot make an output varying in voltage (except for 0V / 5V) by default.
The PWM outputs use 0V/5V with duty cycle but this is not a sine wave.
So you need additional hardware anyway.
Also, regarding speed if you have a DAC. Assume 16 MHz for the Arduino, having a 455 Khz sinewave, you have about 35 clock cycli per complete sine wave. The sine values you can store in a table, but you need probably at least 3 or 4 clock cycli per sine wave value (to fetch the value from the table and to send it to the DAC), this results in about 8 values which will give a very rough sine wave.
So I would go for a separate sine wave generator.

For example, AD9850

Or ICL8038 if you want to go cheaper

If you don't want to buy a chip, and you do have a few other parts laying around, it would not be hard to do a simple oscillator with Op Amps and get a nearly true sine wave.  Alternatively an inverter (74ls04, or any inverting gate chip cmos or ttl) with an R-C can be made into a square wave generator, and another RC or two could get it to approximate a sine wave.

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


text:
Arduino Wifi Works one way but not the other? (ESP32) (Possible Variable Type Problem)
I am working on a code that accepts input from serial monitor and connects to Wifi, and have been getting issues.
my SSID for my wifi is "SamF" but for some reason arduino only likes it when I initialize at the top, not when I accept it from serial monitor even though they are the same..
Example The below code works:
#include <WiFi.h>

char ssid[] = "SamF"; //OR const char* = "SamF"
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
}
void loop () {}

The Code Below Does not work..
#include <WiFi.h>
char pass[] = "secretPassword";
void setup()
{
ssidSerial = my code that receives Serial input and converts to char

for(int k=0;k<=3;k++){
ssidPlaceHolder[k]=ssidSerial[k];
}
const char* ssid = ssidPlaceHolder;
WiFi.begin(ssid, pass);
}
void loop () {}

Everything compiles fine, I debugged by using Serial.print and they are both displaying "SamF" and sizeof(ssid) for both is 4... so I am not sure why one works and the other doesn't? any ideas?
Thanks in advance for any help, and if anyone needs the code after I am done I will be more than glad to share it on git!

add a terminating 0 to ssidPlaceholder end. 4 char string needs 5 char array to have the 5th position set to 0

why do you copy the string from ssidSerial to ssidPlaceHolder and what for is the assignment to ssid pointer?

Thanks for response Juraj, I will try add the terminating 0 to the variable once I get home and will let you know what happens, I copied it over because ssidSerial adds garbage data at the end, because I am using Bluetooth Serial, ssidSerial is "SamF   garbage symbol" and I needed "SamF" that is why I am coping it over.

just to clarify more,  receiving after receiving Bluetooth serial data the variable ssidSerial becomes "SamF   garbage symbol/data" of length 10 which I thought would mess it up.  the wifi library accepts data in the form of a pointer which is why it's there, I know its the same thing as just ssidPlaceHolder but I thought it would help

perhaps you send the new line character(s) \n or \r\n, not garbage

interesting... I will print out the hex value to see what exactly the additional data is

->So the problem was that I had not terminated the char, I didn't know you needed to manually terminate them for some reason. Thanks for answering, please answer the question below so that I can select your answer and you can get reputation!
->Also, If you are wondering or curious, the "garbage data" at the end of the array was some symbols and negative acknowledgments it was ",@NAK?  NAK". Which might be coming from the Bluetooth of the ESP32? maybe it is how Bluetooth ends it's message, I am not too familiar with networking. Thanks again!

Basic string in C is an array of characters terminated by a 0. All functions taking char* or const char* use this 0 to determine the end of the string, because there is no other information about the length of that string.
In your question you copy characters from one characters buffer to other, but you do not set the terminating 0, so the function begin takes the data after the pass pointer until some random memory location with 0.


text:
Arduino button trigger coding
I am trying to write a simple coding to change the color of an RGB LED using a push button trigger.  I just need the the pin output to change when the button is pressed.  I would like to do this using just an ATTiny85 and uploading the code to it using an Arduino Nano.  I don't have much coding experience so I was hoping someone would take a quick look at my attempt and tell me if it will work.
// here are the pin number assignments

int blue = 2;

int green = 1;

int red = 0;

int button = 4; // the pin the button is on.

int choice = 0; // mode selection

void setup() {

  // initialize the pwm pins as outputs.

  pinMode(red, OUTPUT);

  pinMode(green, OUTPUT);

  pinMode(blue, OUTPUT);

  pinMode(button, INPUT);

  analogWrite(red, 255);

  analogWrite(green, 255);

  analogWrite(blue, 255);

}

void loop() {

  // read the pushbutton to see if it's been pushed
  int val;
  val = digitalRead(button);

  // val = HIGH means the button has been pushed
  // and the mode is to be changed.

// SELECT CHOICE //////////////////////////////////////////////////

  if (val == HIGH) {
    choice = choice + 1;

    analogWrite(blue, 255);
    analogWrite(green, 255);
    analogWrite(red, 255);
    delay(500);

    // indicate mode transition with blue flashes
    for (int i = 0; i < 5; i++) {
      analogWrite(blue, 125);
      delay(20);
      analogWrite(blue, 255);
      delay(40);
    }

    delay(500);

    // change this if you want more modes

    if (choice == 5) {
      choice = 0;
    }
  }

  while (val == HIGH) {
    delay(100);
    val = digitalRead(button);
  }

  //////////////////////////////

  // OFF

  if (choice == 0) {
    analogWrite(red, 0);
    analogWrite(green, 0);
    analogWrite(blue, 0);

  }

  // RED

  if (choice == 1) {
    analogWrite(red, 255);
    analogWrite(green, 0);
    analogWrite(blue, 0);

  }

  // GREEN
  if (choice == 2) {
    analogWrite(red, 0);
    analogWrite(green, 255);
    analogWrite(blue, 0);
  }

  // BLUE

  if (choice == 3) {
    analogWrite(red, 0);
    analogWrite(green, 0);
    analogWrite(blue, 255);
  }

  // AMBER
  if (choice == 4) {
    analogWrite(red, 255);
    analogWrite(green, 255);
    analogWrite(blue, 0);
  }

}

Any input?

You could look at the one shot button press example in the Arduino IDE and that change may be able to remove some of the delays in your code that prevent debounce.

The problem with the one shot button example (and apparently with my own code) is the action doesn't stick.  The LEDs only light up when the button is pressed.  When I let go of the button, the LEDs go out.  I need them to stay on when the button is release and change to the next color when the button is pressed again.  Any idea how to make that happen?


text:
Is there any problem in running Arduino logic to 12V LEDs?
I want to run a strip of 300 12V LEDs (Adafruit Neopixels with WS2811), with my Arduino. Is it safe to connect a follows, or is there some "separation" between voltage levels needed?

5V voltage/out and ground (from converter 1) to Arduino Voltage-in and ground.
12V voltage-out (from converter 2) to LED strip voltage-in.
12V ground (from converter 2) to Arduino ground and LED strip ground.
Arduino data pin to LED strip data pin.

WS2811 are (usually) 5V LEDs. What LED strip exactly is it you intend to use?

@Majenko Hmm strange! It's these: https://www.electrokit.com/en/product/rgb-led-slinga-20x-o30mm-2/

Ah right, not quite what I was expecting. Those are separate LED and driver chip arrangements, not the combined driver chip + LED SMD type you normally see. No problem.

The signalling of those LEDs is 5V and the power supply 12V. Basically you have a 5V-powered chip with constant current sinks driving LED chains that are powered from 12V. The 5V power for the chip is created from the 12V power for the LEDs. So, you need to:

Provide +12V and GND to the chain of LEDs from a 12V power supply
Connect the data line to an Arduino
Connect the GND connection to the Arduino as well.

Nothing more is needed.

Great! Thank you! As a beginner I was a bit worried about damaging the Arduino.

@Anna It's a common worry. As long as the 12V doesn't get connected to the Arduino it's fine.


text:
What is this? Looks like a sensor
I got an Arduino kit from my dad.
But inside this box is a thing, maybe a sensor. But I can't find what it is.
Anyone recognize this 'thing' on the picture?

What is written on the chip? Is there anything printed on the reverse of the board?

No it's just a black surface. also the backside is blank.

I can see the ghost of some lettering on the chip. Look closely. You may need a magnifying glass (or even microscope) and some spit to make it visible.

My guess is that it’s a touch sensor. Where you have to touch the white circle. But the number of components on the board makes me doubt that guess.

@Gerben That was my first thought, and main concern, too. Hence wanting to try and find a chip number. Chances are it's just a generic op-amp on there though.

Have you tried hooking it to a 5V supply and connecting it to a Arduino/buzzer?  Then just wave various other items from the kit at it.  But it would be easier to read the writing on the IC, zoom on you phone might work.

To read letters on chips it is good just draw over the chip with chalk (or any other fine powder (be it sugar, baby powder, lady powder...), then decently blow out what is on top and the letters wiil be left powder-filed and readable. Then you can simply remove the rest of powder totally if you wish (with finger, or nearly anything damp/wet). Good trick to know :)

Appears to be a touch sensor that can be found on various on-line retail web pages:
http://www.satistronics.com/
https://www.arduiner.com/
Also, the back may have a URL as this one does:

...however, the URL appears not to function.

The back has no text, but it looks  the same. I followed your link and it shows exactly what I have. Thank you for sharing this with me

The sensor is a K1208043 touch sensor. Here's an updated link.


text:
Interfacing Figaro KE25 Oxygen Gas Sensor with Arduino Uno
I have been trying to interface the Figaro KE25 2 lead fuel cell type oxygen gas sensor with Arduino Uno. I am not getting the required output on the Serial Monitor for regular air (Oxygen concentration of 19%).
I have attached the sketch I have typed out, the output I have obtained on the Serial Monitor, the output(mV) vs Oxygen concentration (%) graph of the Figaro KE25 sensor I have obtained from the datasheet, the chemical reactions governing the working of the sensor,the circuit diagram I have used, and the construction of the sensor.
In this question; I will explain the sensor first, then my circuit, then my sketch, and lastly the problem I have with my output.
In electronics, the Anode is the positive electrode and the cathode is the negative electrode. In electrochemistry, the Anode is the Negative electrode and the Cathode is the positive electrode. Do check the image of the construction of the sensor I have provided obtained from the datasheet.[![image of the construction of the sensor][1]][1] Full Technical Datasheet
The Cathode, that is, the positive electrode is the sensing electrode (Oxygen gets consumed here and an electric current is generated). Since a current is being generated by the sensor (fuel cell), no power supply needs to be given to the sensor. Check the image of the chemical reactions provided (obtained from the full technical datasheet of the sensor). Technical Datasheet
The sensor in question is an analog voltage type sensor. Keeping this and everything I have mentioned above in mind, I have constructed the following circuit with Arduino Uno. Refer the picture I have put up. I have connected the Cathode (the sensing positive electrode, red in colour) to the Arduino's analog A0 pin and the Anode (negative electrode) to the Arduino's ground.
The sketch I have used is as follows:
 /*the analog pin of the alcohol sensor goes into analog pin A0 of the
 Arduino*/

 void setup()
 {
     Serial.begin(9600); //sets the baud rate
 }

 void loop()
 {
     float v1;
     float oxy = 0.0;
     float v2 = 0.0;
     pinMode(A0,INPUT_PULLUP);

     /*To make sure that reading is zero when the circuit is open*/

     v1 = analogRead(A0);

     /*reads the analog value from the Oxygen gas sensor and this value can
     be anywhere from 0 to 1023 (10 bit ADC used in Arduino Uno)*/

     if(v1>900) //To make sure that reading is zero when the circuit is open
     {
         v1=0;
     }
     v2 = (v1*3000)/992;

     /*The above line calculates the output of the sensor in mV using the
     fact that a HIGH reading in an input pin of an Arduino Uno board is
     equivalent to a voltage of 3V or higher. When I displayed just 'v1',
     the lowest of the high values I got was 992. So I equated it to 3V
     (3000mV) and used the unitary method to find out what a non-HIGH v1
     value would be in terms of mV.*/

     oxy = v2/0.6;

     /*The above line calculates the Oxygen concentration from the mV output
     of the sensor using the output(mV) vs concentration(%) graph from the
     sensor's datasheet. The graph is a straight line passing through (0,0)
     and hence the governing equation is of the form y = m * x. Where 'y' is
     'v2' and 'x' is Oxygen conc. in %.*/

     Serial.print("Oxygen value: ");
     Serial.print(v1);
     Serial.print("    ");
     Serial.print(v2);
     Serial.print("mV    ");
     Serial.print(oxy);//prints the Oxygen value
     Serial.println("%");

     delay(1000);
 }

he output(mV) vs Oxygen concentration(%) graph provided in the datasheet is shown below. The straight line labeled as 'KE25' is to be considered.  Product information (datasheet)
he output I have obtained on the serial monitor is as follows:

Such a high voltage from the sensor is not possible. My output reading is not possible at all. Where have I made a mistake and how do I correct it?

Update 1 : I changed the line pinMode(A0,INPUT_PULLUP) to pinMode(A0,INPUT). Now I am getting sensible values on my Serial Monitor. However, I am also getting many '0' outputs (many). I am also getting many random values (many). I need more information on how to interface a fuel cell type Oxygen sensor using Arduino Uno in terms of how to get a proper voltage reading across such a sensor. I have found no question on electrochemical, fuel cell type Oxygen gas sensor interfacing. All questions asked are regarding sensors that require a power supply. In case of fuel cell type Oxygen gas sensors, current is generated when Oxygen is sensed and hence, no power supply is required. Also, if anyone is into electrochemistry, how do I check the voltage output of a fuel cell type Oxygen gas sensor using a voltmeter? Do I use a DC voltmeter or an AC voltmeter?
Update 2: I've made changes to the code based on @EdgarB's suggestions. The output I am getting now is better but still wrong. I checked if the sensors I am using are functional using a multimeter (I confirmed if the method I am using is right, and it is), and they are. The Oxygen values I am getting now are still really low: 6-8%. I should be getting: 19-21%. I used a reference voltage of 600 mV and modified the code.
Modified code:

 void setup()

 {

     Serial.begin(9600);//sets the baud rate
     analogReference(INTERNAL);
 }

 void loop()
 {
     const float A_REF = 0.6e3;
     const float Scalc = (1/0.6);

     float v1;
     float oxy = 0.0;
     float v2 = 0.0;
     pinMode(A0, INPUT);
     v1 = analogRead(A0);
     v2 = (v1 * A_REF) / 1024;
     oxy = v2 * Scalc;
     Serial.print("Oxygen value: ");
     Serial.print(v1);
     Serial.print("    ");
     Serial.print(v2,4);
     Serial.print("mV    ");
     Serial.print(oxy,4);//prints the Oxygen value
     Serial.println("%");
     delay(1000);
 }

Output:

If you remove the pinMode(A0,INPUT_PULLUP); does it improve the readings?

Read this page: https://www.arduino.cc/en/Tutorial/AnalogInputPins - Especially the bit entitled "Pull-up resistors".

@Majenko Thanks! That really helped. I changed pinMode(A0,INPUT_PULLUP); to pinMode(A0,INPUT);I had read that page before typing out my sketch, but I didn't pay much attention to the line that said: "Be aware however that turning on a pull-up will affect the values reported by analogRead()." Is this because in a short time interval like 1000 ms there isn't enough time for the voltage to drop to low and then rise again to the correct input given from the sensor?

Your problem stems from having the internal pullup resistor for A0 turned on.
The sensor is a current generator with a load resistor (plus thermistor) built in to convert the current into a voltage. By adding a pullup resistor you turn it into a voltage divider across 5V with a small current being injected into the central node:

simulate this circuit – Schematic created using CircuitLab
Since the datasheet doesn't specify the load resistance nor the source current I have made up some values to demonstrate.
If we take just the current source and load resistance RL+RT and calculate the voltage drop across that we get:
V=R×I = 5000 × 0.00001 = 50mV

Which is a reasonable value. It's a lot of oxygen, but that's because these are made-up values.
Now what would be the voltage with the pullup resistor added? Well, this is where it gets a little more complex. At times like this it's easier to just simulate the circuit in something like the falstad simulator and I can tell you it's 757.1mV (If you want to learn how to do this kind of circuit analysis manually you should learn superposition theory).
A massive change.
Obviously you're not seeing a change that big - and that's because the pullup resistor is more than just a simple resistor. There's many more factors that influence the reading, including the output impedance of the network, as well as the rest of the internal ADC circuitry.
Suffice it to say, though, adding a pullup resistor is a bad idea when using the ADC.
But you want to keep the pullup resistor so you can know if the sensor is connected or not. That's not a problem. Just turn it on and off at will:
pinMode(A0, INPUT_PULLUP);
delay(1);
bool connected = analogRead(A0) < 900;
if (connected) {
    pinMode(A0, INPUT);
    delay(1);
    v1 = analogRead(A0);
}

It's recommended to wait a moment after changing the pullup resistor state before reading from the ADC to reduce electrical noise picked up by the ADC - hence the delay(1) calls.

You calculation of v2 is incorrect.
v2 = (v1 * 3000) / 992;

The maximum value v1 will have is 1023 and this equates to 5v (not 3v).  So to calculate the voltage v2 I think you should be doing:
v2 = (v1 / 1023) * 5000;

But this will make your calculations even further out!

The maximum voltage at a pin that is configured as OUTPUT is 5V in a 5V Arduino Uno board. However, on the same board, if a pin is configured as INPUT, then the voltage at the pin is 3V or higher. Check [https://www.arduino.cc/reference/en/language/variables/constants/constants/]

I was just reading what analogInput() said.

You have three different issues here:

improper use of the pullup resistor
incorrect interpretation of the analog reading
too small input signal

Pullup resistor
Majenko already covered the first issue, with very good advice.
Interpretation of the analog reading
Code Gorilla already explained the second issue. However, since you do
not seem to understand, I will add my take here.
The formula to convert an analog reading to an actual voltage is
voltage = reading × analog_reference ÷ 1024.
Yes, it's 1024 rather the often seen (but erroneous) 1023. See the
manufacturer's datasheet, which is the only authoritative
reference. Doesn't make much of a difference anyway. The main issue is
the analog reference voltage which, in the default configuration, is the
same as the voltage powering the Arduino, i.e. 5 V.
In a comment, you wrote:

if a pin is configured as INPUT, then the voltage at the pin is 3V or
  higher

This is complete nonsense. The voltage on an input pin is whatever
voltage is provided by the circuit connected to that pin. If you
actually mean the threshold voltage for the pin reading HIGH, well,
that threshold is typically 2.6 V (see the “typical
characteristics” in the datasheet), but the exact value is not
guaranteed. The number you quote is “the lowest value where the pin is
guaranteed to be read as high”. In other words, the voltage threshold
can be lower than 3 V, but not higher.
And all this is completely irrelevant to you. The input thresholds are a
feature of the digital input circuitry attached to the pin. This circuit
is responsible for deciding whether the pin is LOW or HIGH when you
digitalRead() it. But you don't care about the digital value: you are
using the pin as an analog input. The ADC converter is a different
circuitry that has absolutely nothing to do with the digital input.
You can even disable the digital input of the pin and still use the ADC.
Low signal
According to the graph you provide, the sensor should output
12.6 mV in normal air (21% O2). That's about
2.58 ADC steps. Thus you expect the reading to fluctuate between
the digital values 2 and 3. This is really quite low for your ADC.
A simple way to mitigate this problem is to change the analog reference.
The default is 5 V, but you can switch it to an internal
1.1 V reference that will significantly increase
your resolution: in setup(), call
analogReference(INTERNAL);

Then you can compute the oxygen level as follows:
const float A_REF = 1.1e3;         // analog reference = 1,100 mV
const float SENSOR_CAL = 1 / 0.6;  // calibration: %(O2) / mV

void loop()
{
    int reading = analogRead(A0);
    float voltage = reading * (A_REF / 1024);
    float oxygen = voltage * SENSOR_CAL;
    // ...
}

Another way to mitigate the signal weakness is to average multiple
readings. This can make your effective resolution better than the raw
ADC resolution.
ADC offset
The formula
voltage = reading × analog_reference ÷ 1024
applies only to an ideal ADC. In practice, any ADC has some offset error
and gain error. Taking them into account, the formula becomes:
voltage = (reading + offset_error) × analog_reference ÷ (1024 + gain_error)
In many cases these errors are too small to care about. However, since
you are working near the resolution limit of your ADC, the offset error
can be an important concern. The gain error is no issue here, so you can
forget about it.
If you have a voltmeter, you can easily determine the offset error:
measure a low voltage, like the one from your sensor, with both the
voltmeter and the ADC. Ideally, you would average many ADC readings to
get a better resolution. From the voltmeter measurement, you compute the
average reading you would expect from your ADC, then you get
offset_error = expected_ADC_reading − actual_ADC_reading
Then you use this measured offset to correct your readings:
const float offset_error = ...;  // measured with the voltmeter

void loop()
{
    int reading = analogRead(A0);
    float voltage = (reading + offset_error) * (A_REF / 1024);
    // ...
}

I meant that if a pin is configured as INPUT and is at HIGH then the voltage at that pin is 3V or higher. I will read the rest of your answer and update on  the status soon.

@athindrapavan: Understood what you mean, but: 1. It's wrong (a pin can read HIGH even at 2.2 V) 2. It's irrelevant to an analog reading.

First of all, thanks! That helped in getting a better, more precise output. Plus, I understand the assignable constants better now. But I'm still getting a wrong output in terms of the range of Oxygen percentage values I should be getting. I'm getting around 6-8% of Oxygen which is still too low. It has to be 19-21% in regular air. I checked if the sensors I am using are functional with a multimeter and they are. I'll update the question with the modified code and the output I am getting in some time. Please do check it.

@athindrapavan: 1. The internal analog reference is 1.1 V, not 600 mV. You cannot just make up a number and expect that to work. 2. You may also suffer from ADC offset error. See the amended answer.

@ EdgarB Your answer made a lot of sense and the setup is working now. Is the offset error value sensor dependent? That is if I use 2 new Figaro KE-25 sensors, then will it cause an error in one of the 2 sensors depending on which one I used to calculate the offset error?

@athindrapavan: No, the offset error is intrinsic to the ADC. It should not depend on the sensor. It may depend though on whether you are using analogReference(DEFAULT) (i.e. Vcc) analogReference(INTERNAL) (i.e. 1.1 V).

So since I've used the latter, it's intrinsic to the ADC? Also, thanks a ton! Your answer was very detailed and a lot of help.


text:
Run Time Error in arduino
I am trying to communicate multiple clients to a server, all using nodeMCUs. I am getting a weird run time error at the Server Serial Monitor of Arduino IDE when I upload the code.
Here's my server code:
#include <ESP8266WiFi.h>
#define Max_Clients 5

WiFiServer server(80);
WiFiClient *clients[Max_Clients] = {NULL};
String inputs [Max_Clients] = {""};                           //Initializing to store the string received from clients

void setup() {
  pinMode(D1,OUTPUT);                                         //Intializing pins for showing output and input
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);
  pinMode(A0,INPUT);

  Serial.begin(9600);                                         //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP);                                         //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678");                      //Provide the (SSID, password)

  IPAddress myIP = WiFi.softAPIP();                           //Obtain the IP of the Server
  Serial.println("Server IP is: ");                           //Print the IP to the monitor window
  Serial.println(myIP);
  server.begin();                                             //Start the HTTP Server
}

void loop() {
  WiFiClient client = server.available();                     //Check if a new Client has connected to the server

if (client) {
Serial.println("A new Client has connected :)");

for (int i=0 ; i<Max_Clients ; ++i){              //Acknowledges and sets up new clients
  if (NULL == clients[i]){
    clients[i] = new WiFiClient(client);          //nothing in clients[i] means it is a new client
    break;
    }
  }
}

for(int i=0 ; i<Max_Clients ; ++i){                           //For available clients
  if (NULL != clients[i] && clients[i]->available()){
    String request = clients[i]->readStringUntil('\r');
    Serial.println("The string of client "+String(i+1));    //Print client's message
    inputs[i] = request;
    Serial.println(inputs[i]);

    int duty[4];
    duty[i] = inputs[i].toInt();

    if (i == 0){
      analogWrite(D1, duty[i]);
      clients[i]->println("To client 1.\r");
    }
    if (i == 1){
      analogWrite(D2, duty[i]);
      clients[i]->println("To client 2.\r");
    }
    if (i == 2){
      analogWrite(D3, duty[i]);
      clients[i]->println("To client 3.\r");
    }

    clients[i]->flush();                                    //Waiting for transmission to complete
    clients[i]->stop();
   }
  }
 }                                                                 //void loop closure

Here's my client code (which will be same for all clients):
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

IPAddress server(192,168,4,1);

void setup() {
  pinMode(A0,INPUT);
  pinMode(D6,OUTPUT);

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

  Serial.begin(9600);                 //Serial connection
  WiFi.begin(ssid,password);          //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server, 80);   // Connection to the server
  }

void loop() {

  if(WiFi.status() == WL_CONNECTED){   //Check WiFi connection status

    int sense = 200;
    client.println(sense+"\r");  //Client's message to the server
    String answer = client.readStringUntil('\r');         //Reading response from the server
    Serial.println("from server: " + answer);             //Printing the response
    client.flush();

    delay(3600000);
    }
  else{
    Serial.println("Error in WiFi connection");
    }
  }

On uploading this code, the Serial Monitor at the server shows:

A new Client has connected :)
  The string of client 1
  nt8_t* BufferedStreamDataSource::get_buffer(size_t) [with TStream = >ProgmemStream; uint8_t = unsigned char; size_t = unsigned int]
  The string of client 1

While the Serial Monitor at the client shows:

Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connected.
  from server: To client 1.

I have no clue of the source of this error. Any help is appreciated.
Thanks in advance.

do not use port 80 if it is not HTTP. use port 23 or 2323, which indicates plain socket communication (telnet). and you can test the server from a telnet client.

You shouldn't use 23 since that implies an interactive connection. You should use any port but 80 - ideally not use a port associated with any known protocol. But it really doesn't matter on an embedded system what port you use...  Btw - telnet can connect to any port - even 80.

Well, I have used the port successfully before to establish the connection. What other ports are available?

ports until 1023 are reserved https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

I suspect the problem stems from the client side.  This line:
client.println(sense+"\r");  //Client's message to the server

doesn't do what you think it does.
sense is a number (200).  "\r" is a string constant located at an address in memory.  When you add the two together you are not concatenating two strings, but you are adding 200 to the address of the string constant - and then sending whatever it finds at that location.
The "\r" is actually redundant anyway, since you are using println which adds \r\n to the end of a print. However if you do want to do it manually you just need to split it into two prints:
client.print(sense);
clienr.print("\r");

Can I just make 'sense' a string? It should pass as a String and will make changes at the client.

You could, but why? It's wasteful of resources and would have no benefit.

Research WL_CONNECTED, I think you find that is the connection state to your Access Point not the state if a device has connected, also their are issues with this variable.
It doesn't change state when the connection is dropped.
to make a connection you need to make a GET or POST request to a page on your server something like...
if (client.connect(server, httpPort)) {
    // connected to resource
    // send data
    client.print("GET /myfile");
    client.println(" HTTP/1.1");
    client.println("Host: IPADDRESS");
    client.println("Connection: close");
    client.println();
  } else {
    // No connection to server
    // should maybe keep retrying else waits till next call
  } // end if connect
Your server code needs to server a page and keep checking for connection with
webServer.on("/", doRoot);
Then have a function that writes the HTML back to client like...
void doRoot() {
    // write HTML
    String html;
    html = "";
    html += "My Page";
    // and send it
    webServer.send(200, "text/html", html);
  }

Sorry I cant work the formatting out for this site, I use enter code and it says enter code here but when pasted its trash

Yes, code blocks and enumerated lists don't work well together.

WiFiClient is a TCP socket. it can be used as it is. there is no need to use HTTP protocol between two devices. but it is not nice to use port 80 which is in standard reserved for HTTP.

This might work good for web server based communication. However, in my case, one of the nodeMCUs is the server.


text:
I cannot upload any code to my arduino uno
I am using ardunio uno on a windows 10 machine.
I have never been able to upload any code whatsoever.
Every time i get different errors, sometimes it's about com port, sometimes about memory, baud rate and what not.
This time I am getting the following error.
What should I do next?
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core
Linking everything together...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/..\arduino_cache_625197\core\core_arduino_avr_uno_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982" -lm
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.eep"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex"
Sketch uses 1030 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM5": The semaphore timeout period has expired.

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Is it a genuine Arduino or does it have the CH340 USB to serial chip on it?

how did you choose COM5 serial port?

What board are you using? Is it a clone? Any chance of a picture?

If you have arduino with ch340 you need to install driver for board.

The OP seem to have a COM port ready (COM5), which means the driver is already installed.


text:
Problem uploading code to ESP 8266-01 adapter
I feel like I've tried just about everything and it still doesn't work. There must be something I'm not seeing. I am using an Arduino uno, an ESP8266-01 wifi module, and an ESP-01 Adapter. The arduino is connected to the laptop, and I'm using 4 AA batteries as external source (they are brand new) because I wanted to check if my Arduino wasn't supplying the necessary power.
I keep getting the following error:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
I changed my preferences to add to the boards http://arduino.esp8266.com/versions/2.4.1/package_esp8266com_index.json
This is how I set up tools. I keep trying every upload speed whenever I make a change to see if that makes it work but nothing still.

I also tried using this tutorial but it also didn't work.
Any help would be appreciated :)

using Uno instead of USBtoTTL adapter is a workaround that doesn't work with some Unos

Try this: https://tttapa.github.io/Pages/Arduino/ESP8266/Flashing/Flashing-With-an-Arduino.html

I tried it but it still didn't work. Has anyone actually build that themselves? like... any tips? I feel like I followed the instructions by the letter.

@KennethYoung, you think Pieter (tttapa) wrote it in the tutorial without trying?

@Juraj well, the idea was to ask if anyone that did it had any tips, like common problems or easy to miss details or something

I tried it for fun it and it didn't work at all. And I am an experienced troubleshooter. I tested with Seeeduino Lotus with CH340 and with Uno WiFi which in this case should be equivalent to original Uno R3 Made in Italy with ATmega16U2. But normally I use an USBtoTTL adapter to program an esp8266 module.


text:
Averaging input from multiple input over a fixed amount of time (estimated)
I am trying to average input values for a number of inputs and have it then store those averages into a string to write to a txt doc on a sd card.
I am using:
// read 6 sensors and append to the string:
for (int analogPin = 0; analogPin < 6; analogPin++) {
  int sensor = analogRead(analogPin);
  dataString += String(sensor);
  if (analogPin < 6) {
    dataString += ",";
  }
}

to read the pins at the moment, but I want to change the analogRead(analogPin) to an average value and then use the averages to create the string.
but when I try to average the data I run into errors, or I get output that is 0 for something that should be higher (3.3V).
I am doing this to stabilize my values a bit better and remove jitter.
Any suggestions?

Can you show us your entire sketch?

take 10 readings, discard the highest and the lowest, then average the remaining 8 readings

https://github.com/MajenkoLibraries/Average

This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.
int aveAnalogRead(int pin, int ave=10, int delayms = 0)
{
    int tot = 0;
    for(int i=0; i<ave; i++)
    {
        tot += analogRead(pin);
        if(delayms) delay(delayms);
    }
    return tot/ave;
}

in your loop():
for (int analogPin = 0; analogPin < 6; analogPin++)
{
   int sensor = aveAnalogRead(analogPin);
     <<do your work here>>
}

There is almost never a good reason to add a delay.

With this though I have to run it multiple times, one for each input. Is it possible to have it also cycle though the inputs such as a loop within a loop?

yes use it inplace of your analogInput call above loop within a loop

so this:`int pin,
for (int n=0, n<10, n++){
pin = n;
int aveAnalogRead( int ave=10, int delayms = 50)
{
int tot = 0;
for(int i=0; i<ave; i++)
{
tot += analogRead(pin);
delay(delayms);
}
return tot/ave;
}}`

that's not how C++ works; you put this function somewhere outside your loop() on your sketch, then call then function. you don't need to copy the definition of the function to call it.

@EdgarBonet depends on what your sampling; one could remove it, or set it to 0, i just wanted to show how to do it with that in case its needed.


text:
Cannot load anything from library
So I installed libraries through the Arduino interface (Sketch > Include Library > Manage Library). Then I check: C:\Users\username\OneDrive\Documents\Arduino\Libraries, and I confirm the new libraries are there.
However, when I compile I always get the error that Arduino cannot find the library, no matter which one I try to import.
I'm on Arduino 1.8.5, Windows. What am I missing?

Does this answer help? https://arduino.stackexchange.com/questions/51813/this-error-is-shown-continuosly-after-first-time-it-compiles-successfully/51825#51825

@VE7JRO OH MY GOD!! It was OneDrive!?? What the what!? Thanks, this solved it.

This was a problem with using your OneDrive folder.
duskwuff wrote:

This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

The issue with OneDrive folders has been resolved as of version 1.8.6.
https://www.arduino.cc/en/Main/ReleaseNotes

ARDUINO 1.8.6 2018.08.23
[ide]

Updated arduino-builder to 1.4.0:

parallel build (improve compile speed)
better reuse of already compiled files
Windows: fixed build for sketch stored under OneDrive cloud folders

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.


text:
Too many amps for Step motor
I have an adafruit motor shield and attached the Nema 17 stepmotor. Now the big problem is trying to power it without it overheating. I was originally using a 12v 6a power supply but quickly switched to a 12v 2a and then a 12v 1a. All of them still make the Nema stepper motor very hot.
I'm using the accelstepper and adafruit modules on the arduino to control the stepper motor. I noted that the magnets are all always on in my code which might explain why it gets hot but I need to maintain some form of torque for the system I'm developing.
I will attach code as that might be the problem. Is there a second device I need to attach to the adafruit motor sheild and the nema stepper motor.
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

int ComControlValue = -1;

/* Define pins for motor and define step motor function */
const int SlowStepPerRev = 400;                              // Define slow speed constant
const int MotorB = 2;
int rpm = 60;                                                // Rotation per minute
int acelspeed = 40;                                          // Acceleration speed
int distrot = 200;
int destinationunknown = 0;                                  // Destination of plate 1

/* Initialize the stepper library on the motor shield */
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotorB = AFMS.getStepper(SlowStepPerRev, MotorB);

/* you can change these to SINGLE or DOUBLE or INTERLEAVE or MICROSTEP! */
// wrappers for the motor!
void forwardstepB() {
   myMotorB->onestep(FORWARD, INTERLEAVE);
}
void backwardstepB() {
   myMotorB->onestep(BACKWARD, INTERLEAVE);
}

AccelStepper stepperB(forwardstepB, backwardstepB);

void setup() {
   Serial.begin(115200);                                     // Establish Serial connection to computer
   Wire.begin();                                             // join i2c bus as master
   AFMS.begin();                                             // Begin useage of conveyorbelt motor

   stepperB.setMaxSpeed(rpm);                                // Initialize max speed
   stepperB.setAcceleration(acelspeed);                      // Initialize and set speed of acceleration for spinning
}

void loop() {
   switch(ComControlValue){
        case -1: //wait
            Serial.println("Waiting for Command");
            Serial.println(stepperB.currentPosition());
            while (Serial.available()==0){}
            ComControlValue=Serial.parseInt();               // Pull value from serial port
            break;                                           // break loop & return to start
        /* 1 : Move plates into the system */
        case 1:
// Arduino using accelmotor, move to position X
        if (plateNum < platelimit){
               plateNum++;
               ComControlValue= 11;                          // After establishing plate num & location, move to case 11 to start stepmotor movement
               destinationunknown = destinationunknown + 200;
        }
        else {
               ComControlValue = -1;                         // To many plates, cancel move command
        }
        stepperB.moveTo(destinationunknown);
        break;

        /* 2 : Move plate out of system */
        case 2:
        // Arduino using accelmotor, move to position Y
        if (plateNum > 0){
               plateNum = plateNum--;
               ComControlValue= 11;                         // After establishing plate num & location, move to case 11 to start stepmotor movement
               destinationunknown = destinationunknown - 200;
        }
        else {
               ComControlValue = -1;
        }
        stepperB.moveTo(destinationunknown);
        break;

        /* 1 : Run Stepmotor to completion */
        case 11:
        // Step motor requires an uninterrupted while loop to move to completion
        // code setup will utilize while loop and allow for movement
        stepperB.run();                                     // run stepmotor
        if (stepperB.distanceToGo() == 0 ){
                ComControlValue = -1;                       // Completed movement, go back to case -1
        }
        break;
   }
}

Stepper motors get hot. It's a fact of life. More so when they are held stationary.
A typical 12V Nema 17 stepper motor has a coil resistance of 30Ω per phase. With 12V across a single phase it will consume 0.4A.  That is the equivalent of about 4.8W of power. That comes out in the form of heat.
Reducing the current capacity of your power supply will not "fix" the problem. All that will happen is that as you go to lower and lower current supplies the supply will get hotter and eventually break.
You can test the coil resistance of your motors with a DMM set to the Ohms range, then calculate the power dissipation using:
Current = V ÷ R = 12 ÷ <measured resistance>

and:
Power = V² ÷ R = 144 ÷ <measured resistance>

Also if you go with decreasing the voltage (instead of reducing the current value), you would have to compromise with a decrease in torque.

Sounds like the 12v 1a power supply should be used then and just compromise with the head via heatsinks

You have 2 phases. That's a potential peak of 0.8A for just the motors alone. I would derate it and use at least the 2A. You can't have "too many" amps - it only draws what it needs.

I think you will have a better chance reducing the heat by lowering the supply voltage (which will reduce the current as a consequence). You won't get the nominal torque if you go below 12V, but this is a compromise and there's no free cheese there.
Limiting the available current only works in a predictable manner with power supplies which can work as current sources. If your power supply is only a voltage source, then trying to draw more current than it can provide will eventually result in the power supply going into self-protection (not delivering any voltage) or breaking down. With voltage sources, maximum current is a limit you have to respect, not a limit the power supply will impose.


text:
fatal error: avr\wdt.h: No such file or directory in Arduino Due
I am using an Arduino Due for vehicle tracking with a GPS/GPRS device. Before using Arduino Due I used an Arduino Uno. When I tryi to load my code in the Arduino Due, it shows me "fatal error: avr\wdt.h: No such file or directory". I can't delete the watchdog from my code as it is important for my device.
Now how can I solve this problem?

I googled this library https://www.arduinolibraries.info/libraries/sodaq_wdt

The Due is a very different board than the Uno. It uses a completely different architecture (ARM vs AVR). You can't use AVR-specific  code on an ARM chip, and the Watchdog code is AVR-specific.
You will have to find (or write) the equivalent ARM code using the Due's register set instead.

the question is "Now how can I solve this problem ?"

This may help: http://forum.arduino.cc/index.php?topic=350058.msg2416416


text:
Why are commands executing on their own?
This is the program I have used. It's working fine. But I don't known why sometimes it operates on its own. It is used to control a welding machine (Arduino is isolated from earthing). When there is a little vibration the code executes a command. This is the code:
int a = 9;  //right actuator forward relay 1
int b = 12; //right actuator reverse relay 2 (orange 10)
int c = 10; //left actuator forward relay 4
int d = 11; //left actuator reverse relay 3
int x = 0;
int y = 0;
const int stepPin = 8; // HIGH =DOWN; LOW == UP
const int dirPin = 7;

void setup() {
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(b, HIGH);
  digitalWrite(d, HIGH);
  delay(2000);
  digitalWrite(b, LOW);
  digitalWrite(d, LOW);
  delay(1000);
  Serial.println("press the foot swtich"); // Serial Monitor for Debugging
}

void loop() {
  int Val = digitalRead(5); //   Actuator 1 Clamping
  int ValR = digitalRead(6);//   Actuator 2 Clamping
  int ValS = digitalRead(4);//Stepper Motor anticlockwise
  int ValM = digitalRead(2);//Stepper Motor Clockwise
  if (Val == LOW && x == 0  ) {
    Serial.print("Val000=");
    Serial.println(Val);
    digitalWrite(c, HIGH);
    delay(1750);
    digitalWrite(c, LOW);
    x = 1;
    Val = digitalRead(5);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (Val == LOW && x == 1  ) {
    digitalWrite(d, HIGH);
    digitalWrite(b, HIGH);
    delay(2000);
    digitalWrite(d, LOW);
    digitalWrite(b, LOW);
    x = 0;
    Val = digitalRead(5);
    Serial.println("fwd");
    y = 0;
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 0 ) {
    digitalWrite(a, HIGH);
    delay(1350);
    digitalWrite(a, LOW);
    y = 1;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 1 ) {
    digitalWrite(b, HIGH);
    delay(1200);
    digitalWrite(b, LOW);
    y = 0;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValS == HIGH) {
    Serial.println(Val);
    Serial.println("up");
    digitalWrite(dirPin, HIGH);
    // Enables the motor to move in a particular direction
    // Makes 100 pulses for making half cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
  if (ValM == LOW) {
    Serial.println("down");
    Serial.println(ValR);
    digitalWrite(dirPin, LOW);
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
}

By “it operates on its own” do you mean it acts as if the buttons are pressed, including printing the debugging output? 2. The internal pullups enabled by INPUT_PULLUP are quite weak (around 30 kΩ). In a noisy environment, you way want to use stronger external pullups (i.e. lower resistance).

yes its act like the button is pressed, on serial debugging also and the machine runs too. Can debouncing solve if yes how can I add it?

Debouncing may help if it does also deglitching. But it is probably safer to have a clean signal to start with. Thus I would try the weak pullup first. How much distance is there between the buttons and the Arduino board?

What exactly is happening? What messages are you seeing on the serial monitor? Could it be loose wires or wires touching? More information will help us help you.

anyone one of the if() loop starts randomly. There is a relay which used to switch on the welding gun.. it is not controlled by arduino it is independent ... but whenever the relay activates, the arduino execute a if statement.... no wires are loose

Are 10k resistor enough for stronger signals?

I would go straight to 1 kΩ. Also, if your buttons are more than, say, 10 cm from the Arduino board, I would wire them with a twisted pair (signal and ground on the same pair) in order to prevent inductive pick-up.

@EdgarBonet Please don't answer in comments. This totally goes against the Stack Exchange model. Make an answer.

Comments under questions are for seeking clarification of the question. They are not for making mini-answers.

Can you give details of your circuit hardware, in terms of whether wiring is soldered or breadboard/push fit together.  If you had a loose connection that would be susceptible to vibrations.

SOLDERED.  there is strong electro magnetic feilg by the welding  gun relay

Trying to write a proper answer...
According to your description, it looks like you are victim of inductive
noise pickup. The circuit [MCU → Arduino ground pin → foot pedal →
Arduino digital input pin → MCU] is a loop that can pick up magnetic
flux. If this flux varies, either because the magnetic field varies
(ambient electromagnetic noise) or because the geometry of the circuit
changes (you move the wires), this will induce an electromagnetic force
that can make your Arduino read LOW even when the button is not
pressed.
There are two things you can try to overcome this effect:

Replace the weak internal pullup of the Arduino by a much stronger
external pullup. Something around 1 kΩ should make it quite hard for
the noise to pull the signal low.
Connect the pedal to the Arduino board using a twisted pair of wires,
like the ones found in telephone or network cables. This kind of
cable does a good job at minimizing inductive pickup.

I will try with 1k resistor. The Button is actually a foot switch at a distance of 10 feet from arduino

The problem is same with 1K resistor too.. the wires are shielded properly

It only happens when welding gun relay is activated

The welding gun may be a source of huge electromagnetic noise.

what can i do now?


text:
HC-05 and p-channel mosfet
I'm trying to use a MOSFET (BS250P datasheet) to switch a circuit on and off while the MCU is asleep. It's a P-channel MOSFET that closes the circuit when the gate is pulled low. The most power hungry module in my circuit is a HC-05 bluetooth module. The specs on the website I bought it at rates it at 3.3V - 6V and a max current draw of 50mA when pairing and around 9mA when connected. Hooking it up to an Arduino 3.3V source confirms that it works at that voltage and pairs it up with another identical module just fine.
Now when I put that same 3.3V source through the MOSFET with a 10k pull up resistor and connects the HC-05 to the drain, the module does not power up. I measured the voltage on the drain and when nothing is connected it's the same as the source. After connecting the HC-05 it's about 2.4V (maybe this is a clue). Even if I run the power through a step up converter to 4.10V it does not power up through the MOSFET. If I increase the voltage to 5V it all works fine. I would ideally run the circuit at 3.6V in order to preserve current for the rest of the modules, and not having to use a voltage regulator for the RX of the HC-05.
I assume the issue is with the MOSFET properties, but as far as I can read from the datasheet it can sustain 230mA current. It has a VGS(th) of 3.6V, but since I'm always pulling the MOSFET low in this scenario that shouldn't be an issue? Measuring the resistance when the gate is pulled low indeed gives just a few ohms as the datasheet suggests.
So basically, what am I missing here? :-) Thank you for any help with this!

That's not a good choice of MOSFET I'm afraid.
The on resistance is quoted as 14Ω when the gate is at -10V - however, you are only able to get -5V, so it will be considerably worse.
That massive on resistance will be causing a massive voltage drop, which is what you are experiencing.
You should find a MOSFET with an on resistance that is in the milli-ohm range when the gate is between 0V and -5V.

Hi again Majenko and thank you! I know it's not allowed to ask for shopping items etc so I won't, but these would be available with pins as well, not only surface mounted?

You may need to shop around a little for a through-hole one. I only ever use SMD devices unless I have a really good reason not to, so I don't know what is available in larget packages.

The problem with through-hole is they tend to be either high on resistance (i.e., low current capacity) for logic switching, in a small (TO-92) case, or low on resistance for high current use, and hence in a (relatively) massive TO-220 case. For instance the NDP6020P has the resistance specs you want but is aimed at higher currents, so is chunky.

The LP0701N3 has higher resistance, though considerably lower than your current one, but in a smaller case.

Thanks for the links! I found the NDP6020P in my go to shop for electronics. Apart from being clunky, even in a battery scenario it would actually perform better in terms of battery life with less resistance than the LP0701N3?

It wouldn't make much difference really.

I ordered both and will experiment, measure and learn. Just one more thing that I don't yet understand is that when I use the mosfet I have now and I pull the gate to -3.3V, the resistance over D and S is only 7 ohms. I must be misunderstanding something here because I'm experiencing the voltage drop when the module is connected, but not when it's not connected. I'm assuming that current has something to do with the resistance increase in the mosfet when the load is there?

Yep, it sure does. It's non linear.

Got the mosfets (both of the 2 you mentioned) and confirmed that they work exactly like I want them to. Thanks again Majenko!


text:
Casting custom shared_ptr object
I am using custom shared_ptr class for some program on Arduino, and I need to do something like this:
shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

In my shared_ptr class I have three constructors:
shared_ptr() : pData(0), reference(0){...}
shared_ptr(T* pValue) : pData(pValue), reference(0){...}
shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

and some other stuff...
For casting I tried to write the following:
    template< typename T2 >
operator T2 * () const
{
   return (T2 *)pData;
}

and:
    template< typename T2 >
operator shared_ptr<T2> () const
{
    shared_ptr<T2> temp((T2 *)pData);
    return temp;
}

but can't get it to work.

why do you need a shared ptr in the first place? there's not a lot of memory to warrant dynamic allocation for objects in the first place...

It's better not to use C-style casting in C++. It's working for POD types, but it's basically saying this pointer to elephant is now pointer to train. You should learn about static_cast and dynamic_cast (but I'd skip reinterpret_cast as it's roughly equivalent to the C-style casting)

For doing:
shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr(b_ptr);

you have to use another constructor. If you take a look on this Example of shared_ptr implementation, you can see:
template<class U> shared_ptr(const shared_ptr<U>& s) ...

That's exactly the constructor, that takes shared_ptr of different type .
And similarly for assigment operator.

Thankyou for you answer. But how will I initialize private data like:               pData(s.pData), reference(s.reference)? I can't access them directly, since now they are  other class members.

I don't know much about your shared_ptr class. Anyways, you can assign pointer to the child into pointer to the parent directly (by implicit conversion).

I got it working by making template a friend of sared_ptr class. Thankyou for your help

@Mykolas Btw, if the reference is class member, it'll never work. You have to use something common for all copies.

Yes, I know. The reference is a separate class. Each shared_ptr object stores a pointer to this related reference object. Thankyou for the comment. @KIIV


text:
HC-05 bluetooth module not accepting AT commands
I have been attempting to program my HC-05 ZS-040 Bluetooth module for quite some time, and I cannot get the AT commands to return any values. I have searched google for quite some time, and I none of the answers seem to work for me. I have been following along with this website:
https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth
I am using an Arduino Mega 2560 clone by Elegoo to program this Bluetooth module. Currently I have it wired up using this diagram
https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth/HC-05-to-FTDI.png?attredirects=0
Currently I have it modified slightly to use a voltage divider between the Arduino's Tx and the HC-05 Rx, as the HC-05 works on 3.3v logic. The one possibility I think could be causing this problem is that the Arduino Mega is just interpreting all Tx incorrectly as I measured that it sounds ardoun 3.2 volts for a high voltage. According to multiple websites the HC-05 is in AT command mode when the LED flashes slowly, about once every 2 seconds, which is happening. I put it in command mode by holding down the button above the EN pin while providing power to the HC-05.
I have been using pin 14 and 15, which are Hardware Serial3 on the Arduino Mega. Here is the code I have written:
  /*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.
 */
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("AT");
  // set the data rate for the SoftwareSerial port
  Serial3.begin(38400);
}

void loop() { // run over and over
  if (Serial3.available()) {
    Serial.write(Serial3.read());
  }
  if (Serial.available()) {
    Serial3.write(Serial.read());
  }
}

Any suggestions are much appreciated!
EDIT:
I have now received some unrecognizable responses from the controller after sending AT multiple times, here is the screenshot, included is a video of my circuit, which shows how the LED is flashing:
https://drive.google.com/open?id=1mc8PEEnhiKpPzzy5kL9QxTvoQA3NAH6b
The only modification to the code is adding a Serial.println("TESTING"); in the while loop that reads Serial3. I have tried using other Hardware serial ports as well, all with the same result as the above screenshot.

I looked more closely at your code and I believe I see the problem now.  I'll add the additional info in my answer, but did you notice that you set up the mySerial object, but you don't actually reference it in the code?  Your mySerial is analogous to my BTSerial object.  I'll write your code as it should be in my answer so you can copy it and try it.

Thanks for all the help! I had given up on getting Bluetooth module to work, however when working with a simple RGB LED, I noticed my mistake. I was using the ground from my breadboard power supply for the module instead of the ground from the Arduino Mega. I rewired my breadboard so the ground and power come from my Arduino Mega, and everything works perfectly! I ended up using the exact same code that I posted in my original question, so it was just that I was not using the ground from my Arduino Mega

###### Try This : Your Code Updated With Possible Fixes  ######
After examining your code and comparing it to my working code I believe I have found a definitive answer.  I'm altering your code so you can copy it and try it.  I'll add comments where I've changed it.
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  // set the data rate for the SoftwareSerial port
  // notice that your comment on previous line says SoftwareSerial port
  // but you are setting the Serial3 port -- this is where we use mySerial
  // Serial3.begin(38400); // commented your line of code
  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}

I am confident that if you use this newly modified code it will solve your problem.  I should've noticed this earlier.
Here's the rest of my original answer.
I have struggled with this myself.  As a matter of fact it took me a few months of owning some HC-05s before I finally dug up an answer.  It's been a while since I worked with it so I'll do my best to explain what to do.
Arduino Nano
Also, I use an Arduino Nano to do the programming of the HC-05.
This Setup Lets You Alter HC-05
Once you wire it up and run the program (included here) you will be able to send any of the HC-05 commands and they work great.  You can change the name of the device, the 4-digit pass-code and everything.
Crude Snapshot, But Enough To Build Simple Circuit
I also have a crude snapshot* of the circuit I used (at the time just for documenting it for my own memory) but I think we can work you thru it.  and I know those wires are all crammed together and it almost looks like they are in the same breadboardholes but they are actually hooked up properly.  I was so excited it finally worked I snapped the pic too fast.
*see image below
Here's the code I use:
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  //pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  //digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor

  if (BTSerial.available())
    {
     //Serial.println("bt available...");
    Serial.write(BTSerial.read());
    }

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Does Your HC-05 Have the Button?
Okay, so the first thing is to check to see if your HC-05 has the little button on it?  If it does that has to be held when you apply power to the circuit.  The HC-05 will blink and then it will be in COMMAND mode and you can let go.
If No Button
You can see that mine has the button.  That is why the first two lines the setup() method are commented out.  I don't need D9 to go high (it is not connected to the pin) because mine has the button. If yours has the button (most likely does) then you don't even have to worry about it.
Looking Back At Your Question
Now that I look back at your sample code it could be that you're not aware that you have to hold that button when you power up.  Or you don't know that you need to connect that wire to keep the HC-05 in command mode.
Pins For TX / RX
That's probably the problem you are having, because everything else looks the same -- except you are using 15 and 14 for TX / RX.  I am using D10 and D11 for mine and I remember something about those pins in the back of my mind so if yours still doesn't work, try switching to those and try using my code.
I remember the first time I finally got this working and I was dancing around the room. Good luck and I hope you are dancing soon.  :)

Thanks for the response! I tried your suggestion to use pins 10 and 11 however I got no response. I have been pressing down the button while applying power, and the indicator LED is one for two seconds, then off for two seconds. However when using the Hardware serial ports on my Mega 2560, I get responses now in the serial monitor, and managed to change the name of the HC-05, but the responses are still unreadable. Could it be that the HC-05 high (3.3v) is not enough for the Arduino Mega to interpret as a high value, thus sometimes the response appears okay and other times it doesn't?

@JustinVanderBerg  I think that is a good guess, but I'm not sure about it because I don't have experience with Mega.  It may be worth it to you to buy this pack of 3 Nanos https://amzn.to/2MOfHYE ($12.68USD) at Amazon and use one of them to program your HC-05.  Sorry i couldn't be more help with this. Like I said, I struggled with it for a few months trying off and on to resolve it.

@JustinVanderBerg I was thinking about this again and if you are getting garbled text that often means the speed does not match. I noticed yesterday that even though my Arduino was writing to serial port at 9600 (via setting in software) I actually had to set the Arduino IDE Serial Monitor to 19200 to get valid output.  My point is, have you tried setting the speed to different values in the Serial Monitor?  It may be that the HC-05 is defaulting to 9600 -- which is the default for regular data send mode.  It may be worth a try.


text:
Problem with nodemcu esp-01 can't connect to wifi
i've been working on a project that im using an esp8266 nodemcu-01 as described in the title, and i've been having some headache with this module, first because after searching i figured out that the commands LOW and HIGH are inversed as in LOW outputs 3.3v e HIGH outputs low tension, so i began to grow worried about the possibility that other programming resources may follow the same situation. But with that problem a part, i've been trying a few different codes including the one found in the sketchbook examples and still couldn't connect.
Also another weird problem, is that i was working working with the baudrate set on the arduino IDE settings on 115200, and so is the Serial.begin, that is also set to 115200, however i can only read properly the continuous dot that is contained in the while loop "........." when i set it to 74880, which another thing that i was trying to understand. I also forgot to mention that it keeps spamming dots but does not connect at all.
And to conclude, my problem resumes in not being able to connect to any wifi i've tried, i tried my friend's home and also 4g, both did not work, here's the code, which we tried first:
#include <ESP8266WiFi.h>

char* ssid = "Net Wi-fi";
char* password = "testingtest";
//
void setup() {
  WiFi.begin(ssid, password);
  Serial.begin(115200);
  while(WiFi.status()!=WL_CONNECTED)
  {
    Serial.print("Conecting");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP:");
  Serial.print(WiFi.localIP());
}

void loop(){

This was the original try, using the arduino sketch example:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Net6271";
const char* password = "megaman";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, 0);
}

void handleNotFound(){
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Board setting: Generic ESP8266 Module.
Crystal Frequency: 40MHz.
Flash Frequency: 80Mhz.
Upload Speed: 115200.
Flash Mode: DIO.
Flash Size: 512k no SPIFFS.
pls help.

ESP-01 modules use 26 MHz crystal. Set the Crystal frequency in IDE to 26 MHz.
Both io pins (0 and 2) on esp-01 have pull-up circuit. That is why you think you measured 'inverted' logic.

Thank you for replying my good sir, when you suggest setting the crystal frequency to 26Mhz i assume that's the fix for the baud differences in serial monitor? Also, on the second post i assume its referred to the inversion of logic? thanks but what do i do about wifi not connecting? it keeps sending "." and does not connect.

erase the flash with esptool and the try again the sketch

Thank you sir, you are a true legend, thanks for helping me out, your suggestion worked perfectly :)


text:
Is I2C a good option for transmitting data over 200 meters by cable?
Is I2C a good option for such application or are there other protocols? I know that modules like these exists to extend I2C range, and I'm planning to use this one (P82B96).
I'd like to use a frequency of 100kHz for I2C and use DMX cables of 20m connected in series.
So, is there any alternative that is more adapted for Arduino to Arduino data transmission over a cable?
EDIT : The solution here is CAN because it allows to have multiple devices on the bus. But if it is a simple communication between two arduinos, then go for the RS-232.
Solution mentionned by @Dmitry Grigoryev and @Joe S
Thanks in advance.

I2C is intended fo very short ranges. The capacitance of long cables makes the signal unusable. There are other communication standards designed for long distances that mostly use differential signals. You won't get such a signal out of the Arduino itself but need some peripherals that do that.

And some of those peripherals can be controlled with I2C,

@Kwasmich So what are the "other communication standards designed for long distances" ? :)

something like RS-485 might be an overkill. But RS-232 (the 12V variant) is also rated for longer distances than I2C.

Also 1Wire was designed for long distances.

RS-485 or CAN is the way to go here.

With I2C, you're unlikely to get reliable communication on a cable longer than 1m. For your reference, here's a table showing what you can achieve with regular RS-232:
Length (m)  Maximum Baud Rate
1600        600
800         1200
400         2400
200         4800
100         9600
50          19,200
25          38,400
16          57,600
8           115,200

So, if you don't really need 100 kHz data rate, you could use regular RS-232 (which is cheap). If RS-232 is not fast enough for you, consider more complex solutions. RS-485 is one possiblility. Another one is CAN, which supports topologies up to 500m at 100kHz. The key difference of CAN is that it's a bus, meaning that all devices will share the same pair of wires.

It should be noted that regular RS-232 uses +/-12V signals not 5V signals like arduino serial interfaces.

The problem is that I control multiple devices on a bus and they have to be able to send data back to "master", and RS-232 is not adapted for this usage but CAN seems to have that functionnality.

@Storca CAN is more complex (you have to deal with message priority, bus arbitration, etc), but it's totally worth learning if your project is complex enough. BTW, this is how typical CAN transcievers look like.

I2C is perhaps the worst possible choice for this type of communication. Instead you should be using something like RS-485 (which is incidentally what DMX uses) with differential signalling.


text:
Using modulo for negative values
I want to wrap a random number using modulo, so that values exceeding 11 starts over from 0 and greater. However, i would also like numbers less than 0 to dividend 11 or less.
Please correct me if i'm wrong, but as far as i can tell the modulo operator only dividends values exceeding the divisor. If so, how can i write code that also dividends values less than 0?

One crude way:
while (x > 11) x -= 11;
while (x < 0) x += 11;

The first could be replaced with a modulo operation.

Simply use modulo
#include <stdio.h>

int main(){
   for (int i = -23;i<23;i++) printf("%d    %d\n",i,i%11);
   return 0;
}

all modern C variants should work the same way https://en.wikipedia.org/wiki/Modulo_operation (result have same sign as divident):
-23 -1
-22 0
-21 -10
-20 -9
-19 -8
-18 -7
-17 -6
-16 -5
-15 -4
-14 -3
-13 -2
-12 -1
-11 0
-10 -10
-9  -9
-8  -8
-7  -7
-6  -6
-5  -5
-4  -4
-3  -3
-2  -2
-1  -1
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10
11  0
12  1
13  2
14  3
15  4
16  5
17  6
18  7
19  8
20  9
21  10
22  0

for new formulation of request fixed by @Gerben suggestion
if you want monotonic 0..10 sequencies, add 11, if result is negative :
#include <stdio.h>

int main(){
for (int i = -23;i<23;i++)
    {
    int x= i%11 ;
    x += x<0?11:0;
    printf("    %d  %d\n",i,x);
    };
return 0;
}

results in
-23 10
-22 0
-21 1
-20 2
-19 3
-18 4
-17 5
-16 6
-15 7
-14 8
-13 9
-12 10
-11 0
-10 1
-9  2
-8  3
-7  4
-6  5
-5  6
-4  7
-3  8
-2  9
-1  10
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10
11  0
12  1
13  2
14  3
15  4
16  5
17  6
18  7
19  8
20  9
21  10
22  0

Thanks for your feedback. However, this seems to produce a different result than what i asked for.

If the value is negative, add 11.

fixed by @Gerben suggestion


text:
Servo doesn't work in 'for' loop running under 'if' loop
This is my first StackExchange question. I'm relatively new to Arduino and I am trying to tinker with the components and functionality.
I have a RGB LED coupled to my breadboard with a servo attached. The LED only shows Red and Orange for some reason(Why?), SO I mended my code as per the LED behaviour. The code prompts the user for a color, and depending on that, the Servo should rotate along with the LED lighting up. My servo functions well only in 25-165 degrees range. The code goes as,
Here's the code:
# include<Servo.h>
int i;
Servo n1;

String color;
void setup(){

Serial.begin(9600);
  n1.attach(6);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(6,OUTPUT);

}

void loop(){

Serial.println("Enter color: ");

while(Serial.available()==0){
}
color=Serial.readString();

if (color=="red"){
  digitalWrite(2,HIGH);

  for (i=25;i<=165;i=i+5){
        n1.write(i);
        delayMicroseconds(250);
  //}
  n1.write(25);
  delay(2500);
  digitalWrite(2,LOW);
}

}else if (color=="orange"){
  digitalWrite(3,HIGH);

  for (i=165;i>=25;i=i-2){
    n1.write(i);
    delayMicroseconds(250);
  }
  n1.write(25);
  delay(2500);
  digitalWrite(3,LOW);
}
}

So basically when Red is in, I want the Servo to go from 25 to 165 & come back to 25, and vice versa for Orange. But the servo behaves in 2 ways;
1.When Red is entered first, it turns some angle(I guess 25) and stays there, the programme doesn't even loop for further input of color for a long period. Then whatever the input goes, Servo stops rotating, only LED works.
2.When Orange is entered first, it goes again to the same angle as red, and mildly buzzes, but input is accepted and Servo is motionless.
I simulated the same setup and code in TinkerCad circuits, and the behaviour is the same, so no particular problem with the hardware there.
I'm relatively new to understanding the Arduino workings and Fundamentals, any help is appreciated.
Also, the circuit setup is attached.
Any help will be appreciated.
Thanks!

Can you please make a circuit diagram using the provided tools

for (i = 175; i >= 25175; i = i - 2) {

This was a typo in the code that I pasted before, I have re-pasted the corrrected and updated code again.

@JoeS I have updated the Circuit Diagram using TinkerCad for your reference.

Try using delay rather then delayMicroSeconds. I don't think 0.25 mS is enough time for the servo to move even a few degrees.

@ChadG That Worked! The Servo is now running perfectly. I have one question though, when I connect the Servo and the RGB LED to a common ground on the breadboard, the servo keeps on buzzing, even at 90 degrees. But when I connect it to the separate GND pin on Uno, it works good enough without jittering till 25 degrees. What can be the cause?

This section of code is never going to run. The for loop says that i starts at 175, and while i>=25175 then execute the n1.write(i) and subtract 2 from i each time it does this.
for (i = 175; i >= 25175; i = i - 2) {
      n1.write(i);
    }

From the arduino servo example page, n1.write() should only ever be from 0 to 180, as it is the angle the servo is at. So you go from 175 to 180 and it wont move past that.
//angle: the value to write to the servo, from 0 to 180

#include <Servo.h>

Servo myservo;

void setup()
{
  myservo.attach(9);
  myservo.write(90);  // set servo to mid-point
}

void loop() {}

of course it should be 25 not 25175. it is a copy paste error with no need to explain.

Actually, this wasn't the error that is creating the problem. As said by you,it's a copy paste error.

https://arduino.stackexchange.com/q/53814/47552 This is the actual corrected version of the question.

I have updated the code in the question, but it still doesn't follow the for loop sequence.


text:
My 1604 LCD is bright with USB power but not when powered through the jack
I'm making a bench PSU. The Arduino runs off the purple 5v standby. The Mega also powers 2 LEDs (normal 5mm clear). The thing is, when I upload the code and watch the screen go through the process, it's bright and visible. But when I turn on the 5v standby (without USB) the text is visible if you try really really hard to see.
The 5v standby is rated at 2 amps MAX. I can't imagine it's the code but would anyone help? Why does USB power allow the LCD to power fully compared to the 5v standby?

Can you supply a schematic? And are you putting 5V into the barrel jack connector? If so, that's why you're getting a dim screen: the supply through the jack is supposed to be a minimum of 7V or so because it powers the onboard 5V regulator. 5V in will only give you about 3.75V out, maybe less. By "purple 5V standby" I guess you're using an ATX PSU?

get a barrel-jack to microUSB adapter for ~$1 online to by-pass the on-board voltage regulator dropout. Also, you might be able to adjust the contrast to work acceptably; i had one that i ran off 3.3v and at first it was super faint, but with tweaks it was more than acceptable for the viewing angle i needed.

I do not know how to upload fritzing files to the comment. However, dandavis sounds like he is onto something. The problem i have is that, i made a slot on the side of the enclosure to allow updates and debugging easy. The 5v standby was soldered under the onboard barrel connector legs. can i power the arduino  with the purple 5v standy via usb?

You are not supposed to put fritzing files to comments. Instead edit your question and put a screenshot of the fritzing there.

This really sounds, as if you were putting 5V to the barrel jack. That won't work, as CharlieHanson wrote. Connect it to the USB jack or directly to the Arduinos 5V pin.


text:
Blink example compilation error
I just installed the Arduino IDE on Mac and connected the programming port to my Arduino Due. I selected the corresponding board from Tools (though not sure which ATMEL programmer I should choose) I click upload and it gives
In file included from /Users/deepayanbhadra/Library/Arduino15/packages/arduino/hardware/sam/1.6.11/system/CMSIS/Device/ATMEL/sam.h:198:0,
                 from /Users/deepayanbhadra/Library/Arduino15/packages/arduino/hardware/sam/1.6.11/system/libsam/chip.h:25,
                 from /Users/deepayanbhadra/Library/Arduino15/packages/arduino/hardware/sam/1.6.11/cores/arduino/Arduino.h:42,
                 from sketch/Blink.ino.cpp:1:
/Users/deepayanbhadra/Library/Arduino15/packages/arduino/hardware/sam/1.6.11/system/CMSIS/Device/ATMEL/sam3.h:59:37: fatal error: sam3xa/include/sam3xa.h: No such file or directory
   #include "sam3xa/include/sam3xa.h"

compilation terminated.
exit status 1
Error compiling for board Arduino Due (Programming Port)

I'm pretty bumped off as this was my first example. When I connect the USB to the board, the ON is green, the L above and TX below the programming port is yellow. Is this okay?

is there more to that error message? maybe have to scroll up in that bottom window

@ChadG: You're right. I've added what it says further.

Try and pin down whether or not your problem is specific to the Due by compiling for another board, e.g. UNO.  You don't need to have the physical board in order to compile, only upload.  The debug is showing you are missing a library file.

@MichaelT: It still gives different kind of errors with other boards. I'm wondering what the choice of Tools->Programmer-> ? should be

I use default AVRISP mkII from the IDE for UNO.  I'm not aware whether that is different on mac.

@MichaelT: When I choose AVRISP mkII from the IDE for UNO, it just gives 'Problem Uploading to Board' (which's okay because the board isn't connected) I only have a Due. So it seems specific to Due, right? Also, is this okay - the ON is green, the L above and TX below the programming port is yellow?


text:
Flashing firmware in ft232rl
I am new with arduino and hardwares at all and I am having some problems in a project where I want to assemble the head tracker device from this project https://git.iem.at/DIY/MrHeadTracker/wikis/mrht-bno055 ... They use an Arduino pro mini for data processing (with a .ino sketch provided by them), an Arduino USB 2 Serial micro for connecting the pro mino to the pc, and a sensor BNO055 by Adafruit which provides orientation data. I am using the same hardwares instead of the USB converter that in my case is the ft232rl by FTDI. The step I am having problem is the one where I have to flash the HIDUINO firmware (they provide an .hex file) so I can use the whole thing as a MIDI device.
The point is that I just don't understand if I have to overwrite the pro mini's serial firmware or the usb converter's and how it's the correct way to do it, mainly because I can't find examples with the usb converter I have and every new reference I read makes me think of one possibility. In the first link they suggest reading the information in https://github.com/ddiakopoulos/hiduino/wiki which presents 2 methods: DFU method, that tells I need Atmel Flip software for Windows and ISP method, that I don't know if is my case because I can't find out if my ftdi board is an ISP programmer. I've read about it and in other references also, but I am still not sure about what I have to do.
I hope that someone can help! And sorry for the basic doubts...
Thanks!

The arduino USB2serial has an AVR that can be flashed with new firmware. Your FTDI device does not have MCU that can be re-programmed.

@Craig, actually, you can make some changes to the FTDI adapter ... http://www.ftdichip.com/Support/Utilities.htm#FT2xxR

@Craig if that is the case, it means I can't use the board for this application because it can't be reprogrammed or i just don't need to overwrite any firmware because there's nothing to be reprogrammed? Thanks for the answer!

@jsotola Which would be the right section of the link you sent? Thank for your answer!

@Enzor, I do not know if any sections apply to you ... it is unclear what you are trying to do. .... the ftdi chip is just a USB to serial adapter

@jsotola sorry for that... I actually have problemas to explain the problem too... but what I am trying to find out is how to do this step "Flash the USB2Serial interface according to https://github.com/ddiakopoulos/hiduino/wiki.
You can use the provided MrHeadTracker.hex file (HiduinoFirmware directory).", which makes me think I have to do something in my usb to serial conterver, the ftdi, because is the board I am using to substitute the Arduino USB2 serial from their project...

@jsotola The main sketch (.ino) is already uploaded in the pro mini... the device is designed to be a class-compliant MIDI, including the way the code ( https://git.iem.at/DIY/MrHeadTracker/tree/master/Arduino/MrHeadTrackerBNO055Switchable )is written that uses MIDI library... Here's antoher thing they say that makes me think it's all about the usb conv "To enable plug-and-play support without any additional
software, the Arduino USB2Serial converter is used.
Its Atmel 16u2 micro-controller can be programmed to
appear as a class-compliant USB-MIDI device using the
HIDUINO library"


text:
Connecting Arduino with GPS receiver
I have the components as shown and I installed the TinyGPS library.
I'm pretty new to hardware stuff and I'm not sure if these wires would work? (pins on both sides)
The GPS module has 5 pins - GND,5V,IN,OUT and I can barely read the last one. I'm assuming I need to connect only the first 4?
Thanks a lot.

looks like you really need wires with male and female ends.....

@ChadG: So I thought. Is there any workaround, like using a breadboard to interface?

yes... if you put the gps in a breadboard, then the male/male jumpers would be fine.....

I'm assuming I need to connect only the first 4 ... never assume anything .... please post a closeup of the GPS module, back and front, with the writing oriented upright (i'm too lazy to turn my laptop sideways. lol)

@jsotola: I figured this out, thanks nonetheless :)