text:
ADS1115 : measuring 5v voltages and powering with 3.3v
I have a project where I need to measure 0 - 5 V. I’m using a ADS1115 to have a better precision, connected to a ESP12. Since the ESP is only 3.3 V tolerant and the ADS powered by 5 V (because it needs to be powered a the same voltage as the measured voltage), I put the two pull-up resistor of the I2C bus on 3.3 V.
Is it safe to operate like this?

I'd use a Bi-directional Logic Level Converter for I2C

esp8266 has no problem with 5 V I2C

Safe? Yes. Reliable? Not really. VIH is 3.5v at 5V VCC, and 3.3 is below that.

Is your arrangement safe? Yes, perfectly.
Is your arrangement a good idea? No, it is not.
When the ADS1115 is run at 5V it needs at least 3.5V on the I2C bus to properly register a HIGH.
However you can pull up to 5v instead and you won't have a problem.  Not only is the ESP8266 tolerant of 5v, but that 5v is severely limited in current by the pull-up resistors, so even non tolerant inputs would have a hard time complaining. Worst case scenario, the ESP8266 pulls the bus down to maybe 3.8v (3.3v plus an ESD diode drop) which is fine for a logic high on the ADS1115.
However, if you want to do things properly, you really should use a proper I2C level translator.

Ok thank you. I thought the ESP i2c bus was only 3.3 v tolerant. I don’t have enough space to put a logic converter (my pcb has be 4cm * 6cm)

So use a PCA9306 in DSBGA package then - 1.98 mm x 0.98 mm (can you even see that...?) I have used the X2SON version (1.40 mm x 1.00 mm) before, and that was, while tricky, actually possible to work with.


text:
Communication with Arduino and electronic device(for example tv or computer) through rs 232 cable

Say some electronic device (TV OR Computer) has an inbuilt program. Depending on received data from Ardiuno, it displays some text based on requirement. For example, if it receives 1 it should display 'error', else if it receives 0 it should display 'ready'.
I am working on only sending signals/bytes from Arduino Uno to some device which already has an inbuilt program. I just want to send 0 or 1 byte from the Ardiuno to the device using TTL to RS 232 COVERTER.
  this is the code

#include<SoftwareSerial.h>

 #define rxPin 0 //make pin o as rx pin

 #define txPin 1//make pin 1 as tx pin

 SoftwareSerial mySerial(rxPin ,txPin);//i donot undersatnd this line (i got
 the code from net//

 void setup()

 {

     pinMode(rxPin,INPUT);//making rx as input//
     pinMode(txPin,OUTPUT);//making tx as output//
     Serial.begin(9600);
     mySerial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
Serial.print(0x00);//i want to send 0 byte data from ardinuo to device //
delay(200);
}

I am using RealTerm software to check if the signals I have sent from the Arduino Uno are received as they have to be (without any interference).

I am sending continuously 0 from ardinuo to realterm in this case(for testing purpose). I am receiving in RealTerm in Hexadecimal format. Since I'm sending 0s continuously, I should be getting a continuous output of 0s on RealTerm as well. Instead, I am getting some random values initially (while uploading the sketch) and RealTerm stops displaying output soon after.
Can someone please help me solve my issue.
Update 1: i have modified my code as per @chrisl's  suggestion. Now, whn i send 0 i am getting a correct ouput ,but whn i am sending 1 contineosly i am  getting many 0's and random values

#include<SoftwareSerial.h>
#define rxPin 2
#define txPin 3
SoftwareSerial mySerial(rxPin ,txPin);
void setup()
 {
 pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  mySerial.begin(9600);
  }

  void loop() {
     // put your main code here, to run repeatedly:
  Serial.print(0x01);//i want to send 1 byte data from ardinuo to
  device(realterm)
  delay(200);
   }

RealTerm seems to display the hexadecimal values. Since you send the ASCII code for "0" (which is 30) (by using print() instead of write()) you should see a repeating 30 there. Don't assume zeros, when you are sending ASCII. Though this doesn't explain the seemingly random values you get.

You have configured pins 0 and 1 of the Uno for software serial, which makes no sense since those pins have hardware serial. Then you don't even use software serial in your code. You need to take the time to actually understand what the code does instead of just randomly copy pasting and hoping it might work. There is a ton of information available to you, use it!

use Serial.write(0), not Serial.print(0) if you want to send value 0 and not the character '0'

You have 2 problems:

You use the Serial.print() function, which outputs ASCII encoded characters. When sending "0" this way, actually the value 48 (or 30 in hex) will be send. RealTerm seems to display hexadecimal values, so you would get a long series of "30"'s. This is not really a big problem, you only shouldn't expect zeros to display there with this code. You can use the Serial.write() function to send direct byte values instead of ASCII codes.
You initiate the SoftwareSerial on the same pins, that are reserved for the Hardware Serial. This cannot work properly, because both libraries will try to use the same pins. Choose other pins for Rx and Tx of the SoftwareSerial interface.

EDIT:
Also you are setting pin modes for Rx and Tx of the SoftwareSerial. I don't know, if this can cause a problem, but at least you don't have to do this. The library will handle setting the pins correctly.
EDIT2: Further explanation about binary, hexadecimal and ASCII representation of the Serial byte stream
There are different methods to display a stream of byte data (like the stream from your Serial interface). Let's look at the decimal value (the one you are using when invoking arithmetic operations like +, -) 48. These are the different representation of this number in different numeral system (The first two characters mark the numeral system; 0b for binary, 0x for hexadecimal):

binary: 0b00110000
hexadecimal: 0x30

There are more numeral systems, but these are the most important ones. But the byte stream can also be used to look like a sequence of characters. For this the ASCII standard was born long time ago. In simple ASCII every value from 0 to 127 got assigned to a character or control action. The terminal program reads the byte stream and shows the corresponding characters according to the ASCII table. There are expansions to this model, to display more possible characters, but this is the very basic principle. With it, you are able to actually send human readable text from your Arduino to another device.
The Serial.print() function is made for this human readable text, so it will send an ASCII representation of the input parameter. The ASCII value of the character "0" is 48, which corresponds to a hexadecimal value of 30.
Now I'm not sure, if your terminal program shows hexadecimal or ASCII values. I though of the first, because all characters in your first image are digits or characters from A to F, which is the range of hexadecimal values. It didn't seem likely to not get other characters, when you have ASCII encoded text with random values in it. But I'm currently not sure, if the Serial.print() function would automatically print a hexadecimal representation in form of ASCII text, if given a hexadecimal value (I don't think so, but it might be possible). Please try to use the Serial.write() function and try sending different value while watching the output of RealTerm.
And please search for a settings, that determines, how the received byte stream is interpreted. This would make clear, what RealTerm is doing here. Also make sure you understand the relation between binary value and ASCII character. If this is still not clear enough, you can google for in detail explanations. There are tons of tutorials on that.

i have updated the question please check

as your suggestion i followed step 2 so ii am now able to get continuously output ,i can't understand 1 st part of your answer

@jalath I added further explanations.

According to basic serial communication principles, the transmitter (Tx) of the Arduino must be connected to the receiver (Rx) of the device. However, I am getting a correct output when I connect the transmitter of the Arduino to the transmitter pin of the device. Why is this so?

Perhaps the pin information on your device is wrong. You didn't specify, what you have there. Or the TTL RS232 converter might already twist the two lines. From the given information it is impossible to say

source: Stack Exchange

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

sort: votes


text:
Unable to obtain pulse train at 32Hz with 20us pulse width with Uno
I tried to obtain 32Hz pulse train(between 30Hz and 35Hz is also fine) with around 20us pulse width with Arduino Uno but couldn't succeed. The problem is:
If I do the following:
void setup() {

    TCCR1B = TCCR1B & B11111000 | B00000101;

    pinMode(pwmPin9, OUTPUT); // sets the pin as output

}

void loop() {

analogWrite(pwmPin9, 1)

}

I can set the freq. roughly at 30Hz but analogWrite(pwmPin9, 1) will give minimum 100us cannot go down to 20us.
digitalWrite method with delay on the other hand doesn't work to obtain frequencies below about 60Hz.
How can I obtain a pulse train output with between 30Hz to 35Hz and with around 20us pulse width?

Instead of digitalWrite() write the values directly to the PORT register. This takes a lot less time than the big digitalWrite() function. Also you can do this with a timer compare interrupt, so that you will be able to get exactly the frequency you want.

could you write an answer an an example?

For this kind of problems, the first thing to do is convert the two
relevant times (the signal period and the duration of the HIGH state)
into a number of CPU cycles. With a 16 MHz clock that gives:

HIGH time: 20 µs =    320 CPU cycles
period: 31.25 ms = 500000 cycles (±7%)

Then divide those numbers by the available prescaler values, to get the
corresponding number of prescaled clock cycles:
prescaler       1      8    64     256      ...
HIGH time     320     40     5       1.25   ...
period     500000  62500  7812.5  1953.125  ...

Ideally, you want a prescaler that gives you integer numbers, in order
to avoid rounding errors. And since you are using a 16-bit timer, you
want these numbers to be no larger than 216. Or twice that if
you use a phase-correct PWM mode, but I prefer to avoid that
complication if possible.
From the table above, it appears that a prescaler of 8 is ideal. 64
would be practically as good, with a frequency error of only
64 ppm, which is less than the frequency tolerance of the ceramic
resonator clocking your Uno.
Then you use either OCR1A or OCR1B to set the high time, depending
on whether you are outputting to pin OC1A (digital 9) or OC1B (digital
10). An you use either OCR1A or ICR1 to set the period. Since you
are outputting on pin 9, the OCR1A register will be used to set the
high time, thus you have to use ICR1 to set the period. Then you
search the table of modes in the datasheet and find the one relevant to
this mode of operation is mode 14: fast PWM with the TOP value
defined by ICR1. This gives the following configuration:
void configure_timer_1()
{
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;           // ditto
    OCR1A  = 40 - 1;      // HIGH for 40 * 8 CPU cycles
    ICR1   = 62500 - 1;   // period = 62500 * 8 CPU cycles
    TCCR1A = _BV(COM1A1)  // non inverting PWM on pin OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS11);   // clock at F_CPU/8
}

Note that OCR1A and OCR1B have to be set to desired number of cycles
minus one.

analogWrite is 8-bit.
The reciprocal of 30Hz (the time per full period) is 0.0313.
0.0313 divided by 256 (28) is 0.000122, or 122uS.
At 8 bits that's the smallest time that the 30Hz waveform can be cut up into.
To get smaller slices you need a higher resolution PWM signal. This question and answer shows how it can be done, but it's limited to which pins can be used, since you need the PWM channels attached to the 16-bit timer.

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


text:
How to achieve smooth motion with a servo motor?
I'm trying to control the MG995 servo motor with an Arduino Uno, but the motion achieved by the motor is kind of erratic. The servo motor is externally powered from a 2200mAh 7.4V 30C LiPo battery with a 7806 voltage regulator which provides a voltage of 6.1V.
The circuit I'm using is as shown below:

When I load the sweep example, the servo rotates until a certain angle where it appears to be obstructed and is trying to overcome the obstacle before turning and rotating in the other direction. Here is a video of the motion I'm trying to describe: https://streamable.com/dcr2i
If I connect the motor directly to the battery without the regulator, the motion is smoother than that. I want to use the regulator to protect both my circuit and the motor. How do I achieve the same smooth motion?

According to Jameco:

Servos are controlled by sending an electrical pulse of variable
  width, or pulse width modulation (PWM), through the control wire.
  There is a minimum pulse, a maximum pulse, and a repetition rate.

I'm ignorant of the effect of a voltage regulator on pulse width modulation, but based on your experience, I suggest that it is detrimental.
You can confirm this if you have access to an oscilloscope with which to view the pulses directly from the circuit and then again from the output of the regulator. Correction, view the input to the servo without the regulator and then with the regulator.
According to Roger's Hobby Center, a 2S lipo battery, nominally 7.4v will reach voltages as high as 8.4 volts. This moves the concern of 6v deeper into the question.
Another website, pololu.com references "old style" servos as being designed for 6 volts in the form of 4 batteries at 1.5v, while manufacturers are embracing the newer battery chemistry and producing servos which will operate at levels as high as 9 volts.
Additional research (the data sheets for this model servo) show that it is designed to take 4.8 to 7.2 volts. The full charge voltage of 8.4 will cause the servo to run a bit faster, but I don't believe there will be long term effects, as the voltage will drop into the nominal range in short order.
Another piece of information I gathered somewhat indicates that a regulator will (or should) work, but it has to have the current capacity to handle the servo. I missed that figure in my research. This led to me discovering a caution that your circuits should have a common ground. If you don't have a common ground, your answer may lie there.

The datasheet says that the motor is rated for 6V, hence the regulator. I actually need to run three of those motors in the end. Each motor was to have its own regulator circuit as above. Would it be safe to run all three directly from the battery without the regulators?

added edits to answer.

Thank you for the incredibly detailed answer!
All the components do share a common ground, but still experience the same issue. The 7806 is rated for an output current in the range of 1A - 1.8A according to here or here which the stall torque of my motor (1.2A) is in. Would you happen to have any other insights?

Big RC servo like this draw amount of current when rapid moving (maybe greater than stall current) and cause voltage to drop.
RC servo sense spindle position by potentiometer which affect by unstable power source.
You should use more current regulator like switching type or you can add big capacitor (say 1000uF) at servo power to smooth voltage.
I try myself using lab bench PSU and set to 5V 2A and motor still oscillating. I need to go with 5V 5A.


text:
Cannot access SD card on WINC1500
I have a WINC1500 shield and have the Wi-Fi side working fine. I want to do some datalogging to the SD card and am having trouble getting it running. I have bought a 16 GB Sandisk card and inserted it. I have added the SD library, SD.h is included. However SD.begin() fails. I have a Mega2560 card (from Elegoo) so should be able to run the SD and wifi at the same time? Do I need to pass a parameter to SD.begin()?
The code below always prints "Card failed to initialise, or not present".
if(!SD.begin())
{
    Serial.println("Card failed to initialise, or not present");
}
else
{
    Serial.println("Card initialised ok");
}

https://www.arduino.cc/en/Guide/ArduinoWiFiShield#toc9

as @Juraj obliquely pointed out try 'SD.begin(4)'

and set pin 53 to output and set pin 10 high if you don't begin() the WiFi library

Do I need to pass a parameter to SD.begin()?

Yes, you need to pass the Chip-Select (CS/SS) pin number. What number depends on how you have it hooked up, the default is 10. (yours might be 4)
n.b. according to the docs a standard arduino can't use the WiFi, and the SD at the same time; presumably the mega has enough memory.

these docs

Thanks. It does need to be 4 for the WINC1500 with no jumpers cut. And yes the mega has enough memory for both.


text:
How to read OC0A when in CTC (toggle) mode?
I have this code, which puts the Arduino into CTC mode with interrupts, and outputs a square wave on PD6 (OC0A):
void setup_timer(double p_ms, double duty){
  DDRD |= (1 << 6);  // set pin 3 as output
  TCCR0A = _BV(COM0A0); // toggle OC0A on Compare Match
  TCCR0B = _BV(WGM01); // set CTC mode WGM0[2,1,0] = 0b010
  TIMSK0 |= _BV(OCIE0A); // Enable CTC interrupt
  OCR0A = 128;  // set on and off time
  TCCR0B |= ( (0 << CS02) | (0 << CS01) | ( 1 << CS00)); // CS02:0 - No prescaling
  sei();
}

In the ISR (which is not shown) I want to be able to see whether OC0A (i.e. PD6) is HIGH or LOW.
I assumed that I could do a digitalRead(), but this post, Re: How to read the state of an output pin ? says:

Looking at the code the digitalRead() function just does a read of the appropriate bit in the appropriate PINx register without modifying anything, so it should work.
One catch, if it's a PWM pin the PWM will be stopped.

So, will the toggling of OCR0A be stopped?
This answer to How can I digitalRead a pin that is in pinMode OUTPUT? suggests reading PORTD directly, with
bitRead(PORTD,6);

However, will that work for PWM output or will PWM also be stopped by reading PORTD?

Addendum
I plan to use this code either as (primarily) a stand alone AVR µController (48/88/168/328 IC), but maybe in a Nano/Uno (if it will work) for testing purposes. I understand that using Timer0 will affect the operation of millis(), delay() etc., but the rest of the code will not rely on any of those functions... so I presume (maybe incorrectly) that the code will work as expected. Is that correct?
In addition, I don't intend on using a setup() & loop() program structure but rather main(). Just out of interest, would loop() work (i.e. is it reliant on Timer0)? I don't believe that it is.

What Arduino board?

If you look into the Arduino Core, you'll find this code for the digital read:
int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

That means, disabling PWM is just weird feature in digitalRead.
For reading bitRead(PORTB,3); I'm not so sure if you'll get output value of OC0A, it might be different signal line internally. However you'll get logical level on the port pin by reading bitRead(PINB,3);.

Preliminary note: If you are using any of the ATmega48/88/168/328,
then the OC0A pin is PD6, not PB3.
As four your idea of reading the PORT register (PORTD, not PORTB),
it won't work either, as that will only tell you what was the last value
that was written to the port with digitalWrite(). Here is a schematic
showing how the timer controls the output pin. It's taken from the
ATmega328P datasheet, but the other AVRs of that family behave
identically in this respect:

As shown in the schematic, the value written to the port comes from a
multiplexer and is controlled either:

by the PORT flip-flop when the timer is not generating a PWM output
or the OC0A flip-flop when it is.

Quite importantly, the timer does not write to the PORT register, it
only overrides it.
Thus, it would look like you want to read the OC0A flip-flop in your
ISR. Alas, this schematic also shows that, contrary to the PORT
flip-flop, the OC0A flip-flop is not connected to the data bus. Thus
you cannot read it, and it doesn't even have an address.
What I would recommend is to read the PIN register instead. This won't
tell you what the timer is writing to the port, but what you can read
back. However, unless the pin is loaded well beyond its absolute maximum
rating, what you read back what has been written. There is a small delay
between the write operation and the value been available to read back (a
couple of CPU cycles IIRC), but this is way shorter than the execution
time of an ISR prologue.

Thanks for pointing out that I had the incorrect port. I mixed up datasheets, and it is the ATmega16 that uses PB3 = OC0 (page 56 of the ATmega16 datasheet)

Just to clarify: I need to use bitRead(PIND,6);?

@Greenonline: Either that or PIND & _BV(PD6). I tend to favor the later: avr-libc style when doing direct port access, and Arduino style when programming the Arduino way. But in the end it's just a matter of style.


text:
Double Speed Operation for USART on Arduino Mega 2560
I happened to be looking through the HardwareSerial.cpp file that contains the functions used for Serial communication for Arduino.  While looking through the HardwareSerial::begin(baud, config) function, I noticed that the ucsra register has its U2X0 bit set.  When I looked through the datasheet, it says that the U2X0 bit is set to start Double Speed Operation.  From what I'm reading, this means that the baud rate is doubled.
I've been using this Arduino on this computer for a while now with no complaints for the baud rate being at an incorrect speed. What is Double Speed Operation?  Why does it seem to be set in the code by default? I attached the code and section in the manual below.
void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

  _written = false;

  //set the data bits, parity, and stop bits
  #if defined(__AVR_ATmega8__)
    config |= 0x80; // select UCSRC register (shared with UBRRH)
  #endif
  *_ucsrc = config;

  sbi(*_ucsrb, RXEN0);
  sbi(*_ucsrb, TXEN0);
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
}

When in double-speed mode, as noted in the manual, fewer samples are used. In Asynchronous serial communication, there is no clock signal, so the clock that keeps the two devices in sync is extrapolated from the data signal. Each end of the communication has it's own clock source (crystal oscillator, ceramic resonator, R-C oscillator, etc.), and you'll rarely find two that are calibrated identically.
The receiver samples the signal at a higher rate than the actual baud rate so that it can better determine where, relative to it's own clock, the data-signal edges go up or down and continually adjusts its offset to compensate for clock drift.
By operating in double-speed mode, the receiver has fewer samples to work with, and so if your transmitter has a clock source that is different enough than the receiver, or is not stable, or you have long or noisy wires or fluctuating temperatures (etc.) then you may experience less stable communication.
If your particular use-case works fine, then stick with it. But if you start to notice errors in communication, the first troubleshooting step would be to disable this mode, since the clock recover is less robust in this mode.

As explained in jose can u c’s answer, in double speed mode the UART has
fewer samples for doing clock and data recovery. But this doesn't help
answering the second question:

Why does it seem to be set in the code by default?

Double speed mode has also an advantage: it enables higher resolution in
setting the baud rate. In normal mode, the bit duration is constrained
to be a multiple of 16 CPU clock cycles, whereas in double speed
mode it is only constrained to a multiple of 8 cycles.
As an example, let's say you want 57600 bps on a 16 MHz
Arduino. Then,
F_CPU ÷ desired_baud_rate = 277.78 = 8 × 34.72 = 16 × 17.36
In single speed mode, this would be rounded to 16 × 17, and the rounding
error would make the baud rate 2.1% too fast. In double speed mode, it
is rounded to 8 × 35, and the baud rate is only 0.8% too slow. Thus you
get better baud rate accuracy in double speed mode. Note that for some
baud rates, like 9600 bps, single speed and double speed yield the
exact same rate.
This is presumably the reason the Arduino core uses double speed mode,
except for a documented compatibility exception and for extremely low
baud rates (double speed cannot work below 488 bps).
It should be noted that this is not the only possible strategy. The
avr-libc, for example, provides some helper macros for baud rate
calculations. These macros give preference to single speed
mode and revert to double speed only if the rounding error exceeds a
specified tolerance, which defaults to 2%.

Thank you very much!  That makes a lot more sense now.  I had no idea how running Double Speed Operation all the time worked for the Arduino.


text:
ESP8266 Bad request error 400
#include <ESP8266WiFi.h>

const char* ssid     =  "Tonosh";
const char* password =  "a43056043";

const char* host     =  "192.168.8.107";

void setup()
{
  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid,password);

  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());

}

int value = 0;

void loop()
{
  delay(2000);
  ++value;

  Serial.print("Connecting to ");
  Serial.println(host);

  WiFiClient client;
  const int httpPort = 80;
  if(!client.connect(host,httpPort))
  {
    Serial.println("Connection failed");
    return;
  }

  String url = "http://192.168.8.107/prueba.php";

  String data = "serie=777&temp=33";

  Serial.print("Requesting URL:  ");
  Serial.println(url);

  client.print(String("POST ") + url + "HTTP/1.0 \r\n" +
               "Host: " + host + "\r\n" +
               "Accept: *" + "/" + "*\r\n" +
               "Content-Length: " + data.length() + "\r\n" +
               "Content-Type: aplication/x-www-form-urlencoded\r\n" +
               "\r\n" + data
              );
  delay(10);

  Serial.println("Respond:");

  while(client.available())
  {
    String line = client.readStringUntil('\r');
    Serial.print(line);

    Serial.println("Closing connection");
  }
}

Any idea? I tried different post here and nothing works.

in POST line the url should be without protocol and host. "POST /prueba.php HTTP/1.0

Thanks a lot this simple trick to print it to the console already helped.

HTTP status code 400 means that your request syntax is invalid.
Here's a good way to debug it: store the request in a string, print that, and then transmit it. You'd see very quickly at least one of the problems your code has.
String request = String("POST ") + url + "HTTP/1.0 \r\n" +
                 "Host: " + host + "\r\n" +
                 "Accept: *" + "/" + "*\r\n" +
                 "Content-Length: " + data.length() + "\r\n" +
                 "Content-Type: aplication/x-www-form-urlencoded\r\n" +
                 "\r\n" + data;
Serial.print(request);
client.print(request);

The request in the POST line needs to be just the pathname and any arguments. You also need a space before HTTP/1.0.
So right now you're transmitting:
POST http://192.168.8.107/prueba.phpHTTP/1.0

when you need to transmit
POST /prueba.php HTTP/1.0


text:
ESP8266-01 WifiScan not working
I have a ESP8266-01 and am trying to get it to work. I am using the example WiFiScan code shown below.
#include "ESP8266WiFi.h"

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

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

I have a voltage regulator producing 3.3 V connected to CH_PD and the Arduino powers the ESP's VCC via the 3.3 V pin. TX is connected to TX and RX is connected to RX. GPIO0 is connected to ground. I can upload, but it cannot find any networks. It always states no networks found. Now I'm not even sure how to proceed... Any help would be appreciated.

Try Wifi access point example and connect green wire to 2 and white one to 3. And give it a try

ch_pd is an enable signal, VCC draws current that the Uno 3.3 pin can't supply

Actually, I'm not too sure how to control the current being produced. Some things I have tried include using the 5V but adding a 100ohm resistor, and powering the esp through the mains via a phone charger. Do you have any suggestions? Thanks!

and the voltage regulator? how many amperes can it supply?

Try connecting the ESP's Vcc to your 3.3v regulator. You didn't say which regulator you are using but most will be able to supply more than enough current for your ESP. I power my ESP-01s with LM-1117 regulators which can supply up to 800mA.

I have connected a multimeter in series to the circuit to read the current produced by the voltage regulator. I connected the positive probe to the positive output of the voltage regulator and the negative probe to the VCC of the esp. The circuit still lights up but the multimeter shows 0A. Am I connecting it wrong. I am using a 2A fast charger for the source and a LM2596 DC-DC regulator.

You should provide a good power source for the VCC. One that can supply 170 mA for WiFi operations of esp8266. You should use the power regulator to supply 3.3 V to VCC and there is no reason to use other power source for the CH_PD pin. CH_PD pin is "enable" pin, it doesn't need a strong power supply.
IO 0 should be connected to ground only for upload, not for normal operation.


text:
Using a DFRobot Voltage Divider
I'm reading on the DFRobot website to implement this Voltage divider: Analog Voltage Divider SKU: DFR0051
void setup()
{
  Serial.begin(9600);
}
void loop()
{
      float val;
      float temp;
      val=analogRead(2);//This divider module will divide the measured voltage by 5, the maximum voltage it can measure is 25V.
      temp= val/40.92;
      val=(float)temp;
      Serial.println(val);
      delay(1000);
}

Where does 40.92 come from? And even when printing only VAL it's something like 210 and I'm not sure what this is supposed to be. I don't get how to get the actual voltage of the battery etc. being measured? If it's divided by 5, why do you not multiply by 5 anywhere?

1023/25=40.92

How is this Uno code? An Uno has no SerialUSB.

Im using it on another board, sam thing. just replae SerialUSB with Serial....

Then why is it tagged [tag:arduino-uno]?

The unit measures a maximum voltage of 25v. When the measured voltage is 25v it divides it by 5 to present a maximum of 5v to the Arduino.  That is measured as a value of 1023 by analogRead(). If you divide 1023 by 40.92 you get 25.


text:
How do i send ads1115 data over spi to master arduino
I am trying to send ADS 1115 data which is connected with Arduino mega_1 over I2C and arduino Mega_1 is connected with arduino Mega_0 over SPI.
Arduino Mega_1 is act as a slave and send ADS 1115 data to master device..
I think my whole setup is working but i want to received actual data of ADS 1115 on master Arduino
Here is screenshots of results of my code
master
#include <SPI.h>

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

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{
byte a;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
a=transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("results:");
  Serial.println (a);

  delay (1000);  // 1 second delay
}  // end of loop

slave
#include <Wire.h>
#include <Adafruit_ADS1015.h>
int out_buf;
int adc0;

// Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
Adafruit_ADS1015 ads;
// what to do with incoming data
volatile byte command = 0;
void ss_falling ()
{
  command = 0;
}
void setup (void)
{
 ads.begin();
 Serial.begin(9600);
 //ads.startComparator_SingleEnded(0, 1000);
// have to send on master in, *slave out*
 pinMode(MISO, OUTPUT);

// turn on SPI in slave mode
 SPCR |= _BV(SPE);

 // turn on interrupts
 SPCR |= _BV(SPIE);
 attachInterrupt (0, ss_falling, FALLING);

}

// SPI interrupt routine
ISR (SPI_STC_vect)
{
 byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = out_buf; // add 15
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
adc0 = ads.readADC_SingleEnded(0);
Serial.print("AIN0: "); Serial.println(adc0);

out_buf=adc0;
//int buff = atoi(out_buf);
Serial.print("AIN1: "); Serial.println(out_buf);
delay(1000);
 }

i am sending 1570 but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time i am stuck here please help me.
Thank you in Advance
example

My Problem is solved now, thanks to the almighty. I did few changed in code as:
1. Converted the received int type data from ADS to Char.
2. Stored it in an Array, to form a string.
Here is my Modified Slave Code:
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1015 ads;
void setup (void)
{
ads.begin();
 Serial.begin(9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

char buf[20];
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
int adc0=0;
adc0 = ads.readADC_SingleEnded(0);
itoa(adc0,buf,10);
Serial.print("AIN1: "); Serial.println(buf);
delay(500);
}  // end of loop

On Master side
We are receiving string by sending one dummy value at a time.
Here is modified master code:
#include <SPI.h>

void setup (void)
{
  Serial.begin (9600);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (500);
}  // end of loop

Implementing SPI slave mode is a little more tricky than you may think.  The most important thing to remember is that it's not a "Give me X" -> "Ok, here is X" kind of protocol.  It's actually a "Here's X" <=> "Here's Y" protocol.
That is, at the same time that the master sends X to the slave, the slave sends "Y" to the master.
The way you have it is that the master sends "a" as a command and discards what it receives.  The slave remembers that "a" as the "command". Then the master sends 0, and remembers what it receives. The slave receives that 0 and thinks "Ah, I got the command last time, so it must want the value" and queues up the value to be sent the next time a transaction occurs.  That then gets thrown away, since that occurs when the next "command" is sent.
You need to be a little more cunning, and implement a finite state machine to work out where in the stream you are.

When SS falls set a "byte counter" to 0.
When a byte is received examine the "byte counter":

Byte 0: If it's an "a" then place the first byte of the value in SPDR.
Byte 1: Place the second byte of the value in SPDR
Byte 3: Do nothing (or place 0 in SPDR)

Increment the byte counter

So the transaction goes something like this (1570 is 0x622 in hex, and I choose "little endian" since the AVR is naturally little endian):
Master Sends        Slave Queues          Master Receives
'a'                 0x22                  Rubbish
0                   0x06                  0x22
0                   0x00                  0x06

'a'                 0x22                  0x00
0                   0x06                  0x22
0                   0x00                  0x06

The important thing to remember is that the master receives what the slave queued on the next transfer.

My SPI communication is working fine because i also tried addition and subtraction between master and slave and the result was "ok "

If your spi communication were working fine you wouldn't be here asking us for help...

dude read this lines "i am sending 1570 which is a ads1115 data but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time." SPI is ok to me.... i think there is something missing like byte to char conversion or split 16 bit adc data into 8 bits and thn sent to master that is my real problem.

35 has no relation to 1570. The closest you could be receiving would be 34 (0x22). Fixing your code in the way I specify not only fixes the mess you made of the sending system, but also fixes the 16-bit issue. Oh, and make your out_buf volatile. Also the out_buf should be "captured" at the point you either queue the first byte, or when SS falls.

i added two more screenshots in which i send 10 and in return i received 20  "20=10 +10"

It's pure chance that sometimes you happen to receive a result you think is right. It isn't You're receiving old results from previous transactions that never got sent.

ok if i am doing wrong thn what is the right way to send ads data to master arduino by using spi

How I detailed in my answer.


text:
Writing analog voltages on analog pins of Arduino
Can we write a analog voltage to analog pins A0-A7 of the Arduino Nano (for example)?
As in:
pinMode(A3, OUTPUT);
analogWrite(A3, 200);

read the doc https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

No. The analogWrite(pin, val) function is reserved to PWM pins (D3, D5, D6, D9, D10, and D11 in Arduino Nano). Pins marked as "ANALOG IN" on the board can work either as analog input (to the Analog to Digital Converter), digital input, or digital output.
It is worth to note that the Arduino Nano (and any other Arduino board I'm aware of) actually doesn't have any 'true' analog output port. When you use analogWrite(pin, val) you are actually telling the Arduino to output a PWM signal with the duty cicle specified by val (100% for val = 255 and 0% for val = 0). If you actually do need a true analog output, you should consider using any form of analog lowpass filter at the specified PWM output port. Depending on how clean you want your signal to be, you could use a single capacitor or any other (a little more complex) filter.
If you don't know anything about filters, this could be a good starting point: ElectronicsTutorials - Passive Low Pass Filter
More insight about PWM in Arduino, here: EAS 199 - Basic Pulse Width Modulation

Note that the Due does have two true analog output pins (called DAC0 and DAC1), in addition to a dozen PWM pins.

analogWrite are PWM digital pins. Analog pins on Nano are ADC read/input only (or digital I/O except A6 and A7).

All microcontrollers including Arduino are digital, and rely on specific circuit hardware in order to interface with the analog world.  Two of these relate to your question:

Analog-to-digital converters (ADCs) sample an analog voltage and output a number representing the voltage relative to the measurement range - such as 0 to 1023 on a 10-bit ADC.
Digital-to-analog converters (DACs) do the reverse, where a digital number from the microcontroller is used to output an analog voltage, e.g. between ground and the supply voltage.

While ADCs and DACs convert analog-to-digital and vice versa, they need different circuits.  In the case of Arduino boards and other microcontrollers, analog input (read) and output (write) must use different pins.  Analog input pins cannot be used as outputs, and vice-versa.
The exception is where you want to produce an analog output via PWM (and a smoothing capacitor).  In that case the answer is yes, you can use pins A0-A7.  However, you will need to bit-bang and won't be able to use the timer hardware.  It's much easier to use the pins dedicated to DAC or analogwrite if that's an option for you.

You can create your own PWM on non-PWM pins using Blink Without Delay techniques.  Use the micros() timer and check it every pass thru loop() to if it is time to change the state of the output.
This will create 50% duty cycle, with frequency = 1/(2 x halfPeriod)
void loop(){
  currentMicros = micros(); // capture the current 'time'
  elapsedMicros = currentMicros - previousMicros;
  if (elapsedMicros >= halfPeriod){
    previousMicros = previousMicros + halfPeriod; // set the 'time' of the next transition
  }
}

all time related elements are of type unsigned long
Then filter with a RC Lowpass filter (Resistor and a capacitor) to smooth it out so it's more like an analog level.


text:
The code does not produce the serial output
#include <Streaming.h>
#include <StopWatch.h>
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"
const byte adcPin = A0;
void setup(void)
{
    Serial.begin(9600);
    while(!Serial);
    Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
    for(int i=0; i<10; i++)
        testAnalogRead();
}
void testAnalogRead()
{
    static Stopwatch stopwatch(micros);
    //delay(1000);

    stopwatch.start();
    int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
    stopwatch.stop();
    int t1 = stopwatch.interval;

    analogReadResolution(12);
    stopwatch.start();
    int adc2 = analogRead(adcPin); // 425us on SAMD21
    stopwatch.stop();
    int t2 = stopwatch.interval;

    analogReadResolution(10);
    stopwatch.start();
    int adc3 = analogReadFast(adcPin); // 23us on SAMD21
    stopwatch.stop();
    int t3 = stopwatch.interval;

    analogReadResolution(12);
    stopwatch.start();
    int adc4 = analogReadFast(adcPin); // 24us on SAMD21
    stopwatch.stop();
    int t4 = stopwatch.interval;

    Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
    analogReadResolution(10); // restore default
}
void loop()
{
}

This code does compile in the Arduino Zero, but does not produce the serial output on the serial monitor (serial plotter) at all.
What am I doing wrong?

Can you please confirm, that the Arduino really executes the whole setup() function to the end, by turning on an LED at the end of the function? Maybe Serial cannot be initialized correctly, so that it stays in an infinite while loop. Also try a simple example sketch for serial communication to test, if this works

Thanks all for the suggestions. I was able to figure it out after spending few days. The main problem was the Albert.h library was not necessary for this code. I commented out # <Arduino.h> and this worked!!!


text:
Runtime Error when using array of structs of unknown size as variable within class - some kind of overflow issue?
I have a class defined as below, it's basically a simple ring buffer, with some methods for getting useful statistics from the data held in the buffer.
enum BalanceMsgType{
  BAL_MSG_NOT = 0,
  BAL_MSG_READING = 1,
  BAL_MSG_SPECIAL = 2,
  BAL_MSG_ERROR = 3
};

typedef struct MeasuredMass{
  float mg;
  unsigned long time;
  bool steady;
  BalanceMsgType type;
};

class RingBuffer{
  private:
  unsigned int _size = 0;
  unsigned int _pos = 0;
  MeasuredMass *_array;
  void LinearRegression(){
    //... left out for simplicity
  }
  public:
  float lin_reg_m = 0;
  float lin_reg_c = 0;
  float lin_reg_r = 0;
  float est_current_mg = 0;
  //methods
  RingBuffer(unsigned int size){
    _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
    _array = new MeasuredMass[_size];
    for (int i = 0; i < _size; i++){
      _array[i].mg = 0.0;
    }
  }
  void Add(MeasuredMass in_element){
    _array[_pos] = in_element;
    _pos = (_pos + 1)%_size;
    LinearRegression();
    est_current_mg = lin_reg_m*(in_element.time+BALANCE_DELAY) + lin_reg_c;
  }
  void ReadInOrder(MeasuredMass *pdata){  //Call with
                                          //my_buffer.ReadInOrder(data)
    for(int i = 0; i < _size; i++){
      pdata[i]=_array[(_pos+i+1)%_size];
    }
  }
  float Sum(){
    //...
  }
  float Mean(){
    //...
  }
  float StdDev(){
    //...
  }
  bool SteadyEnough(float max_sd){
    //...
  }
};

It compiles fine, and runs nicely in test programs. However, if I include it in larger programs (something like progmem 117404 of 122880 bytes, global vars 13604 of 32768) I get a "Board at COM8 not available" warning when using the Arduino Serial Monitor after uploading to my Fubarino Mini. (Even without actually interacting with those programs beyond creating an instance of the class.) Recent experience tells me this is some kind of crash due to a runtime error.
Fiddling around with the code, I've found that the issue doesn't occur in a version of the library which holds an array of floats instead of my MeasuredMass. That my MeasuredMass struct is obviously much larger than a float suggests to me that this is due to some pointer/array overflowy behaviour.
I've also managed to show that if I alter the class such that it uses a fixed length array rather than a pointer to one, the issue disappears.
i.e. RingBuffer's private member MeasuredMass *_array; becomes MeasuredMass _array[25];
and
RingBuffer(unsigned int size){
  _size = size; //forgetting to put this line -> div0 -> >1hr bugtracking
  _array = new MeasuredMass[_size];
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

becomes
RingBuffer(){
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

I'd rather maintain the ability to set the size of the ring buffer at runtime (in my case it's set based upon the number of seconds' worth of data requested), so can anyone help me in figuring out how I can achieve this without running into the overflow / memory problems I seem to be having?
Thanks

The problem is most likely here:
_array = new MeasuredMass[_size];

You're allocating _size * sizeof(MeasuredMass) bytes in the heap. If _size is too big the amount of memory allocated becomes too great and it fails to allocate. You should check if _array is NULL or not after the new.  If it's NULL then it failed to allocate.
The problem is that heap allocation is limited to 2kB. This is regardless of the amount of memory you actually have in the chip. This is a limit imposed by the compiler (actually the libraries bundled with the compiler) and is set by a value in the linker script.  It's something I've been campaigning to have removed from the libraries for many years, but it's always fallen on deaf ears. So much so that I provide a "fixed" version of the compiler in UECIDE that removes this hard limit.
The best thing you can do is to not use dynamic allocation. Instead have a statically created array which you then pass to the constructor.
MeasuredMass massBuffer[25];
RingBuffer massRing(massBuffer, 25);

and:
RingBuffer(MeasuredMass *buf, unsigned int size){
  _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
  _array = buf;
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

Thank you! I was just in the middle of adding a comment to my original question, wondering if allocating a buffer just before calling the constructor and passing it through would work. But you beat me too it.
On the compiler hard limit - the more I use the Arduino IDE, the more I find that I don't want to use it anymore...

You should move over to uecide for chipKIT stuff... You get better support ;)


text:
Serial data showing incorrect values
I am sending data over USB Serial to my Uno in a specified format and printing the values after they are read
void loop() {
    if(Serial.available()){
        while(Serial.available()){
            int pos = Serial.readStringUntil(':').toInt();
            Serial.println(pos);
            int r = Serial.readStringUntil(',').toInt();
            Serial.println(r);
            int g = Serial.readStringUntil(',').toInt();
            Serial.println(g);
            int b = Serial.readStringUntil(';').toInt();
            Serial.println(b);
        }
    }
}

This is how the data is being sent
0:255,255,255;1:255,255,255;2:255,255,255;3:255,255,255;4:255,255,255;5:255,255,255;6:255,255,255;7:255,255,255;8:255,255,255;9:255,255,255;10:255,255,255;

format is {position}:{Red value},{Green value},{Blue value};
When I send this string to the device through the serial monitor it prints wrong values
0
255
255
255
1
55 //should be 255
255
255
2
55 //should be 255
255
255
3
55 //should be 255
255
255
4
55 //should be 255
255
255
5
255
255
255
6
255
255
255
7
255
255
255
8
255
255
255
9
255
255
255
10
255
255
255

Why is the data wrong?
Is it just the serial monitor that isnt showing it right but the values are actually right?

it probably will not help, but four times parseInt() would do. parsing ends on non-digit character and skips leading non-digit characters

do you send the data as one line?

@Juraj yes one line

@Juraj parseInt actually seems to help I just have to add in some extra logic so it does not keep trying to read after the last number

you don't know the count of rgb sets on the line?

Yes I do so in this example what I do is I check the position as the last thing in the while and if the position is the last expected rgb value I just read until available is zero

I don't think your problem is with your code. I ran it (at 9600, 115200, and 230400 baud) and and got proper-looking results. I used the Arduino built-in terminal in line mode - copy/pasting your sent-data example into the terminal input line and clicking 'Send'.

It looks like you are parsing the incoming data for a string of 4 numbers, pos+r+g+b.  To avoid data loss as well as improve speed (if you need it), it may be better to send the data as bytes:
: 0x01 0xFF 0xFF 0xFF : 0x02 0xFF 0xFF 0xFF : 0x03 0xFF 0xFF 0xFF ... etc

This can be done with Arduino serial monitor via a hex to ASCII converter.  For example https://www.branah.com/ascii-converter
Type in hex (missing 0x, where 0x3a=':'): 3a01FFFFFF3a02FFFFFF3a03FFFFFF3a04FFFFFFFF
Get ASCII: :ÿÿÿ:ÿÿÿ:ÿÿÿ:ÿÿÿ
Copy this into the Arduino serial monitor
Also, try to do all of the serial prints in one go, don't interleave reading and writing unless you absolutely have to.  Sometimes bytes get dropped that way, too.
byte pos, r, g, b;

void setup(){
// serial begin
}

void loop() {
    if(Serial.available()){
        while(Serial.available()){
            Serial.readStringUntil(':');
            pos = Serial.read();
            r   = Serial.read();
            g   = Serial.read();
            b   = Serial.read();
            Serial.write(pos);
            Serial.write(r);
            Serial.write(g);
            Serial.write(b);
         }
    }
}

If you need a more elegant way to do the serial write, you will find plenty of answers already on stack exchange (too many to suggest only one).

Technically I dont need the delimiters, I was just using them as a way to know what I was reading by separating the values

@MichaelT, how do you send bytes from Serial Monitor to be read by read()? I don't think the Serial Monitor converts hex to bytes

The Arduino serial monitor allows character input.  You can use other programs either to convert byte to char (and copy/paste into the IDE), or do the entire serial reading and writing (like Qt, matlab, mathematica).

but the question implies Serial Monitor as input and output. your answer is good and true, only add some intro about sending and receiving with a computer program

I have given an example of how to send hex with Arduino serial monitor.  If it works for you please accept/upvote.


text:
Problem with incrementing values of an RGB LED
I'm trying to use a remote control to control the red/green/blue values of an RGB LED using an Arduino Uno. Here's what I've got so far:
#include <IRremote.h>
#define IRPin 7
#define bluePin 9
#define greenPin 10
#define redPin 11

int blueValue = 0;
int greenValue = 0;
int redValue = 0;

IRrecv irrecv(7);
decode_results results;

void RGBLED(int blue, int green, int red)
{
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void setup(){
  irrecv.enableIRIn();
  pinMode(sensorPin, INPUT);
  Serial.begin(9600);
}

void loop(){
if (irrecv.decode(&results)){
  switch(results.value)
  {
    case 0xFF6897:
      Serial.println("Red+16");
      redValue = redValue + 16;
      if(redValue >= 256)
      {
        redValue = 255;
      }
    break;
    case 0xFF9867:
      Serial.println("Green+16");
      greenValue = greenValue + 16;
      if(greenValue >= 256)
      {
        greenValue = 255;
      }
    break;
    case 0xFFB04F:
      Serial.println("Blue+16");
      blueValue = blueValue + 16;
      if(blueValue >= 256)
      {
        blueValue = 255;
      }
    break;
    case 0xFF30CF:
      Serial.println("Red-16");
      redValue = redValue - 16;
      if(redValue < 0)
      {
        redValue = 0;
      }
    break;
    case 0xFF18E7:
      Serial.println("Green-16");
      greenValue = greenValue - 16;
      if(greenValue < 0)
      {
        greenValue = 0;
      }
    break;
    case 0xFF7A85:
      Serial.println("Blue-16");
      blueValue = blueValue - 16;
      if(blueValue < 0)
      {
        blueValue = 0;
      }
    break;
  }
irrecv.resume();
RGBLED(blueValue, greenValue, redValue);
}

Everything works fine, except the adding up to redValue. It's the same exact code that is used for greenValue and blueValue. The substraction from redValue works fine too. Everytime the problematic function gets called, the serial monitor prints Re and the whole thing just stops working.
I have tried rewriting that code from scratch, copying the other code, but nothing worked. I have switched up the codes from my IR remote but that had nothing to do with it either.
Can anyone spot the mistakes or tell me what I'm doing wrong?
Thanks in advance

try a short delay and see if that helps

Try swapping the red case with the green case, and see if now the green will give the problem. (i.e. maybe the first case somehow breaks things).

Are you sure this is the code you are using? setup() uses sensorPIN but it does not appear to be declared anywhere.

@Craig I'm also using a sound sensor as a clap sensor to turn on the LED, but that isn't causing the issue, so I removed it.

@Gerben I tried switching the two around and the red one is still broken.

@dandavis adding a short delay after the Serial.println makes it so that the message gets printed fully, but it still doesn't work.


text:
Error compiling for board Arduino/Genuino Uno
I am getting the following error message when compiling a program on my Arduino IDE. This does not happen when compiling the given example programs in the IDE.
The error message is as follows :
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware
C:\Program Files\Arduino\hardware -tools
C:\Program Files\Arduino\tools-builder -tools
C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries
C:\Program Files\Arduino\libraries -libraries
C:\Users\mahim\OneDrive\Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path
C:\Users\mahim\AppData\Local\Temp\arduino_build_361527 -warnings=none -build-cache
C:\Users\mahim\AppData\Local\Temp\arduino_cache_227236 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=
C:\Program Files\Arduino\hardware\tools\avr -verbose
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino
readlink
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino: The system cannot find the file specified.

Error compiling for board Arduino/Genuino Uno.

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.

Following on from duskwuff's answer, 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:
Arduino and Pyton Serial Communication, Pyton get stuck and keeps sending
I have recebntly started a project where I need to connect an arduino and another device through serial. And I have setup a simple serial connection betwee python and arduino. I can setup the connection through the python terminal and it works just fine. When I type : arduino.write("1"), It receives the data only once. However, When I run this code:
import serial

arduino = serial.Serial('/dev/ttyACM0', 115200, timeout=.1)

while True:
    arduino.write("1")

it writes properly, howver when I stop it using Ctrl-C, it doesn't stop sending and keeps sending to the arduino. Stops sending when I open a serial. connection using the python terminal again.
I have no idea what is causing this or how I can fiz it. Would reallly appreciate some help. Thanks in advance:

PC side programming is off-topic here.

Your python code is sending "1"'s to the serial port at a blinding speed.  Way faster than they can go out over the serial line.  So when you stop your python code the serial port is still sending trying to get all the "1"'s out of its buffer.  When you open the connection again you clear that buffer and it stops sending.


text:
Empty output with GPS module GTPA010
I've synced my Uno with the Arduino IDE and I'm using the following code to get the GPS coordinates:
#include <TinyGPS.h>
#include <SoftwareSerial.h>

unsigned long fix_age;
SoftwareSerial GPS(4,3);
TinyGPS gps;
void gpsdump(TinyGPS &gps);
bool feedgps();
void getGPS();
long lat, lon;
float LAT, LON;

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

void loop(){
  long lat, lon;
  unsigned long fix_age, time, date, speed, course;
  unsigned long chars;
  unsigned short sentences, failed_checksum;
  // retrieves +/- lat/long in 100000ths of a degree
  gps.get_position(&lat, &lon, &fix_age);
  // time in hh:mm:ss, date in dd/mm/yy

  getGPS();
  Serial.print("Latitude : ");
  Serial.print(lat/100000,7); //#UPDATED
  Serial.print(" :: Longitude : ");
  Serial.println(lon/100000,7); //#UPDATED
}

void getGPS(){
  bool newdata = false;
  unsigned long start = millis();
  // Every 1 seconds we print an update
  while (millis() - start < 1000)
  {
    if (feedgps ()){
      newdata = true;
    }
  }
  if (newdata)
  {
    gpsdump(gps);
  }
}

bool feedgps(){
  while (GPS.available())
  {
    if (gps.encode(GPS.read()))
      return true;
  }
  return 0;
}

void gpsdump(TinyGPS &gps)
{
  //byte month, day, hour, minute, second, hundredths;
  gps.get_position(&lat, &lon);
  Serial.print("Hello World : "); //#UPDATED (Test)
  LAT = lat;
  LON = lon;
  {
    feedgps(); // If we don't feed the gps during this long
  }
}

When I compile, it uploads successfully and when I check the serial streams, it displays:
Latitude : 41103 :: Longitude : 41103
But my lat/lon (in the risk of disclosing location) is
(38.984898400, -76.957276900)
It doesn't seem to be the same.

is the GPS getting a good view of the sky?   Should add some prints to see if you are getting into gpsdump()   or just print your lat/lon rather then reassigning it to LAT/LON

@ChadG: I've kept it on a wide window sill with a view. So I guess that should work. Surprisingly, now it's even displaying garbage like
⸮7C⸮wyCCZVa⸮HR-⸮K=LR3⸮(⸮:⸮xk;GqB⸮9Jb⸮j
I added some prints inside the gpsdump(). Nothing happens, so I'm not even sure if it's getting into it.

Can you update the code and provide the output

@ChadG: I updated the code and results.

Actually update the code in the question, its to hard to go back and forth between your original code and the comment.   Did you ever try the GPS baud rate of 4800?

@ChadG: I did just now. No change in the lat/lon. Also if I change the baud rate from 9600 in the serial monitor, it again outputs garbage.

You have control of both sides of the serial monitor speed.   The drop down in the serial monitor needs to match the speed that is in the Serial.begin() function.   The GPS.begin() needs to match what the gps is outputting. (which is usually fixed and not changable)    I would print the data received from the gps directly to the console, no need to try and process it until you are sure your getting good data from the GPS. The strings coming out of the gps are human readable, so you will be able to see if your getting data this way, and then send it be processed after that is working

@ChadG: In that case, my other (possibly duplicated) post should output the raw data correctly?
https://arduino.stackexchange.com/questions/53963/garbage-output-with-gps-module-gtpa010?noredirect=1#comment112937_53963

Did changed the baud rate on the other code do any good?

@ChadG: Surprisingly, no. I'm really clueless now.

Did you ensure you have the RX/TX pins correct for the GPS? You can swap them in the code without harming anything.

@ChadG: After a discussion with my team, it seems the GPS module was faulty. I replaced it with a Adafruit Ultimate GPS and now it's working fine :) What a pain!


text:
Interrupts: use of the "volatile" keyword with a structure pointer for button debounce
I've written a small sketch targeted at the Arduino Uno (ATmega328P) to debounce a mechanical pushbutton using the summing/integration technique:
#include <IntegratingDebounce.h>
#define PIN_BTN 4

IntegratingDebounce *btn;

ISR (TIMER2_OVF_vect) {
  ideb_poll(btn);
} // end timer2 overflow ISR

void set_debounce_timer() {
  TCNT2 = 0;                                  // Clear timer
  TCCR2A &= ~( bit( WGM21 ) | bit( WGM20 ) ); // Set waveform generation mode to normal
  TCCR2B &= ~bit( WGM22 );
  TIMSK2 |= bit( TOIE2 );                     // Enable interrupt on overflow
  TCCR2B |= 7;                                // Start clocking the timer
} // set_debounce_timer()

void setup() {
  Serial.begin(9600);
  pinMode(PIN_BTN, INPUT_PULLUP);

  ideb_init(&btn, PIN_BTN, 4);
  set_debounce_timer();
} // setup()

void loop() {
  while (ideb_read(btn) == HIGH);  // wait until the button pin goes low
  Serial.println("Pressed!");
  delay(100);
} // loop()

An IntegratingDebounce structure stores the data needed to perform the debounce. I keep a pointer to the structure, btn, in the global memory space.
The timer2 overflow ISR periodically polls the state of the button pin, updates the internal integrator, and sets the (also internal) debounced output accordingly. The ideb_read() function reads the debounced output out of the structure.
I'm having trouble determining where the volatile keyword should be placed in the declaration for the btn structure pointer. First I declared it as:
volatile IntegratingDebounce *btn;
I thought this would make all of the fields in the structure pointed to by btn volatile, but button presses are not detected in loop(). Declaring btn as a volatile pointer rather than a pointer to a volatile structure generates the expected output:
IntegratingDebounce *volatile btn;
This seems backwards. Why does this work?
IntegratingDebounce.h
#ifndef __INTEGRATING_DEBOUNCE_H__
#define __INTEGRATING_DEBOUNCE_H__

#include <Arduino.h>
#include <stdint.h>

extern "C" {

typedef struct IntegratingDebounce_S IntegratingDebounce;
typedef uint8_t ideb_size_t;

// Create a debounce structure and initialize.
void ideb_init(
  IntegratingDebounce **ideb,
  uint8_t pin,                  // I/O pin to debounce
  ideb_size_t clamp             // debounce clamp; the maximum value the
                                //   internal sum is able to take on
);

// Poll the state of the pin, integrate, and update the debounced output.
void ideb_poll(IntegratingDebounce *ideb);

// Read the debounced state of the pin.
uint8_t ideb_read(IntegratingDebounce *ideb);

// Reset the internal integrator to either the LOW or HIGH state.
void ideb_reset(IntegratingDebounce *ideb, uint8_t state);

} // extern C

#endif

IntegratingDebounce.c
#include "IntegratingDebounce.h"

struct IntegratingDebounce_S {
  uint8_t pin;              // pin to debounce
  uint8_t output;           // debounced output
  ideb_size_t clamp;        // debounce clamp
  ideb_size_t integrator;   // clamped running sum
};

void ideb_init(IntegratingDebounce **ideb, uint8_t pin, uint8_t clamp) {
  *ideb = (IntegratingDebounce *)malloc(sizeof(IntegratingDebounce));
  (*ideb)->pin = pin;
  (*ideb)->clamp = clamp;
  (*ideb)->output = 0;
  (*ideb)->integrator = 0;
} // ideb_init()

void ideb_poll(IntegratingDebounce *ideb) {
  // update the integrator based on the present state of the pin:
  // - if LOW, decrement the integerator; if HIGH, increment the integrator
  // - constrain the integrator to values between 0 and 'clamp'
  if (digitalRead(ideb->pin) == LOW) {
    if (ideb->integrator > 0) ideb->integrator--;
  } // if
  else {
    if (ideb->integrator < ideb->clamp) ideb->integrator++;
  } // else

  // update the output based on the value of the integrator; the output
  // will not change until the integrator reaches a limiting value
  if (ideb->integrator == 0 && ideb->output == HIGH) {
    ideb->output = LOW;
  } // if
  else if (ideb->integrator == ideb->clamp && ideb->output == LOW) {
    ideb->output = HIGH;
  } // else if
} // ideb_poll()

uint8_t ideb_read(IntegratingDebounce *ideb) {
  return ideb->output;
} // ideb_read()

void ideb_reset(IntegratingDebounce *ideb, uint8_t state) {
  if (state == LOW) {
    ideb->integrator = 0;
    ideb->output = LOW;
  } // if
  else {
    ideb->integrator = ideb->clamp;
    ideb->output = HIGH;
  } // else
} // ideb_reset()

I think, that the problem is in ideb_read, which expects "a pointer to (non-volatile) structure" and so it does not care about re-reading ideb->output if it can it optimize out somehow (say putting it in free register).
IMHO the ideb_read should have parameter declared as (volatile IntegratingDebounce *ideb) (to know, that structure pointed by ideb is volatile) or use global variable btn (which is pointer to volatile structure) instead of pointer parametr to non-volatitle structure.

And why the second works would be because it forces re-read the parameter of ideb_read and so it cannot be saved out somewhere and the function is indirectly forced to expect changed pointer, so it have to use its 'new value' and read the structure (as it is simpler, than ensure, that the ideb have the same value as it had last call and so the whole structure there (which is declared as non-volatile in header of ideb_read) could be cached)

Another wording of the above:
Declaring volatile IntegratingDebounce *btn; the main program in loop simply takes the value of btn (which is non-volatile pointer to volatile structure) and copy that (non-volatile) value to ideb parametr od ideb_read, which is non-volatile pointer to non-volatile structure. ideb_read use it that way and compiler somehow was able to cache all of that and so not read ideb->output again, as it knows, that it is part of non-volatile struct. (So it does not work)
Declaring IntegratingDebounce *volatile btn; you made the btn volatile, so it gets read each time ideb_read is called and the 'new actual value' is passed to (non-volatile) ideb parametr (which is this way given 'new value' and so cannot be cached between calls) and it results to reading (non-volatile) date from "new" place pointed by ideb. So it works (by mistake).
Right solution would be declare correctly volatile IntegratingDebounce *btn; in main program AND declare correctly uint8_t ideb_read(volatile IntegratingDebounce *ideb) so the ideb_read function is forced read value pointed by ideb every time again (which is the right thing to do)
And it should be used for all other ideb_** functions too.
And I think, that it would be simpler to declare some typedef for this volatile structure (something like typedef struct { ... } volatile ideb_t; ) and use the new type everywhere.

That is making sense, and your solution works! Thanks. So passing a volatile IntegratingDebounce * as an argument to a function that expects an IntegratingDebounce * is an implicit type conversion to non-volatile, allowing the structure to be cached?

Yes, "pointer as pointer, it just points somewhere to memory" :) After all you can convert any pointer to void* and then convert it to any (other) pointer.

Also keep in mind, that the IntegratedDebounce.* can be (and usually is) compiled (long) before the main.* and (as any library after all) does not know much, what would use/call it and how. (and the ideb_read is so small and easy, that compiler probably would it convert it into inline where possible, as the function body is lot smaller (in asm), than the preffix and suffix of the function and comparable with length of calling sequence.

Getting pointer declarations right can be anything but obvious, especially where const and volatile are concerned (which are syntactically equivalent). Your problem stemmed from the confusion between "volatile pointer to struct" and "pointer to volatile struct". See the difference? In words it's fairly clear. In C, it has you - and me - running to your C manual's Table of Precedence.
I keep a copy of Dan Saks' article, "Const T vs. T Const" on hand for just exactly this case - it seems I always need to look it up.
And while you're there, check out some of his other articles as well. I learn something every time I read one.

The article is very helpful, particularly in the suggestion to place const and volatile to the right of other type specifiers to improve the right-to-left reading. Thanks!

Also interesting and simple insight is here - http://unixwiz.net/techtips/reading-cdecl.html


text:
ESP8266 Stops Working After A While (Unknown Problem)
have an esp8266.
i'm trying to create a DDNS updater.
it has to wait 5 min then do a GET request to a URL.
Here's my code:
/* Code For DNS Updater.*/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define LOOP_TIME 300000

const char* ssid = "SomeSSID";
const char* password = "SomePSWD";

const String address="http://dynamicdns.park-your-domain.com";
const String path="update";
const String pathHost="host";
const String pathPassword="password";
const String pathDomain="domain";

const String dnsName="my-example-host.com";
const String ddnsPassword="my-example-password";
const String updateHosts[]={
    "@",
    "subdomain1",
    "subdomain2",
  };

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

long nextUpdate=0;

void loop() {
  if(nextUpdate<millis()){
    if (WiFi.status() == WL_CONNECTED) {
    updateDNS();
    }else{
      connectWiFi();
    }
    nextUpdate=millis()+LOOP_TIME;
  }
}

void updateDNS(){
  Serial.println("Updating Hosts:");
  for(int host=0;host<(sizeof(updateHosts)/sizeof(String));host++){
    Serial.print(updateHosts[host]+": ");
    String assembledURL=address+"/"+path+"?"+pathHost+"="+updateHosts[host]+"&"+pathDomain+"="+dnsName+"&"+pathPassword+"="+ddnsPassword;
//    Serial.println("Host: "+updateHosts[host]+" URL: "+assembledURL);
    HTTPClient http;
    http.begin(assembledURL);
    http.GET();
    http.end();
    Serial.println("Done");
  }
}

void connectWiFi(){
  WiFi.begin(ssid, password);

  Serial.print("Connecting To ");
  Serial.println(ssid);
  Serial.print("Password: ");
  Serial.println(password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
    Serial.print(".");

  }
  Serial.println();
  Serial.print("Connected To ");
  Serial.println(ssid);
}

and it stops after a couple of hours - which isnt good for a DDNS updater.
EDIT: maybe it has something to do with my timer. will try an unsigned long instead.

Hi @NadavTasher and welcome to the Arduino Stack Exchange community.  Unfortunately your question doesn't meet our quality standards.Your question is rather terse.  Please edit and improve it. See [ask] and How to ask a good question for Arduino Stack Exchange.

what version of esp8266 arduino package?

shouldn't if(nextUpdate<millis()){ be if(nextUpdate>millis()){, as in the timeout is past the current time?

no, cause if nextUpdate is for example 5000 and millis is 4000 we dont yet wanna run the update.

I have had the "stops after a while" too and it turned out to be heap memory consumption and fragmentation that caused not having enough stack and heap space any more.
My solution: check the heap from time to time (in loop) and reboot the node when it comes down to a practical limit.
Alternate: avoid using the String type and other Heap usages.


text:
exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'
The code below
// include the library code:
#include "LiquidCrystal.h"
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2,4,5,6,7);

void setup()
{
// set up the LCD’s number of columns and rows:
lcd.begin(16,2);
// Print a message to the LCD.
lcd.print("hello");
}
void loop()
{
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

Gives me the following error:
exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

It seems as if you are missing a parameter in the lcd() call. It seem to take six arguments, not five.
From the Blink example in the LiquidCrystal library:
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Also, looking at the library definition, from LiquidCrystal.cpp:
class LiquidCrystal : public Print {
public:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
...
}

The number of arguments accepted by the various overloaded constructors are (respectively):

10
11
7
6

So, your statement:
LiquidCrystal lcd(2,4,5,6,7);

is missing a parameter (or more) as it only has five.
This explains why the error that you are seeing has five ints listed in the parameter list:
'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'


text:
How does Arduino memorize the last bytes from Bluetooth HC-05?
I have made a home automation project.
Description: Light on, off through HC-05 Bluetooth module and my Android app. The problem is when the power is gone, the system stops, that's OK. After that, when the power comes back, the system remains off, as because of no storage of the value.
Please any one help me, that how to store Bluetooth data on EEPROM on Arduino. My simple code looks like...
#include <EEPROM.h>
#define ledPin 7
int state = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
}

void loop() {

  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
  }

  if (state == '0') {
    digitalWrite(ledPin, LOW); // Turn LED OFF
    Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
    state = 0;
  }
  else if (state == '1') {
    digitalWrite(ledPin, HIGH);
    Serial.println("LED: ON");;
    state = 0;
  }
}

Don't shout next time! Also format the code correctly.

Have you tried to use the EEPROM examples from the Arduino IDE? There is a library for using the EEPROM. Do you have any specific problem with it?

Sir you didn't used EEPROM functions, you just initialized them. For example

EEPROM.read();
EEPROM.write();

if you use these function then your issue will be solved out..


text:
How to work with non-traditional UART baud rates
I am trying, unsuccessfully to communicate, using my Arduino Nano, with a custom device at a baud rate of 800 kbit/s.
The Arduino code look like this:
void setup() {
  // Put your setup code here, to run once:
  Serial.begin(800000);
}

void loop() {
  // Put your main code here, to run repeatedly:
  delay(5000);
  Serial.println(0x2be1);
}

When I am trying to debug it with PuTTY the result is:

And when I change the baud rate to 400 kbit/s the result is (as it should be):

Any idea?

The Arduino Nano cannot do 800 kb/s. As you can see in the source
code, the bit duration is rounded to the nearest multiple of
8 CPU cycles. In your case, it is rounded to
3 × 8 CPU cycles, which yields a baud rate of
666.666 kb/s. That is 16% too slow, an error too large for any
communication to be possible.
At 400 kb/s there is no rounding error, so everything works fine.
Edit: Note that if you build your own barebones
Arduino, then either a 12.8 MHz or a 19.2 MHz
crystal should allow you to get that exact baud rate. But then
millis(), delay() and co. would all be off.


text:
Too few arguments for multiple if statement conditions
I am using the Arduino Uno.  I am attempting to only light a red LED when both a blue LED is on and the push button is pressed.  However, I keep receiving an error message stating too few arguments in my if statement.  I don't know whether I am simply overlooking something in my code.
The code is as follows:
int redLEDPin=7;
int blueLEDPin=3;
int redLEDOn=2000;
int redLEDOff=1000;
int blueLEDOn=2000;
int blueLEDOff=1000;
int leverR=2;

void setup() {
    pinMode(redLEDPin, OUTPUT);
    pinMode(blueLEDPin, OUTPUT);
    pinMode(leverR, INPUT);
    }

void loop() {
    digitalWrite(blueLEDPin, HIGH);
    delay(blueLEDOn);
    digitalWrite(blueLEDPin, LOW);
    delay(blueLEDOff);
    }

  if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {
    digitalWrite(redLEDPin, HIGH);
    delay(redLEDOn);
    digitalWrite(redLEDPin, LOW);
    delay(redLEDOff);
    }
  else
  {
    digitalWrite(redLEDPin, LOW);
  }
}

Please include the complete error message in your question.

In function 'void loop()':
24:31: error: too few arguments to function 'void digitalWrite(uint8_t, uint8_t)'

I get the following error: testSE:22: error: expected unqualified-id before 'if'. Please include the error that you are getting (copy and paste it). There's an extraneous } just before your if

The digitalWrite statement in the if statement needs a value to write. It looks like you meant digitalRead, since you're comparing the result to something and the other condition is a digitalRead.
 if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {

vs
 if ((digitalRead(blueLEDPin) == HIGH)  && (digitalRead(leverR) == HIGH)) {

I want the arduino to cause the blue LED to blink.  Only when it blinks and the button is pressed will the red LED be activated.  I think that means I need a digitalWrite for the blueLEDPin and a digitalRead for the leverR

Either way, digitalWrite needs 2 parameters: one for the pin and one for the value. digitalWrite also does not return anything so you can't test if it's equal to something.

So would I be able to set another arduino pin as an input channel that corresponds to the output produced by the blue LED?

This is your loop() function:
void loop() {
    digitalWrite(blueLEDPin, HIGH);
    delay(blueLEDOn);
    digitalWrite(blueLEDPin, LOW);
    delay(blueLEDOff);
    }

Your if() statement is outside of your loop. Check your brackets. In the Arduino IDE, if you put your cursor to the right of a bracket, it will highlight which bracket corresponds to that one.
Large Edit:
To blink two LEDs concurrently, you need to get rid of the delays. Please read about using the millis() function: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing
I don't know how to explain this succinctly, so I am providing the code (note that the on and off times for the LEDs are equal -- if you want them on longer than they are off, you can work on that part of it):
int redLEDPin=7;
int blueLEDPin=3;
int redLEDOn=2000;  //not used
int redLEDOff=250;
int blueLEDOn=2000;
int blueLEDOff=1000;  //not used
int leverR=2;

// the following variables are needed for timing and tracking LED state:
long previousMillisBlue = 0;
long previousMillisRed = 0;
bool ledStateBlue = LOW;
bool ledStateRed = LOW;

void setup() {
    pinMode(redLEDPin, OUTPUT);
    pinMode(blueLEDPin, OUTPUT);
    pinMode(leverR, INPUT_PULLUP); //I am using internal pullup resistor
}

void loop() {
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillisBlue > blueLEDOn)
    {
      previousMillisBlue = currentMillis;

      if (ledStateBlue == LOW)
        {ledStateBlue = HIGH;}
      else
        {ledStateBlue = LOW;}

      digitalWrite(blueLEDPin, ledStateBlue);
    }

    //since we are tracking ledStateBlue above, we can reference it here
    if(digitalRead(leverR) == HIGH && ledStateBlue)
    {
      if(currentMillis - previousMillisRed > redLEDOff)
      {
        previousMillisRed = currentMillis;

        if (ledStateRed == LOW)
          {ledStateRed = HIGH;}
        else
          {ledStateRed = LOW;}

        digitalWrite(redLEDPin, ledStateRed);
      }
    }
    else
    {digitalWrite(redLEDPin, LOW);}

}

@ajf444 please take a look at this and let me know if you have questions

A more succinct way to write the ledStateBlue if/else would be: ledStateBlue = !ledStateBlue; (and similar for ledStateRed)

Your if statement is outside of the loop() function.
Remove the } after delay(blueLEDOff);

Thank you for that. I removed the misplaced } but it still gives me an error message of too few arguments.

@ajf444: digitalWrite() takes 2 arguments (a pin# and a bool) - your calls only supply one.


text:
Arduino loses communication with bluetooth when sending commands to nodemcu esp8266
i've been working on a project using an Arduino UNO, Bluetooth Module HC-06 and NodeMCU esp8266, the project consists on turning leds on via bluetooth and telling the esp8266 that the leds were turned ON, so then we can display some particular webpage data, everything that is not related to the serial communication works perfectly fine.
#include <NewPing.h>
#include <Servo.h>
#include <SoftwareSerial.h>
#define TRIGGER_PIN 2
#define ECHO_PIN 3
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

SoftwareSerial Serial1(5, 4);

Servo myservo;

int ledazul = 8; // LED RED
int scLed1 = 9; // LED 1
int scLed2 = 10; // LED 2
int scLed3 = 11; // LED 3
int scLed4 = 12; // LED 4
int scLed5 = 13;
int fan = 6;
bool br = false;
bool bra = false;
bool porta = false;
int pos = 0;

char val;
void setup() {

  Serial1.begin(115200);
  Serial.begin(9600);
  myservo.attach(7);
  pinMode(ledazul, OUTPUT);
  pinMode(scLed1, OUTPUT);
  pinMode(scLed2, OUTPUT);
  pinMode(scLed3, OUTPUT);
  pinMode(scLed4, OUTPUT);
  pinMode(scLed5, OUTPUT);
  pinMode(fan, OUTPUT);

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

    Serial.print("Ping: ");
    int dist = sonar.ping();
    Serial.print(sonar.convert_cm(dist));
    Serial.println("cm");

  } else {
    //Serial.println("");
  }
  bool ledState = false;

  if (val == '1' && Serial1.available() > 0)
  {

    Serial1.print(val);
    Serial.print("SENT");
  }

  if (val == '0' && Serial1.available() > 0)
  {

    Serial1.print(val);
    Serial.print("SENT");
  }

  if (val == 'A')
  {
    digitalWrite(ledazul, !digitalRead(ledazul));
    ledState = true;
  }
  if (val == 'B')
  {
    Serial.print("Ping: ");
    int dist = sonar.ping();
    Serial.print(sonar.convert_cm(dist));
    Serial.println("cm");
  }
  if (val == 'C')
  {
    digitalWrite(scLed1, HIGH);
    ledState = true;
  }
  if (val == 'D')
  {
    digitalWrite(scLed2, HIGH);
    ledState = true;
  }
  if (val == 'E')
  {
    digitalWrite(scLed3, HIGH);
    ledState = true;
  }
  if (val == 'F')
  {
    digitalWrite(scLed4, HIGH);
    ledState = true;
  }

  if (val == 'G')
  {
    digitalWrite(scLed5, HIGH);
  }
  if (val == 'S')
  {
    digitalWrite(fan, HIGH);
  }
  if (val == 'O')
  {
    switch (porta)
    {
        if (pos < 90)
        {
        case false:
          porta = true;
          for (int x = 0; x < 90; x++)
          {
            myservo.write(x);
            delay(15);
          }
        }
        break;
    }
  }
  if (val == 'P')
  {
    switch (porta)
    {
        if (pos >= 90)
        {
        case true:
          porta = false;
          for (int y = 90; y > 0; y--)
          {
            myservo.write(y);
            delay(15);
          }
        }
        break;
    }
  }
}

What happens is, i can toggle ESP led on or off as long as i dont use commands that uses bluetooth module, it works perfectly fine. Now, if i do use bluetooth commands and then esp commands, it'll lose connection with the bluetooth module.
What im looking for is a workaround for the baudrates, because i have a 9600baudrate for the HC-06 and 115200 for the nodemcu, how do i do to fix it?

You have a copy paste error in the code (nested setup functions). Also I don't really understand the code. With which Serial you connect the HC-06? And what does "it does not work" mean?what are you expecting as output?

Hello Chrisl, There arent any errors with the code. HC-06 is connected to pin 0 and 1 respectively on arduino, and esp8266 is connected to 5 and 4 of the arduino using SoftwareSerial, My problem is that, whenever i send a message to ESP8266 it loses bluetooth connection, i can no longer trigger bluetooth leds, however the opposite doesnt happen. If i toggle bluetooth leds FIRST, i can still toggle esp8266 leds

Yes you have a copy paste error in the code above. Look at the two lines with void setup(). 2. Does the HC-06 lose the bluetooth connection or does the Serial code stop working? This is an important difference, because the Arduino doesn't know anything about the bluetooth connection. It only write on it's serial interface

There is only 1 part in the code, where you read anything from the ESP, but it is commented out. Even if it weren't, it would only be executed, if you first send a 0 or 1 from your bluetooth device. It is unclear, what do you want to achieve with this if-statement, and what with the following else-statement (why is it an error, if there is nothing to read in the receive buffer?) And this else-statement has a syntax error ( you must enclose both commands into the { } pair. All in all correct these errors and describe better, what you want to achieve with these parts of the code.

Hey again chrisl, i have editted the main post with the full code, 0 and 1 sends a message via serial to the ESP8266(NodeMCU), let me remind me that both communication works as long as i dont attempt another module commucation after. Hopefully it should look easier to understand now.

What is the sense in checking, if there is something to read from Serial1, but then don't reading it? Are you sure you want to include this into the if statement?

That was a maneuver to tell arduino to check if serial1 is available to receive inputs from arduino, so it didnt overlap the communication with the bluetooth, after

Let us continue this discussion in chat.


text:
a code problem for arduino GSM 1400 to send a SMS when tilt movment is detected using accelerometer
There is a mistake in the design implementation of the code probably in if statment - when using the serial monitor it repeatedly shows printf() statements from the code instead of "Sending SMS message".
 // Include the GSM library
#include <MKRGSM.h>
#include<math.h>
#include<stdio.h>
int xp = A5;
int yp = A4;
int x,y;
#include "arduino_secrets.h"
// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[] = SECRET_PINNUMBER;

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

void setup() {
    x=analogRead(xp);delay(2);
    y=analogRead(yp);delay(2);

  // initialize 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("SMS Messages Sender");
  pinMode(xp,INPUT);
  pinMode(yp,INPUT);

  // connection state
  boolean connected = false;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (!connected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

void loop() {
    if ((x>=0.60) & (y>=40))

 Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+491781234567\"\r");
    char remoteNum[20];

  // sms text
  Serial.print("your bike is in danger!");
  char txtMsg[200];

  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNum);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
   delay(5000);
   if ((x<=0.30) & (y<=25))

 Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+491781234567\"\r");

  // sms text
  Serial.print("your bike is in danger");
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNum);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
   delay(5000);
}

If that is a real phone number you should redact it, also you should have edited your other post instead of posting a new question.

you already asked this question .... please update your previous question and delete this one .... Problem with code for arduino GSM 1400 to send a SMS when tilt movment is detected

Nowhere in your code will it print "Sending SMS message". It should print "SENDING Message: ". Please paste in the serial output that you are actually seeing, rather than describing it - in your original post rather than this duplicate..

Your if statement is broken!
if(cond)
   statement; // this is conditional
statment2; // this will always be executed!

You need to use a code block:
if(cond)
{
    statement; // both statments are now
    statement2; // conditional!
}


text:
Where should a modified "pins_arduino.h" be stored for Arduino IDE compile?
Our PCB uses an ATmega2560 chip and uses most of the pins, including some that are not defined in the standard pins_arduino.h module, since that module only provides for the pins that are brought out to headers on the Arduino Mega2560 PCB.
We have a modified pins_arduino.h module that has all pins defined, but it doesn't get included in the Arduino IDE compile.  It was cataloged in the same directory as the standard module (that we renamed original).  The path where the modified module is stored is C:/Arduino/hardware/arduino/avr/variants/mega, where the original was also located.
In the sketch, we added #include "pins_arduino.h" as well as #include <pins_arduino.h>, but neither seemed to have included the modified module, so the extra pins are not accessible.  Putting the module in the same library as the sketch didn't help either.
Any suggestions?

Did you try a folder within C:\Users\Username\Documents\Arduino\libraries?

Thanks for suggestion, however it still doesn't give access to the extra pins.

I'd vote for another board variant. Or you can use MegaCore

Now have 2560 “full pin definition” working.  This is what I think I did:
1) Download IDE with "Windows ZIP file for non admin install " from https://www.arduino.cc/en/Main/Software
2) Download pins.arduino.h from https://forum.arduino.cc/index.php?action=dlattach;topic=200887.0;attach=60348
3) Open the IDE distribution zip file and extract all files into the location where you want the IDE files and your sketches to reside.  Could be anywhere.
4) Before starting arduino.exe from the extracted files, replace the pins.arduino.h file that came with the IDE, with the "all pins defined" version.  It is replaced in folder path: .../arduino-1.8.5/hardware/arduino/avr/variants/mega/pins.arduino.h
5) Place sketch within the same path as everything else (e.g. create a folder like “12.My_Sketches” inside “examples”). For example, I put my test sketch Blinky-2560 in folder path: .../arduino-1.8.5/examples/12.My_Sketches/Blinky-2560/Blinky-2560.ino
Why it worked this time?  The only difference I can see is I got the new pins file inserted in the right place before running the IDE.  It is also possible the sketch has to be in the same path as the rest of the IDE (saw that somewhere!?!?).  Otherwise I don’t think there was anything else different from what I was doing with the previously installed IDE.
Since the “all pins defined” file is a superset of the standard mega pins.arduino.h file, there is full compatibility with the Arduino ATmega2560 PCB.  It would be great if Arduino would make this fully defined pins file the standard that comes with the IDE.
Never did get MegaCore to upload the sketch after the compile.

Add another folder in the /variant folder, and put your modified pins_arduino.h in there.
Then in boards.txt, create another section of lines like the exsting Mega section, use a new board name, and add the path to your new folder.
Adding Megacore to the IDE in a similar manner pretty much does all that for you.

Added folder Mega2560DJC in /variants with new pins.ardruino,h module. Duplicated "Genuino Mega or Mega 2560" with name "Mega2560DJC".  Not sure how to add the path to the new folder.  New board doesn't show up in IDE Board list.

Look at how board types are shown in boards.txt.  Make a section like that with  your new info.  I can't look it up further until I get home.  Which Arduino revision are you using? 1.8.5?

Yes, using IDE "Arduino 1.8.5 (Windows Store 1.8.10.0)" reinstalled but no change.

@KIIV  I have added a new board type "allmega" that points to the new “pins.arduino.h” file in C:/arduino/hardware/arduino/avr/variants/allmega with all 2560 pins defined, however, the new board does not show up in the IDE Tools-Board drop-down menu.  Is there something you have to do to make the new board type active in the IDE?