text:
Connect Arduino to Socket IO Webserver via Esp8266
As part of a project I want to receive data on my arduino uno via a sensor, which is working fine. This data should be sent to a webserver where a node js with socket io is running. Therefore i bought a esp8266 and the corresponding adapter (https://www.amazon.de/gp/product/B01LZLVEJ4/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1).
In the IDE I have the following code:
    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Started");

      // set the data rate for the SoftwareSerial port
      esp8266.begin(115200);
    }

    void loop() {
      if (esp8266.available()) {
        Serial.write(esp8266.read());
      }
      if (Serial.available()) {
        esp8266.write(Serial.read());
      }

    }

I use the serial monitor to perform my AT Commands and it seems to work some times, however there seems to be a problem with the output, for example if I type the command AT+CWLAP to display the Access Points. If I do so, it outputs something like:
    +CWLAP:(3,"WLAN-32CC39",-73,"10:c6:0f:2c:32:cc",1,65,0)
    +CWLAP:(3,"F1e:,:oMc:0(x8:1LN⸮⸮⸮:b),k7:,(-,36Ao-2,
    (e0e,C".66,Cwe8:"+L,:"+27:6L W79",944,Ab,::0(ot230( -5,CTO940PBc,63+3y8:")3,dc3
    "P4-ze6P!"80,3716

I should also note, that even if I input the same, the response differs, and sometimes it is just single characters that are wrong, e.g. "wigi" instead of "wifi". I tried different baud's for the esp8266 but the current one produces the least problems. So my questions here are:
1: Is there anything I am currently doing wrong while connecting to my local wifi network?
2: If there is a connection made, is there any way to connect to a socket io server as a client? Most Tutorials I have found have the arduino as a server. However, I want to have it as a client which communicates to a server. Therefore it should both be able to send and receive messages to/from the server.
Thanks in advance!

The baud rate is way too high for SoftwareSerial, try 9600 baud. Don't use AT commands. Either use a library that handles it for you, or program the ESP8266 directly. (I prefer the latter.) By the way, you have been ripped off on that adapter, you can get a WeMos D1 mini for $3.50 (which includes a USB connection etc. for programming).

@tttapa Hello, thanks for the fast answer. I tried switching the baud rate, but when I set the esp8266 rate to 9600, there is no answer after the "AT" command. Even though you said not to use the AT commands, shouldn't it at least work? I searched for libraries but did not find any. By programming myself you mean writing directly in the code to the serial? Sorry I am not really comfortable with arduino development. Also what is wrong with the adapter, does the WeMos D1 do the same thing as the esp8266 and adapter combined? Thanks in advance

Programming it directly means you program the ESP8266 (it is a very powerful microcontroller) instead of the Arduino or as well as the Arduino. It is much easier, more flexible, and more efficient than using AT commands. Take a look at the link I posted in my previous comment.
How did you change the baud rate? You have to use AT+CIOBAUD=9600 (send it at a baud rate of 115200), then reupload the Arduino sketch with a baud rate of 9600 instead of 115200, then it should work.

@tttapa Oh yes I see, I will try that then I think. Setting the baud rate via AT command makes sense, I tried that with both baud rates on 115200, and then executed your command. It returned "ERSOR", and I don't mean "ERROR". That is one of those weird character switches it constantly makes. Also do you have any experience with connecting to a websocket btw?

try AT+UART_DEF=9600,8,1,0,0

@Clueless: Please check my answer below, as Juraj said, you need AT+UART_DEF to set the baud rate permanently.

Using the ESP8266 in general
The easiest, most flexible, and most efficient way is to program the ESP8266 directly.
If it is possible, have it replace the Arduino entirely. To do this, it is best to get an ESP8266 development board that breaks out all IO pins and has a USB interface for easy programming. Programming these development boards is just like programming an Arduino: plug in the USB connection and hit upload in the Arduino IDE. One of my favourites is the WeMos D1 mini (around $3.50 from China).
The ESP8266 is a very powerful microcontroller on its own: it has a 32-bit processor that runs 10 times faster than an Arduino Uno, it has up to 4MB of flash memory (vs 32KB on the Uno), 160KB of RAM (vs 2KB on the Uno). It has 11 digital IO pins, an analog input, support for I²C, SPI, PWM, etc., just like an Arduino. If you use AT commands, you don't use its full potential.
Your specific situation
Given that you already bought an ESP-01 + adapter that only gives you access to the UART, connecting the sensor to the ESP directly is probably not possible.
In this case, you can do one of three things:
1) Program the ESP8266 directly:
Write a program that just reads a number from the serial port, and sends it to the server over WiFi.
This is the easiest, because you can use all features of the ESP8266, and you don't have to change the program that you wrote for the Arduino (it should just measure the sensor value, and send it to the ESP8266 over the serial port, this is exactly the same as sending it to the serial monitor on your computer).
2) Don't program the ESP8266, but use an AT commands library on the Arduino. (For example WiFiEsp)
The downside is that you have to make significant changes to your Arduino sketch, and that you cannot use all of the functions and resources of the ESP.
3) Control the ESP8266 using AT commands yourself, without any libraries.
This is very cumbersome, and is a complete waste of time, IMHO.
Practical
Programming the ESP8266 directly
To program the ESP8266 directly (both with an Arduino and stand-alone), you need a USB-to-Serial converter. You can either use something like an FT232 (3.3V) or an Arduino. How to program it is covered here. If you use an Arduino as USB-to-Serial adapter, the right connections are TX-TX, RX-RX.
Using AT commands or an AT commands library
If your Arduino has a hardware UART that is not used for programming the Arduino (e.g. Arduino Mega, Arduino Leonardo, Arduino Due, ...), you can use this UART for communicating with the ESP8266. The right connections are TX-RX, RX-TX. You can use any baud rate that's supported by both devices (9600 - 921600).
If your Arduino doesn't have an extra hardware UART, you'll have to use the UART on pins 0 and 1, that's used for programming, and you'll have to disconnect the ESP8266 every time you upload new firmware to the Arduino.
Alternatively, you can use SoftwareSerial. Keep in mind that this is far from an optimal solution, as it uses a lot of resources, it is very slow, and data might get corrupted if you spend a lot of time in interrupts on the Arduino.
To use the ESP8266 with SoftwareSerial, you need to lower the baud rate to 9600 baud. To do this, first upload an empty sketch (bare minimum) to the Arduino to make sure that the hardware UART is not used. Then connect the ESP8266 to pins 0 and 1: TX-TX, RX-RX.
Open the Serial Monitor from the Arduino IDE, and select the baud rate that the ESP8266 is currently operating at. (This is probably 115200, but it could be something else.) Select "Both NL + CR" as the line ending, and send "AT" (without the quotes) to verify that it is working. If everything works, it should answer with "OK". If it doesn't, check your hardware, or try a different baud rate. Finally, send "AT+UART_DEF=9600,8,1,0,0" to set the baud rate to 9600 baud. Then change the baud rate of the serial monitor to 9600 as well. Send "AT" again to verify that it is working.
Now you can connect the ESP8266 to the SoftwareSerial pins, using a baud rate of 9600 baud.
Edit: The WebSocket protocol is not supported using AT commands, so you have no other choice but to program the ESP8266 directly.

WiFi Link firmware and library https://github.com/jandrassy/arduino-library-wifilink/blob/master/README.md

you can use websockets vith WiFi Link library WiFiClient object

btw: WiFi Link firmware is a sketch for the esp8266

Wow, thank you botch soo much for that detailed answer, I will look into it, and am optimistic. Thanks for being patient, it is appreciated!


text:
Blink without delay for 5 times every 20 seconds
I'm trying to write a blink without delay code that will wait 20 seconds, then blink 5 times, then wait another 20 seconds - rinse and repeat.
Here's the minimal code I wrote:
if (currentTime % 20000 == 0) {
  for (int x = 0; x <= 5; x++) {
    if (currentTime % 500 == 0) {
      if (solenoid == LOW) {
        solenoid = HIGH;
      }   else {
        solenoid = LOW;
      }
      digitalWrite(solenoidpin, solenoid);
    }
  }
}
}

All this seems to do is set solenoid to HIGH and keep it there. If I get rid of the for loop and the second if statement, I can get it to switch between low and high every 20 seconds, but adding the if and for loops seems to kill it. Any thoughts on how to make this work?

Why are you executing it in a for loop 6 times? If currentTime % 500 == 0 is true, it will flip the solenoid state 6 times (i.e., not change it).

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

By comparing the result of the modulo operation on a micros() value, you will only "trigger" if you happen to approach each if statement on exactly the microsecond boundary. Depending on your other code, you may find that the Arduino doesn't get around to your if statements on every sequential millisecond, and so you may miss some triggers. Better to do the subtract-and-compare operation that the BlinkWithoutDelay actually uses. That way, your if will trigger, even if you happened to miss the time by one millisecond.

That code just flips the solenoid really fast for a milisecond, then repeats it in 20 seconds. The for loop and the second if are pointless. In the for loop the variable currentTime doesn't change and the second if is always true because 20000 is divisible by 500.

Here is a solution:
void setup()
{
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);
}

#define INTERVAL 20000L
#define BLINK_TIMES 5
void loop()
{
    static unsigned long lastBlink = 0;
    static int count = 0;

    unsigned long now = millis();

    if(count > 0) {
        count -= blink();
        lastBlink = now;
    } else {
        if(now - lastBlink >= INTERVAL) {
            count = BLINK_TIMES;
        }
    }
}

/*
 * Do one blink.
 * Return 1 when blink is done.
 */
int blink()
{
  static unsigned long lastFlip = 0;
  static int count = 0;
  bool last = false;

  unsigned long now = millis();

  if(now - lastFlip >= 500) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    Serial.print(now / 1000); Serial.print(". "); Serial.println("blink");
    lastFlip = now;
    count++;
    if (count == 2) {
      count = 0;
      last = true;
      }
   }

   return (last) ? 1 : 0 ;
}

The count variable controls when to blink and how many times. While it's zero, no blinking.
When not blinking, it keeps comparing actual time with the last time it blinked. When the time exceed 20s, it puts count to five, and in the next loop, the blinking start.
Variables are declared static so they keep their values between loop executions.

Since the last blink will end with a 500ms delay, the wait-time of 20 seconds, will become 20.5 seconds (-:

@jsotola. My bad. I correct my answer.

@Gerben. Check the new answer without delays.

// assuming blinking is 500ms ON, 500ms OFF, so 4500ms for 5 blinks.

int tick = (currentTime/500) % 49;
// if one tick is 500ms, that means,
//    1 tick ON, 1 tick OFF, 1 tick ON, ... , 1 tick ON, 40 ticks OFF (for a total of 49 ticks)
if( ( tick < 5*2 ) && ( tick%2==0 ) )// only turn ON the led on the first 10 ticks (5 ON; 5 OFF)
                                     //  and only if the number of ticks is ODD
    digitalWrite(solenoidpin, HIGH);
else
    digitalWrite(solenoidpin, LOW);

What I did was convert the milliseconds in to ticks of 500 ms. Then based on the tick value, update the led.
PS I tested it on a Arduino Pro Mini

converting elapsed time to tick makes all kinds of sense. ... it is so easy to expand the number of controlled pins ... you could use lookup tables to make complex timing patterns like in a drum machine

This is smart. But note that: 1. The division and modulo operators are computationally expensive, although tick%2 would be cheap if tick was unsigned. 2. The formula for tick is ill-behaved when millis() rolls over. Both issues could be fixed by updating tick within a if (millis() - lastMillis > 500) { ... } construct.

source: Stack Exchange

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

sort: votes


text:
Controlling multiple solenoids with arduino
I was wondering how I could connect multiple 12v solenoids (more than the 53 allowed on mega because of the pins) on the Arduino Mega 2560 to get it to control the keys on a piano/keyboard/organ. Would 74HC595 shift register work for it with the 12v? (Many of them) Because there are so many high voltage solenoids is it possible to control a few of them at a time? I was wondering if someone has a link to somewhere that I could refer to. Thanks

you could also use a 74HCT259 or a PCF8574 to expand the number of pins

Arduino I/O pins, and the output pins of 74HC595 shift registers are logic-level outputs, and are not intended to drive power-hungry items like solenoids. In either case (direct I/O or shift registers) you need to use the logic signal from the output pin to drive something else that switches the 12V source.
That something else can be a MOSFET or a relay, though often even relay coils are themselves driven by a MOSFET or other transistor that is switched by a microcontroller output pin.
One of the many search results that describe this is at http://hades.mech.northwestern.edu/index.php/Driving_using_a_single_MOSFET

Ok thanks for the link and explanation - it'll help with the project!

the shift register has 2 features that will help you:

a latch pin. When a the storage register pin is kept low the outputs won't change this allows you to shift in a new value without perturbing the outputs.
a Qh' output this is the output from the last bit that bypasses the normal output. If you connect that to the next shift register you can daisy chain several registers.

The outputs of the chip are not meant to driver significant currents. Instead use them to drive a mosfet that in turn drives the relay. There are boards that contain all the support circuitry needed to drive relays using low power signals.

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


text:
Getting better results from DHT22
I am working on a dew point sensor, and I am using the Arduino Uno board with the DHT22 sensor. I have it taking a reading once ever 2 seconds and I am using the DHT.h library.
The problem I am having is when I compare the values to our standard here the Humidity reads high and the Temp reads low. Is there anyway to get the values to read closer to what the standard is?

personal opinion - use a better sensor ... my DHT reads humidity low (very low in fact) and temperature high ... so opposite to your problem. I've had better success with the BME280, or a DS18B20 for temperature plus a HopeRF HH10D for Humidity

calibrate the sensors

See this article which includes a section about calibration. https://www.allaboutcircuits.com/projects/how-to-check-and-calibrate-a-humidity-sensor/

Thanks for the answers, there were kind of what I was expecting.

Using a RH and Temp Calibrator I had access to I was able to get better results by all lines to adjust the RH and Temp to a better value. Basically a correction equation.

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


text:
Using different ADC channels
How could the same code be used with different ADC channels?
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 100;

volatile int resultsV [MAX_RESULTS];
volatile int resultsI [MAX_RESULTS];

volatile int resultNumber;

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 338;
  OCR1B = 338;   // 39 = 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering
}

// ADC complete ISR
ISR (ADC_vect)
{
  resultsV[resultNumber++] = ADC;

  //resultsI[resultNumber++] = ADC;

  if (resultNumber == MAX_RESULTS)
  {
    ADCSRA = 0;  // turn off ADC
  }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
  { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.print( resultsV);
    Serial.print("   ");
    Serial.print( resultsI);
    Serial.println();
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF) | bit (ADPS2) | bit (ADATE);
  // turn ADC back on
}

To use a different channel you'd change ADMUX.  See the datasheet to determine what it should be.

From what I understand, you want to read two ADC channels
simultaneously. First, you have to understand that you cannot read them
exactly at the same time, as you have a single ADC. What you can do,
however, is read them one after the other: you read the V channel, then
the I channel, then the V channel again, etc. This means you will have
to change the multiplexer setting (the ADMUX register) in between the
readings. The most convenient place to do this is within the ADC ISR,
the logic of which becomes:

Save the value that has just been read
switch the multiplexer to the other channel
turn off the ADC if you are done.

Example code (not tested):
const byte PIN_V = 0;  // A0
const byte PIN_I = 1;  // A1

// ADC complete ISR.
ISR(ADC_vect)
{
    if (ADMUX & 7 == PIN_V) {
        // We have just read the V channel.
        // Save the value and switch to the I channel.
        resultsV[resultNumber] = ADC;
        ADMUX = bit(REFS0) | PIN_I;
    } else {
        // Otherwise we completed a (V, I) pair, we can increment
        // resultNumber.
        resultsI[resultNumber++] = ADC;
        ADMUX = bit(REFS0) | PIN_V;
    }

    // Turn off the ADC when done.
    if (resultNumber == MAX_RESULTS)
        ADCSRA = 0;
}

Note that this example assumes you do the readings in the (V, I) order.
Thus, within setup(), you have to initialize the multiplexer for the V
channel, as in
ADMUX = bit(REFS0) | PIN_V;


text:
Communication between Arduino Uno and Mega
I am working on a project which uses a set of sensors (HC-SR04). These sensors use pins 2 to 13 of the Arduino Uno. Here you can find the board:
.
I also want to add an MP3 shield (VS1053B) to it and it fills all the pins on Arduino. So I decided to add an Arduino Mega and add the sensors to it and use the Arduino Uno and MP3 shield. The problem is with connecting these two Arduinos. As I said the MP3 shield fills A4 and A5 pins too, so I can not use them to communicate with the Mega. What other options do I have?

the MP3 shield you linked doesn't use A4 and A5

and perhaps it can be used on Mega with changed pin mapping

@Juraj but it fills all pins when I put it on Arduino,

@Juraj actually I am thinking about using only MEGA, But I have no idea about changing pin mapping

the SPI pins should the shield connected over the ICSP header. it is on the same place on Uno and Mega. the helper pins are then connect to other gpio pin numbers on Mega.

all pins will be the same if the shield uses the ICSP header for SPI comunication

if you have the usual stackable shield headers on the shield, the you can connect to pins not used by the shield

@Juraj I noticed that the shield uses ICSP pins but It also uses A4 and A5 In its wiki it says:D11, D12 and D13 are the MISO, MOSI and SCLK buses of the SPI interface by default.

nothing about A4 and A5 in wiki. Yes, D11, D12 and D13 are SPI connected to D labeled pins and to ICSP header.

You can multiplex the trigger line. With 3 pins you can address up to 8 sensors. If you multiplex the reply line as well (so you can abstract out the latency) you only need 2 additional pins for the actual trigger and reply.

So I do not need Adruino mega anymore? Can you give me a link about multiplexing the trigger line?sorry I am new to adruino

Salam, you could somewhat multiplex the HC-SR04 Ultrasonic Sensor by using I2C(IIC) instruction on how to convert those into I2C and by using OctoSonar library can be found here so that only the SDA(pin16) and SCL(pin17) pins on your Arduino UNO will be used.
https://hackaday.io/project/19950-hc-sr04-i2c-octopus-octosonar


text:
client.connect() problem
I'm using XAMPP(version-7.2.1) server in my PC to publish my arduino sensor data in a webpage. I have tried the code above and it shows an error like:

Ethernet configured via DHCP
Connecting...
-->connection failed

I have also followed the steps given in this https://forum.arduino.cc/index.php?topic=40448.0 but it doesn't work.
The code runs till client.connect() after that it doesn't get inside the if(client.connect(server,80)) loop.
The arduino's ethernet shield is assigned an IP by the PC via ICS.
I believe that the problem is in connecting the arduino to the localhost but I don't know how to resolve it. The XAMPP server seems to run properly. I have checked it logs.
I have also posted at https://forum.arduino.cc/index.php?topic=525947.0.
Hope someone can help me
Thanks in advance

#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
DHT dht;
const int sensor_pin = A1;
unsigned int ldr;
byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 33);
char server[] = "192.168.1.7"; // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie. "www.yourwebpage.com")
EthernetClient client;

void setup() {
  Serial.begin(9600); // Serial.begin starts the serial connection between
  computer and Arduino
  Ethernet.begin(mac, ip);
  Serial.println("Ethernet configured via DHCP");
  delay(1000);
  dht.setup(2);
}

void loop() {
  delay(dht.getMinimumSamplingPeriod());  /* Delay of amount equal to sampling period */
  float soilmoisture;
  int sensor_analog;
  sensor_analog = analogRead(sensor_pin);
  soilmoisture = ( 100 - ( (sensor_analog / 1023.00) * 100 ) );
  float temperature = dht.getTemperature();
  float humidity = dht.getHumidity();
  ldr = analogRead(A0);

  Serial.println("Connecting...");
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("--> Connected");
    client.print("GET /write_data.php?"); // This
    client.print("temperature="); // This
    client.print(temperature); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.print("&humidity="); // This
    client.print(humidity); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.print("&soilmoisture="); // This
    client.print(soilmoisture); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.1.7"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println( "Content-Type: application/x-www-form-urlencoded" );
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
  }
  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  client.flush();
  client.stop();
  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

My PHP code is as follows:
<?php
// Prepare variables for database connection
$dbusername = "x";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "y";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
$dbname = "arduinotest1";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword,$dbname);
if (!$dbconnect) {
    die("Database connection failed: " . mysqli_connect_error());
}
$dbselect = mysqli_select_db($dbconnect, "arduinotest1");
if (!$dbselect) {
    die("Database selection failed: " . mysqli_connect_error());
}
// Prepare the SQL statement
$sql = "INSERT INTO arduinotest1.tabletest2 (temperature,humidity,soilmoisture) VALUES ('".$_GET["temperature"]."','".$_GET["humidity"]."','".$_GET["soilmoisture"]."')";
// Execute SQL statement
mysqli_query($dbconnect,$sql);
?>

How do you know till where it runs? What output does it produce? What have you tried to debug? Why do you stop the client twice?

Also asked at: http://forum.arduino.cc/index.php?topic=525947 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

try to change ip to 127.0.0.1?
maybe try NAT at your router.

Have you prove disconnecting your firewall protection? It works for me.

As far as I can see, when you call client.connect(server, 80), you call it with char[] variable that holds char server[] = "192.168.1.7". And from library code it seems that it will call function with those parameters which will try to resolve dns but can't do it and returns 0.
It calls: int EthernetClient::connect(const char * host, uint16_t port)
,when it should call: int EthernetClient::connect(IPAddress ip, uint16_t port)
Source code: https://github.com/arduino-libraries/Ethernet/blob/master/src/EthernetClient.cpp
So you need to change char server[] = "192.168.1.7"; to IPAddress server(192,168,1,7);
That way it will call the right connection -function and wont get stuck with dns.
Edit: added details

Check the server ip is correct and server is running. Then check the return value of client.connect() function. If it's a 0 then most likely your server is behind a firewall. If so, unblock the apache server to pass through it. I had this similar issue with wamp.
Although 0 is not a valid return code for client.connect() according to http://www.arduino.cc/en/Reference/ClientConnect , it weirdly returns a 0. Oherwise it will give you a clue.
Also use IPAddress class for assigning the server address instead of using char [].


text:
Confusion over Transistors for a switching circuit with an Arduino Mega 2560
Apologies if this is a stupid question asked by a noob, but I've looked around to try and find the answer and just can't work it out.
Basically, I'm making a project on thingiverse (Glitch's MK2 Stargate), and I've tried all sorts of different transistors with my circuit, I just can't get it to work properly.
Could you please advise which Transistor would work for the following circuit:

It's a basic thing, but the plan I was originally working from on thingiverse called for BC548BU transistors, however, the LEDs they were using were surface mount, and I am trying the same thing with 3mm standard LEDs. The BC548BU didn't work right on the normal LEDs.
I'm a total noob with this, but I've been trying to match the Base pin on the Transistor voltage output of my Arduino, but not sure if I'm doing the right thing. Can anybody help?
Thanks
-Dave
p.s. I have a load of transistors already (listed below), if any of these work, that would be great, if not, I will order the correct ones. The only one that seemed to match Data with the BC548 is the S9014, but it didn't seem to work at all, unless my understanding of the wiring of Transistors needs adjustment.

do you have ground of the arduino connected to anywhere in the circuit?

Not to the LED circuit no, just through its own PSU's ground. Should I be grounding it like that?

I thought the issue might be that my Mega 2560 is 3.3V on the digital, but the 584 is 5V base. The original circuit was for the Uno.

You cannot create the required voltage difference between base and emitter for switching when there is only a single electrical connection on the entire circuit.

But aren't the digital pins outputs? i.e, it gives the base 5V from the Arduino which then 'turns the switch' on the transistor which then turns the LED circuit on. I'm not saying you're wrong obviously, just trying to get an understanding.

Don't forget to add a resistor between the digital pin, and the transistor.

Thankyou, I am working it all out now, I've never done electronics like this before - as you can probably tell.

A transistor amplifies current, not voltage.
The first thing to check is the current of your LEDs. In your current configuration, it is between 25 and 30 mA. This is too high for most LEDs. Check the datasheet of your LEDs for the actual forward voltage, and current rating.
To calculate the value for the resistor in your circuit, use Kirchhoff's and Ohm's laws. According to Kirchhoff: VResistor + 3 VLED = 12 V. Let's assume that the LED's forward voltage drop VLED = 1.8 V. This means that VResistor = 12 V - 3 VLED = 6.6 V. Ohm's law will then tell you the relationship between the voltage across the resistor and the current through it: R = VResistor / I. The current through the resistor is the same as the current through the LEDs. Let's assume that this is 20 mA. Therefore: R = VResistor / I = 6.6 V / 0.020 A = 330 Ω.
The next thing to calculate is the resistor between the Arduino and the base of the transistor. As mentioned before: the voltage on the base does not matter, the current does. You want to use the transistor as a switch, so you have to drive it into saturation. As a general rule of thumb, you want the base current to be a tenth of the collector current in that case: IBase = ICollector / 10. The current through the collector is the same as the current through the LEDs, so IBase = 20 mA / 10 = 2 mA.
In a similar way as before, we can calculate the base resistor: VResistor + VBase-Emitter = VArduino. The voltage of the Arduino pin is most likely 5 V, and the Base-Emitter voltage of a silicon transistor is around 700 mV (look it up in the datasheet): VResistor = 5 V - 0.7 V = 4.3 V. Then use Ohm's law again to calculate the resistor value: RBase = VResistor / IBase = 4.3 V / 0.002 A = 2150 Ω ≈ 2.2 kΩ.
The current has to flow through the base to the emitter. For current to flow, you need at least two connections: current flows from the Arduino pin, through the transistor, to ground. You have to connect the emitter of the transistor to the Arduino's ground.
You can use pretty much any normal transistor that has a maximum collector current that is larger than the LED current, and a maximum collector-emitter voltage greater than your power supply.

I used https://www.kitronik.co.uk/blog/led-resistor-value-calculator/ to get the resistor value, and I've just double checked and it tells me that 3 in series, powered by a 12V power supply would need a 220Ohm resistor in line.
I will look into the calculations that you've sent to try and work it all out. Thankyou for your response.

@DavidRobilliard: the calculator you used is for LEDs in parallel, you have your LEDs in series. Running LEDs in parallel on a single resistor is not recommended.

Hi, I have tried it on http://led.linear1.org/led.wiz and it agrees with you about a 330Ohm, my mistake, sorry.


text:
Can I remove soldered atmega328P from arduino board, using hot air gun, without damaging it?
I need to remove atmega328P from arduino board and the best tool what comes up to my mind is a hot air gun. What is the maximum temperature that atmega328P can withstand?

A decorating style hot air gun? No, definitely not. You need a proper reflow station, or you will end up melting everything.

The SMD version or the DIP version? The DIP can be desoldered, one pin at a time, with e.g. a solder-sucker/solder-pump. I've desoldered SMD chips by putting the entire board into a (old) pan, an heating it on a furnace. Crude, but works when in a pinch.

new boards are under $5, is an hour or two of time for an uncertain outcome worth it?

This really seems like it would be more appropriate on [electronics.se].

You are likely to damage the connectors and displace small surface mount components before you damage the chip.  A heat gun would not be recommended if you want to preserve the board, but it could with skill be used to salvage the chip.  For a DIP package you should heat from the underside, and that can be an option for surface mount as well.

web search reveals the peak reflow temperature is 260°C
the chip will withstand that for 15 seconds or so
here is an example graph of a reflow oven temperature during the reflow process

This is of course a specification under which the manufacturer is willing to say the chip will work.  Often for personal/experimental use things far, far worse are survivable.

@Kirill there is no practical guidance here.  Oven reflow and hot air rework are very different operations and it's all but certain that anyone using a temperature controlled hot air station would set it notably higher than this implies.   So it's sad to see you pick this as an answer.

The idea of using a simple "heat gun" (such as this) will fail on two fronts:

You can't control the temperature. It will get too hot and you will damage the chip.
You can't control the hot air. It will melt all the plastic items on  the board (the connectors, etc) and you'll just end up with a big blob of bubbling plastic.

You need a proper reflow station. These are to a heat gun what a soldering iron is to a blow torch. They are temperature controlled, so you can select a specific temperature (with reference to the datasheet of the component you want to (de)solder), and have interchangeable nozzles to allow you to accurately direct the heat where it is needed.
I use the (cheap) Atten 858D+.

Actually, you can control the temperature with either a heat gun or a blow torch, by controlling distance and time.  Both have a long tradition for salvaging ICs for hobby re-use off boards to be scrapped (especially in the DIP era), but yes, damage to plastic connectors is probable, and with a torch, the PCB substrate as well.  Also vile smoke.

@ChrisStratton You can't control the heat accurately. There is no feedback, other than "it feels too hot" - and you can't really tell the difference between 200C and 400C and still keep the skin on your hand.

Untrue.  You know it's hot enough when the chip you've been lightly pulling on comes out.  You also see the solder change appearance, and quickly learn other ways of judging - just as you do when using a precision hot air tool.  Doing it from the reverse side of the board also simplifies things greatly, since you get the board and the pins which need to be hot, hot faster than the package.

@ChrisStratton And all the other components fall off too, or blow off because there's far too much air being blown, and the connectors all turn to syrup. While it is possible, on some boards, and with plenty of practice, to use a decorating heat gun, in general it's a really bad idea.

As said right at the beginning, it's often useful for salvaging chips at the cost of the board.

@ChrisStratton You can do the same putting the board upside down in the oven and whacking the temperature right up. There is, of course, a higher chance you will kill the chip by using such crude tools as these.

The ATMega328P comes in 2 packages. DIP(Dual Inline Package) and SMD(Surface Mount Device)
The Hot Air Gun method is only best applicable to the SMD version. I would recommend you to not focus on what temperature the board can withstand, but try to practice on the hot air soldering techniques.
First try to practice removing SMD components on a separate PCB so you can be familiar with the hand movements and the techniques in safely removing SMD components. When you are familiar enough with the hand movements and techniques, then that is the best time to work on your Arduino Board.
After doing this you should be able to remove and SMD components from any type of circuit boards.
PS. Be sure to use a lot of soldering paste when using hotair reflow ;)

Actually, in some ways a heat gun is more applicable to a DIP, and that's one of the few cases I might use one rather than a precision hot air tool.  The cost of likely damage to the rest of the board.

Thats correct. if the DIP is soldered on the board and has many more than 4pins, then the heat gun will come in handy. Still each person has its own way/learned technique by practice to remove components using different tools :)


text:
Call by reference
I am trying to learn 'call by reference'. I want to call a function fcn1 from the main loop and pass a reference of the local variable var to the function fcn1. Next step is to call a second function fcn2 from the function fcn1 and pass again the reference of the local loop variable var. I always get this error massage:
invalid conversion from 'int' to 'int*' [-fpermissive]

Here a small example code:
void fcn1(int *variable)
{
  fcn2(&variable);
}

void fcn2(int *variable)
{
  //do something with the variable
}

void setup()
{

}

void loop()
{
  int var = 1000;
  fcn1(&var);
}

I tried to solve that issue by using:
void fcn1(int *variable)
{
  fcn2(*variable);
}

But it's the same error.
By deleting the * respectively & it works fine, but is it still a reference?

Thanks a lot! If I interpret your answer and the link correctly, the following code works only with references, right? void fcn1(int &variable) { variable++; fcn2(variable); } void fcn2(int &variable) { Serial.println(variable); } void setup() { Serial.begin(9600); } void loop() { static int var = 1000; fcn1(var); delay(1000); } Many thanks!

Yes, however, it will not compile that way .. int & variable denotes a pointer, to increase it, you should use variable++.

void fcn1(int *variable)
{
  fcn2(*variable);
}

This function takes a pointer to an integer as parameter, and then passes the value of the integer to the second function.
To do it by reference, use an ampersand (&, not to be confused with the address-of operator).
void fcn1(int &variable) {
  // Do something to variable
}

For example:
void increment(int &variable) { // Reference to an integer
  variable++;
}
void setup() {
  Serial.begin(115200);
  int a = 1;
  Serial.println(a); // 1
  increment(a);
  Serial.println(a); // 2
}
void loop() {}

You could achieve the same thing using pointers, but using references is much cleaner and easier to read.
void increment(int *variable) { // Pointer to an integer
  ++*variable; // dereference first, then increment value
}
void setup() {
  Serial.begin(115200);
  int a = 1;
  Serial.println(a); // 1
  increment(&a); // address of a
  Serial.println(a); // 2
}
void loop() {}

Please note: this question is not specific to Arduino, it is just C++. For questions like this, it is best to google for 'C++ pass by reference' instead of 'Arduino pass by reference'.


text:
Is it common that Uno clones misbehave when connected to 12v on VIN?
Edit: this was completely my mistake. See end.
My official Uno worked fine when powered by 12v on VIN, but my Uno clone acted really funny--it read random noise from an input when a simple wire was attached, but not with no wire. It was solved with a pulldown resistor. The worse problem was that the PWM didn't turn off when I called analogWrite(pin, 0). More worrying, it seemed to be outputting by power rather than duty cycle, since my small LED strip seemed to be doing higher duty than my big LED strip (both powered by transistors), though both were being set with analogWrite(pin, 0). I measured the 5v pin at 5.9v. The input voltage may have actually been up to 12.5 v, but clean. I disconnected VIN and hooked back up to USB, and everything worked fine.
I assume the solution is to either use a linear regulator wired to VIN, or a battery?

I did get the linear regulator, which didn't help. I finally checked all my voltages, and found there was a 0.8 volt difference between different grounds!  It turned out my breadboard was wired to the Arduino pin next to ground, instead of ground itself. I feel very lucky not to have ruined the board, and my only complaint is that the pins aren't labeled clearly as they are on my official Arduino. On the other hand, I wouldn't have been able to debug this as easily on the official Arduino, since the clone has lovely solder holes at each pin which are a great spot to stick a voltmeter probe.

you connected the uno clone to 12V without reading the specs for the board?

It may be naive of me, but I wasn't aware cheap clones had specs, at least specs that are in English. I thought they were supposed to work like the official ones, but with less reliable construction and components. Various internet sites indicate that clones max out at 12v while Arduino will handle 20v in a pinch, but I didn't think 12.3v (probably) would be over some hard limit.

the solution is to either use a linear regulator wired to VIN, or a battery - or stop using cheap chinese knock offs - I mean, clones :p

@JaromandaX You highlighted "cheap". Do you mean it's possible to find high quality knockoffs?

Clones. Yes off course

@JaromandaX I'd better ask a separate question about that. Are clones highly frowned upon in this forum? I live an hour from China, so I don't consider this to be an ethical issue like it might be for someone in the US or Italy. I mean, Arduino isn't marketed or priced for my demographic.

I'm not saying all chinese clones are poor quality either

I don't think there are any issues with discussing clones. This isn't the official Arduino website, and even there they have quite a lot of questions about clones, or indeed "home-made" boards which technically are nothing to do with Arduino, except that they might have an Atmega328P processor on them.

Have you tried to use INPUT_PULLUP mode on input pins? The CMOS circuits are basically high input impedance amplifiers and it catches all kinds of EMI.

@KIIV Thank you, is INPUT_PULLUP considered a best practice for using switches? That would save me a component. But it seems unlikely I would want a pulldown resistor on the base of an NPN transistor, right? The bad PWM output (going into the transistor bases) makes me think the board is going haywire, one step away from giving up the ghost.

For switches it's sufficient (maybe in environment with high interferences you'll have to use lower impedance). For driving NPN Base the OUTPUT mode is used and you have to use current limiting resistor (usualy about 1k).

i frown on using name-brand boards, but that's me; i like my money in my pocket.

Is it common that Uno clones misbehave when connected to 12v on VIN

Whether it is "common" is probably unanswerable unless you do some sort of survey.
However bear in mind that clones or "knock off" boards (some of which pretend to be official ones) are built to a price. The original Arduino was already designed to be cheap. To make them even cheaper the manufacturers may well make a number of compromises. For example, some use a cheaper USB interface chip. It wouldn't surprise me if the components like the voltage regulator, capacitors, etc. are under-specified.
I see from eBay that clones are already quite cheap, possibly around $US 4.50. To compete with that, some manufacturers may be cutting back even further on the quality of components.

I assume the solution is to either use a linear regulator wired to VIN, or a battery?

You are probably better off bypassing the on-board regulator entirely. Get a wall-wart that outputs 5V regulated. The sort of thing that might power a USB-based device. Then plug that into the 5V pin of the Uno (not VIN). In fact, virtually any mobile phone charger wall-wart will output exactly what you want. Just run a USB cable from that to the USB port on the Arduino, and there you have it! Regulated 5V power.

The other thing that could work would be to give the voltage regulator a break. Don't put 12V into it, put in 9V. Then it doesn't have to work so hard (that is, dissipate the extra voltage as heat).

I'm just outside of China, so these clones were $2.70. They weren't even the cheapest I could have bought.
A wall wart is the worst and last option--this project has a fixed location, and it would mean running an additional long power cord to it. However, I should be able to get a linear regulator to output 5V from the (required) 12V that's being supplied.
I'm also thinking about making a voltage divider--the fluctuation shouldn't be that bad if I let 500 mA flow through the divider with no load. But please let me know if this is a bad idea.

To clarify, if I use a voltage divider, I would be supplying 9 V to VIN (letting the Arduino take care of fluctuation), but if I use a linear regulator, I'll apply 5 V to the 5V jack (assuming there is no fluctuation).

@piojo: The issue with the divider is that the voltage you get is highly dependent on the current you draw. Depending on what the Arduino is doing, the current draw can vary quite a bit.

Check out my post about a temperature sensor that runs from batteries. There are much better ways than trying to put 12V into VIN.

@NickGammon That mosfet technique is really interesting! As for my original post, I edited it to explain that the board wasn't the problem. I wired ground to a floating pin (next to GND) instead of GND. So the problem is between keyboard and chair, unless you blame the board manufacturer for labeling that's not as good as the labels on an official Arduino.

Some of the labelling on alternate boards is almost impossible to read (for me). I thought that was just my eyes. :)


text:
How to create custom bootloader with accompanying program loader for ATMega2560
Just for some context, I have created a custom board based on the ATMega2560. I currently have the original Arduino Bootloader for the ATMega2560 and have no problems uploading code via the USB Port on TX0 and RX0.
What I am hoping to achieve is creating a custom Bootloader that allows me to upload my .hex binaries to flash but in a proprietary way, so that any program cannot be uploaded to it with the standard Wiring Protocol used by Arduino IDE. In addition, I will need a custom PC based program that can upload the code via the USB port.
The reason why I need this is that I will have this device out in areas where I would not want someone taking the device and uploading their own program to it and screw it up. I know it sounds paranoid, however, it would be preferred to have this feature so I can update the firmware via the USB Port without using the Wiring protocol.
Has anyone accomplished this before?
TL;DR
Want to upload custom Bootloader to Arduino Mega so that I can upload my firmware with a proprietary programmer via the USB Port on TX0 and RX0 because I am paranoid.

The source of the bootloaders is publicly available, so a simple thing would be to make a minor modification, for example XOR each incoming byte with 0xEE. That would mean the bootloader wouldn't work with normal uploading programs (the IDE) but with a modified uploader.
However even simpler would be to upload your code using ICSP and not include a bootloader at all. Or, leave the bootloader there but turn off the BOOTRST fuse so that the processor ignores it.
That way, it takes some effort for people to replace your code.


text:
Connecting Load combinator to HX711 then to Arduino
i'm currently a student and my project is to create a weighing scale using 50kg load sensors (x4) with HX711 amplifiers, load combinator and Arduino UNO. I've connected the load combinator and HX711 based on the picture below:

I'm wondering after this connection, how do i connect it to the pins of Arduino UNO and does anyone know the codes to make the load sensors work? Because currently i keep getting 0kg as the final value as well as the offset value.

How have you connected it to the Arduino? What code are you running? How are the rest of the pins on the bridge board wired?

part of your school learning is how to do research. ... i do not think that research is asking someone to give you the answer.

To be able to wire load sensors up you first need to understand how they work and what the wires on them actually mean. There are no standards as regards colour coding of the wires.
So step one is to find out the colour coding of your load cells. Assuming they are "normal" cheap 3-wire ones, internally they look like:

simulate this circuit – Schematic created using CircuitLab
You need to identify those wires on your cells.  We'll call them +, C and - (in that order) from now on.
The idea is that you provide power between + and - and a varying voltage comes out of C depending on the load applied. More load means a lower voltage, since R1 and R2 form a simple potential divider.
However that's not enough to get good results - the voltage differences are too small. So they are usually used as part of a Wheatstone Bridge. This allows a much smaller voltage variance to be detected.
The Wheatstone Bridge is created by the combinator board. It does it by combining the individual parts of separate cells together to form just two load cells along with the static resistances.  This is the form the Wheatstone Bridge create takes:

simulate this circuit
I have boxed in each load cell so you can see how two "variable" legs combine into a single variable resistance, and two "static" legs combine into a single static resistance.
Now you can see how you could test the combinator to make sure it's giving proper results. Apply a voltage between E+ and E- (say 5V) and measure the voltage between A+ and A-. Apply pressure to the load cells (all of them at once) and observe a change in the voltage between A+ and A-.
Assuming that is showing good results (the voltage change will be quite small, so set your DMM to its most sensitive setting), your next point of call is the connection to the Arduino itself.
The HX711 uses a digital serial protocol. Sparkfun has software that bit-bangs that protocol over any pair of IO pins you choose. There is nothing special about which pins are chosen - any two can be used. So as long as you have +5V, GND and the two data pins connected up to the Arduino there's not much that can go wrong.
So that then leaves the software.  The biggest mistake people often make is to not tell the software which pins are being used for the serial communication. Or telling it the wrong pins - getting the clock and data pins mixed up, for instance.  This would be the first port of call for checking the software. Make sure you have the right pins specified.  Quite how you do that without seeing your software I can't say, but Sparkfun have some example software (scroll down to the bottom of the page) which just uses a pair of #define macros to specify the pins.

Those cheap load cells are half-bridges.  The glued-on strain gauge has a patch with two variable resistor-strain gauges on the center bar of the disk.  Much like https://www.omega.com/en-us/force-strain-measurement/strain-gauges/dual-parallel-strain-gauges/p/SGT-Half-Bridge-Uniaxial   When the disk is supported on the ring, and loaded on the rivets on the E in the OP's pics, the center bar bends like a sigmoid function, one gauge compresses, and one gauge extends. They match resistances of the gauges by printing them w/same technology. R1,3,7,8 aren't constant, but vary opposite R2,4,5,6

thank you for your help to my question and sorry i was not being specific enough.
Initially the connection of the weighing scale was based on this:

However, after much research, i've decided to give the load combinator a try and use it to connect all the 4 load sensors to form a Wheatstone Bridge that will then connect to the Arduino. So basically, the load combinator is just another add on component.
As for my codes, this is how it looks like:
#include <hx711.h>
#define DOUT 3
#define CLK 2

Hx711 scale(3,2);

int count=0;

float sum=0;
float value;
float avg=0;
float offset;
float toffset;

int count2;

float V;
float VT;
float total;
int t;
float foffset;

void setup()
{
  Serial.begin(9600);
  Serial.println("HX711 Test");
}

void loop()
{
  for(count=0;count<10;count++)
  {
    value = (scale.getGram()*0.07);
    sum = sum + value;
  }
        toffset = +(sum / 10);
         Serial.print("Offset: ");
        Serial.print(toffset, 1);
        Serial.println(" kg");

        Serial.println("Please stand on the plate and do not remove both of your legs.");
        delay(4000);

  for(count2=0;count2<10;count2++)
  {
    V= (scale.getGram()*0.07);
    total=total+ V;
  }

  VT=(total/10);
  Serial.print("Average Weight: ");
  Serial.print(VT, 1);
  Serial.println(" kg");

   if(foffset= -toffset)
   {
    Serial.print("Final Weight: ");
    Serial.print(((VT+foffset)*-1), 1);
    Serial.println(" kg");
   }
 else
  {
    if(foffset=toffset)
   {
    Serial.print("Final Weight: ");
    Serial.print((VT-foffset), 1);
    Serial.println(" kg");
   }
 }
 Serial.end();
}

You should not answer your own question with information about your question. You should edit this into your question and delete this answer. I will leave it here for now to give you easy access to it, but it will be deleted soon.


text:
ino.hex vs ino.with_bootloader.hex
I'm working on a Android App able to update the content of my Arduinos. Start to work (reset the Arduino, communicate with STK500 protocol, get id of ATmega and so on).
But I face a question about the two hex files produced by the compiler.
Some FAQ, forum... give replies about the two, explaining: "the ino.hex file has only the code and the other as the code + the code of the bootloader".
After having a look at the hex files, that's true: you can find in the "with_bootloader" the code of the bootloader.
The "why" gives the following answer: "that's because when the bootloader receive the code, it erases the flash so the installed bootloader destroy itself. So if you send without bootloader, you will not have a bootloader any more in the Arduino".
Problems:
1) In that case, in order to change the bootloader why use an ISP? Just add the HEX code of your new bootloader in the main HEX file, send it with AVRDUDE and that's all...
2) When you use the Arduino IDE with AVRDUDE in Verbose mode you'll see AVRDUDE send the file....
without the bootloader!
So the question is: when you want to update the content of the flash, sending "manually" the data using STK500 protocol, do you need to send the "ino.hex" or the "ino.with_bootloader.hex" file? And why?

If flashing with AVR In System Programing (ISP) the bootloader is not needed. Only the flashing over Serial needs a bootloader.
The ISP erases the flash including the bootloader. To be able to use the serial flashing after ISP, the hex with_bootloader can be used.
I flash AVR over WiFi with esp8266's core AVRISP library and I use the hex with_bootloader to have the option of flashing later over USB.
Your Android app will use the serial flashing utilizing the bootloader. The bootloader doesn't delete itself. So you should use the hex WITHOUT bootloader.

Nice answer, coming from one who use and not only copy answer from others. Thanks VERY MUCH!

While flashing the Arduino over USB (UART) you use the bootloader in that case the bootloader doesn't delete itself that's why the Arduino IDE sends the file without the bootloader. You need to use the file with a bootloader only when you are programming using an ISCP programmer and want to keep the ability to flash through USB.


text:
State machine sketch to drive a DC motor with limit switches
I have a DC motor that will need to use two limit switches to detect end of travel in two directions.
I've read that coding a state machine to do this task is the best method, however I have no idea where to even begin.
Below you'll find a fritzing sketch of my experimental configuration for the code once implemented, and a flow chart.

Do you have any code?

You have created a flow chart.  When discussing state machines it is better to use a state diagram.

In this state diagram of a turnstile (from the state machine wikipedia page linked to above) it is observed that the nodes (bubbles) contain the state of the turnstile and on the edges (arrows) is written the condition required to travel in the direction of the arrow to a new state.
For the question asked here, at least 2 nodes are needed to state the direction of the motor.  The edges likely will state which arrow is to be used to travel to a new state based on which switch is open or closed.  Later, consider adding a new state to stop the motor once an end switch is closed. (Hint: Likely, you will need 2 stop nodes.  One for each end-stop switch.  The reason being you will need to know which direction the motor is to turn when restarted.)
For certain cases, adding a momentary contact switch is complex due to the need to mitigate the contact bounce.  This is true when the meaning of activating the switch changes.  The end-stop switch meaning does not change so there is no need to mitigate the contact bounce or "debounce" the end-stop switches.  However, it is assumed the "Cycle Switch" can start the motor spinning in different directions depending on the history of the motor movement.  Therefor the "Cycle Switch" can benefit from a 4 node state machine where there is clearly nodes which output switch-closed and switch-open.  But to get to either of these 2 nodes there needs to be 2 other nodes where the switch "debouncing" is handled.

When handling multiple state machines in one program it is important not to block the flow.  All state machines need to be continuously checked for state chances (testing the edge conditions for traveling from the current node to a new node).
When writing for an Arduino (in C / C++), the code pattern most often used is a "case" statement (switch / case) where a variable is assigned numbers associated with different nodes.  In such a code pattern, each "case" is a node which contains the edge test(s) and can assign a new value to the variable to switch to a new node ("case") if any of the edge tests are true.
Simplifying the design:  If you do not plan on stopping the motor then you do not need to "debounce" the "Cycle Switch".
Here is why: The meaning of the "Cycle Switch" changes from push-to-start to push-to-stop should you want to stop the motor between the 2 stop-switches.  If all you need is to start the motor after either of the stop-switches are closed, then the number of times the "Cycle Switch" bounces is irrelevant as long as the bounces do not continue for longer then it takes for the motor to reach the opposite stop-switch.

Each state in the state machine should be a state in which the arduino will be for a time. Anywhere you would use a delay() or a blocking function or a busy loop will be a state.
You can also use multiple orthogonal statemachines and mix them. For example 1 to control whether the motor needs to be driven at all and one to control which direction it is driven in. That way the motor control part will look like:
if(motorDriven) {
    if(motorDirection = TOP) {
        driveMotorCW();
    } else {
        driveMotorCCW();
    }
} else {
    stopMotor();
}

Then the control of the state machine is straightforward. If limit switch is pressed change motorDirection to the opposite (and maybe stop the motor).
For timing you should keep a timestamp of the start of the interval and then test if millis() - timestamp > interval. For intervals less than a month this will work decently enough (barring drift). For intervals greater than that you should invest in a external clock.


text:
Need to read/send both values of a button push
I'm trying to use a float switch to receive alerts via Blynk when a water level drops, and when it rises again. The code I have been using has been working for when the float drops (button pressed) and I could get it to work when the water comes back up, but it gets stuck in a loop. I'm new to Arduino programming and I'm sure it's some simple error in the way I'm writing/modifying this code...
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "SSID";
char pass[] = "PWD";
int flag=0;
void notifyOnButtonPress()
{
  int isButtonPressed = digitalRead(D1); //assignment here for pin
  if (isButtonPressed==1 && flag==0) {

    Blynk.notify("Alert : Water Level has dropped");
    flag=1;
  }
  else if (isButtonPressed==0 && flag==0)
      Blynk.notify("Alert : Water level has risen");
  {
    flag=0;
  }

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

I believe the problem is in function notifyOnButtonPress.

Is the float connected to a switch on pin D1 such that if the water level drops, lowering the float, the switch connected to pin D1 is turned on and it stays on until the water level rises sufficiently, lifting the float, so that the float turns off the switch connected to pin D1? So the flag variable indicates if a message has been issued that the switch is turned on, low water level, or turned off, high water level?

Correct. The pin is assigned to D1. The water level is normally high. When it drops, the float drops and sends the "on" signal to the board. It remains in this state for around 15 minutes or so, then the water ebbs back up and opens the loop again (switching off). I'm trying to use "Flag" to be able to determine the last state and reset after a cycle of ON/OFF essentially with this switch... or i guess OFF/ON/OFF and repeat.

It seems to me that the saved float level state needs to be initialized to what it's actual current level is rather than just starting it off as 0. That way conditions such as a power outage during which the float level has changed could be detected.
I also changed the text of your notifications, which may or may not be allowed, to more accurately describe the state of the system.
I haven't actually tested this so I would like feedback as to whether it works or not.
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
  }
}

Or I suppose even simpler would be:
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       if (floatLevelLow) {
           Blynk.notify("Alert : Water Level low.");
       } else {
           Blynk.notify("Alert : Water level high");
       }
       floatSavedState = floatLevelLow;
  }
}

Thank you. This gives me a single notification of "Water Level low" when powered up and float is in the HIGH position. Manually adjusting the float after has no effect. This holds true for both examples provided.

@gfuller40 look at your pinMode(D1,INPUT_PULLUP) call. I think that makes pin D1 to be an INPUT pin and is attaching a pullup resistor to it so that if the line attached to the pin is floating, the pin will be pulled up to a HIGH value. I am a bit hazy on it but I am wondering if you have a wiring and setup problem. My impression, which may be wrong, is that the pin will always be HIGH. Could you check the value of the digitalRead(D1) that it returns a value of 1 if the float is pushed down, water level low, and a value of 0 if the float is up, water level high?

Thank you, Richard. I'm only using D1 and GND. This works as it should when i only check to see if the float has dropped in my initial programming
int isButtonPressed = digitalRead(D1);
if (isButtonPressed==1 && flag==0) {
Serial.println("Resevoir Water is Low!");
Blynk.notify("Alert : Resevoir water is Low!");
flag=1;

}
else if (isButtonPressed==0)
{
flag=0;
}
)
but when I add to check the state again (high) is where I've been having trouble. I guess that's the only reason i have to believe it is set up correctly?

@gfuller40 please update your posted question with a wiring schematic showing how you have things wired up. As part of that identify the actual components being used in the wiring. I am not sure what you mean by "only using D1 and GND" and how that wiring is done. You want to make sure that if the water level is low then the pin will definitely see a HIGH or 1 and if the water level is high then the pin will definitely see a LOW or 0. See https://playground.arduino.cc/CommonTopics/PullUpDownResistor or https://www.electronics-tutorials.ws/logic/pull-up-resistor.html

OK. I have a float switch (2 wires) one is connected to the GND pin on on the digital side of the MCU and the other is connected to D1 on the digital side as well. I just ran a test using a very simple function (void notifyOnButtonPress()
{
Serial.println(digitalRead(D1));
}) and I'm  only seeing a value of "1" on the serial monitor (both positions). That explains things.... do i need a 3 wire float or something? or just use two floats?

OK!!! I knohw what is going on... your code is fine, the serial monitor is registering correctly, it's the blynk notifications, it keeps sending them one after the other, is this an issue with the loop?

It has to be something going on here: void setup()
{
// Debug console
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
// Setup notification button on pin D1
pinMode(D1,INPUT_PULLUP);
timer.setInterval(16000L,notifyOnButtonPress);
}
void loop()
{
Blynk.run();
timer.run(); // Initiates BlynkTimer
} Blynk keeps looping and saying the water level is high regardless of the position of the float.

@gfuller40 so I am not sure what your particular float switch looks like and how it operates so details about that would be good. Your Arduino sketch looks similar to the example from Blynk documentation. I really think it is your circuit. See this diagram that goes HIGH when button is pressed or LOW otherwise https://goo.gl/images/QWJftz because when button is pressed, pin is HIGH as power flows to pin and when button is released, pulldown resistor makes sure pin is LOW.

Richard - The code and wiring are fine. The serial monitor is outputting what it should and reflecting what the float switch is doing. The issue is that blynk is sending notifications every few seconds of it's current state when I'm only asking for a single notification of the float as the status of it changes

@gfuller40 is that notification every few seconds from your original code or is it from the code example I provided? Or both?

From the code you provided. I added your new code to the existing and the serial monitor reflects 100% what I'm doing with the float but notifications keep getting pushed.

Change
else if (isButtonPressed==0 && flag==0)
    Blynk.notify("Alert : Water level has risen");

to
else if ((isButtonPressed==0) && (flag==1))
{
    Blynk.notify("Alert : Water level has risen");
}

Otherwise, when flag == 1, it will never revert back to 0.
Also it's best to add brackets, and use parenthesis.
Also, change the variable name flag to something more meaningfull.

His brackets are also wrong. flag always gets set to 0.

Are you saying I should also get rid of this:
{
flag=0;
}

No you have to change it to flag==1
Also use brackets (I will add it in my answer)

Ok so this gets me stuck in a loop of water level LO and manually moving the float to HIGH has no effect.


text:
ESP8266 not connecting to WiFi
I am trying to send the temperatures from an DS18B20 to ThingSpeak, using an ESP8266. You can see the code I am using for that.
When I run the code I do not get any errors. In serial monitor it just shows that it is not connected to WiFi. If I change the WiFi name in code to something not even existing I still do not get any errors. I do not think that the ESP even finds the WiFi.
I think that the only problem to get everything work is just to get the WiFi connection to work properly. I have also checked the ESP with another simple code just to check that it is not broken and it actually get the code from my computer.
Here is the code I am using. (I have removed my password etc... )
//nodeMCU v1.0 (black) with Arduino IDE
//stream temperature data DS18B20 with 1wire on ESP8266 ESP12-E (nodeMCU v1.0)
//shin-ajaran.blogspot.com
//nodemcu pinout https://github.com/esp8266/Arduino/issues/584
#include <ESP8266WiFi.h>
#include <DallasTemperature.h>
#include <OneWire.h>

//Def
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS D4  // DS18B20 on arduino pin2 corresponds to D4 on physical board
//#define mySSR 0  // Solid State Relay on pin 0

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="******";
const char* MY_SSID = "******";
const char* MY_PWD = "******";
int sent = 0;

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

void loop() {
    float temp;
    //char buffer[10];
    //DS18B20.requestTemperatures();
    //temp = DS18B20.getTempCByIndex(0);
    temp=1111;
    //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
    Serial.print(String(sent)+" Temperature: ");
    Serial.println(temp);

    //if (temp != prevTemp)
    //{
    //  sendTeperatureTS(temp);
    //  prevTemp = temp;
    //}

    sendTeperatureTS(temp);
    int count = myPeriodic;
    while(count--)
    delay(1000);
}

void connectWifi()
{
    Serial.print("Connecting to "+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("Connected");
    Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
    WiFiClient client;

    if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
        Serial.println("WiFi Client connected ");

        String postStr = apiKey;
        postStr += "&field1=";
        postStr += String(temp);
        postStr += "\r\n\r\n";

        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n");
        client.print(postStr);
        delay(1000);

    }//end if
    sent++;
    client.stop();
}//end send

it prints a dot every second in Serial Monitor? how is the esp8266 powered? can the power source 300 mA?

You should upload the "WiFiScan.ino" example sketch to verify what WiFi stations (and with what signal strength) your ESP can see, if you think you cannot connect to your network.

yes it just shows the dot all the time. The ESP is right now connected to my computer by a micro USB-cable so no external power source if that is what you mean ? I just run the scaning and yes it finds the wifi witch I am trying to connect to.

For me i just changed the AP Band to 2.4Ghz from 5.0Ghz and it's working now

I have the same problem and I was struggled many days.
The solution for my issue was because SSID is case sensitive and I was trying to type all small letter.

Maybe you have a space in your WIFI SSID so you should check this in your router. Also maybe your WIFI is on 5Ghz and the ESP can't see it because it is only for 2.4 Ghz. Also if your WIFI AP is on a channel from 13 - 14 it also couldn't be seen by the ESP. And to test your ESP you can run the scan example and if it works you should try the web server example to connect to your network. If that all will work ok than the problem is in your code.

I had the same problem, when i tried to connect to my home wifi i got stuck with just printing dots and never could connected. First of all i though that my ssid or password had a typo, but it hadn't. Then i changed the nodemcu and the problem persisted. But when i tried to connect to other wifi it worked. So the problem was in my modem/router.So i changed my modem/router configuration to:
Operation mode: 802.11g+n to Automatic
Channel: 11 to Automatic
Channel Bandwich: 20 to Automatic
then the problem was solved.

This worked for me too, thanks for sharing.

In order to connect to Wifi from ESP32 and other boards, the WiFi connection needs to be 2.4GHz, wireless mode must be legacy. It cannot be set to Auto or N only. Go to your router box web page, and change this setting under Advanced Settings > Wireless.
The only code required to connect is.
void setup() {
  ...
  WiFi.begin(MY_SSID, MY_PWD);
}

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

In my experience a NodeMCU / ESP32 works perfectly fine with “N-only” Wifi networks.

Try to add WiFi.hostname("ESP-host"); before  WiFi.begin(ssid, password); - it works in my case.


text:
Connecting TCD1304 with Arduino
I'm working on a project, where I will have 2 red light beams, where one will be constantly turned on while the other will be turned on and off continuously with frequency about 100 hz.
I need to detect, on which side is the blinking beam and show it on the output (something such as if the blinking beam is on the left, turn green LED on; if it's on the right side, turn on the red LED). Each beam is big as 3mm circle.
I bought 3pcs (in case if I burn 2 of them :D) of Toshiba TCD1304 sensors(datasheet), which have 3684 elements in a row. I want to connect the sensor with Arduino, but I really don't know how I would even start this project. I've found some schematics, but it's either for some other model or is for different kind of a project(reading different colors over the field). Either way, none of them is useful for me.
It will look something like that at the end (the blue circle will be also red, but it's striped to show, it's the blinking one).

The TCD1304's minimum OS-datarate is 200 kHz. Quite a lot more than what the arduino is capable of. You should look to faster processors or to a different sensor. The TSL1401 seems to be popular with the arduino-community.
If you /need/ the TCD1304, then an arduino due will probably be able to do it, but I'm guessing you'll have to drop the arduino-IDE to achieve the full speed of the ADC.
Here's how I've done it with a STM32F4 processor:
https://tcd1304.wordpress.com/


text:
When I turn on the servo it spins on its own before going to the right position and start the sketch
I can't get my head around this: when I turn the servo on it just spins on its own as if it's setting up, it goes to an angle superior to the one I want it to go. (Don't mind if it has to set up but it can't spin more than 20 degrees which is currently doing).
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  myservo.write(0);
}

void loop() {
  for (pos = 0; pos <= degrees_of_motion; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos); // tell servo to go to position in variable 'pos'
    delay(servo_speed); // waits 15ms for the servo to reach the position
  }
  for (pos = degrees_of_motion; pos >= 0; pos -= 1) {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos); // tell servo to go to position in variable 'pos'
    delay(servo_speed);// waits 15ms for the servo to reach the position
  }
}

Humm, all the methods in object myservo are available after you instantiate it.  So try initializing before you attach the servo (swap lines in your setup() method).  Also be careful not to write a negative number to the servo.  I don't think you are doing it.  But just keep it in mind as the driver might interpret it as a really large number.

st2000 Do you mean swapping  myservo.attach(3);
myservo.write(0). It doesn't make a difference also tried to put int after void setup. Was this what you meant?

If you remove the positioning code in the loop() function so that the setup() does an attach followed by positioning the servo to 0 degrees, what happens? Also what if instead of the for loops in the loop() function you instead have a global variable for position which you set to zero degrees in setup() function and then have the logic in the loop() function just increment or decrement by 1 each time loop() is called?

If I remove the loop() function so that the setup() does an attach followed by positioning the servo to 0 degrees: Every time I turn it on it will spin to an unidentified angle really fast and come back to 0 and stop. Also global variable I am really new to Arduino not really sure what you mean. Thank you very much

the question title implies that the motor moves before you run the sketch. it that what happens?

Start simple.  Just power up the servo without connecting the control line to anything.  Most if not all normal servos should do nothing.  Maybe this servo is broken or behaves in unexpected ways. Perhaps the processor has been damaged. You might try a different Arduino Uno or at least a different PWM port on the same Arduino Uno.  Also, you might try a different servo library or write your own.

jsotola If I upload an empty sketch on the servo and power it nothing will happen.

Also tried a new arduino

Noise on the control line could cause random movement, try putting a pulldown on the control line; If this doesn't happen with an empty sketch that is very strange.

What happens if you have a sketch such as the following? This uses the loop() function of the Arduino sketch to do one movement each time the loop() function is triggered.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;   // variable to store the servo position
int direc = 1; // direction and amount of position iteration, + to increment, - to decrement

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  pos = 0;            // start off with zero degrees.
  direc = 1;          // start off incrementing the angle by 1
}

void loop() {
  if (direc > 0 && pos > degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = degrees_of_motion;
  }
  if (direc < 0 && pos < - degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = - degrees_of_motion;
  }

  myservo.write(pos);    // tell servo to go to position in variable 'pos'
  pos += direc;          // increment/decrement the position
  delay(servo_speed);    // waits 15ms for the servo to reach the position
}

Thank you but there is no difference with this sketch

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


text:
Arduino nano stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1
I have been building a project using an arduino nano clone. It uses the CH340 chip. It worked perfectly, and a week later it now doesnt.
When I want to upload code in arduino IDE I get the error below
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1

To try to fix the issue, I bought a USBasp board to program the nano, however, when I run AVRdude, it reads
avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: programm enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.}

If anyone can help please do
Thanks


text:
Arduino Vending Machine to monitor coin slot input while waiting for user input
I have this project called Onionskin Vending machine.
The function should be: when a coin is inserted, the pulses from the coin acceptor (which is not accurate sometimes so i didn't use attachInterrupt) is recorded by the Arduino and is shown to the user as Credits.
then while still waiting for coin input, it will ask the user to select a product.
EX. Scenario 1:
The user drops a 1cent coin, then the machine will show the user its credit as 1cents and will ask to press a button. the user will press a button then the machine will turn on a motor for (X) seconds to dispense product and say thank you then resets again.
EX. Scenario 2:
The user drops a 5cent coin, then the machine will show the user its credit as 5cents and will ask to press a button. then the user will drop again a 1cent coin so the machine will show its credit as 6cents and will again ask to press a button. the user will press a button then the machine will turn on a motor for (6X) seconds to dispense product and say thank you then resets again.
Here is the code I wrote so far, but the problem is when activated, it only records the first cent/pulse then goes on waiting for user input to press a button, even if I drop more coins, it will not count the new coins inserted, only always the 1cent / 1 Credit is displayed.
EDIT: There is no target credit, 1cents would do. but if user drop 2cents, then 2 Sets of product should be dispensed upon user selection of product. So target is the arduino should wait for coin slot input while waiting for user input at same time.
#include <Wire.h>  // Comes with Arduino IDE, Required for I2C
#include <LiquidCrystal_I2C.h>  //Call LCD I2C Library

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);   // Set the LCD I2C address Set up data transmission from microcontroller to LCD

int coinPin = 2;            //Defined as the receiving pin from the coin machine.
int coinState = 0;          //Determine the status of coinPin
int credits = 0;            //Define a variable to display the credit.
int delayTime = 0;          //Define delay variable for number of onionskin sheet feed duration
int resetPin = 12;          //Define reset pin for resetting after complete function
int sensorPin = A0; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor
const int laserPin = 6;
const int shortSizeFeedTime = 5000;  //Duration for 2pc onionskin to pass feeder
const int longSizeFeedTime = 7500;   //Duration for 3pc onionskin to pass feeder
const int ledpin = 13;      //define LED Pin at pin13
const int ButtonS = 8;      //Define button for short onionskin
const int ButtonL = 7;      //Define button for long onionskin
const int shortSize = 9;    //Define pin for motor pin shortSize
const int longSize = 10;    //Define pin for motor pin longSize

void setup()
{
  digitalWrite(resetPin, HIGH);
  delay(200);
  pinMode(coinPin, INPUT);     //Determine the function of the buttton pin to the input pin.
  pinMode(resetPin, OUTPUT);  //Set Reset PIN as OUTPUT
  pinMode(shortSize, OUTPUT);
  pinMode(longSize, OUTPUT);
  pinMode(laserPin, OUTPUT);         //Laser PIN
  /*
    lcd.begin(16, 2);         //Schedule your columns and rows. LCD
    lcd.setCursor(4,0);         //Set the cursor's starting position at position(4,0)
    lcd.print("WELCOME");      //Display screen text LCD
    lcd.setCursor(0,1);         //Set the cursor's starting position at position(0,1)
    lcd.print("PLZ  INSERT COIN");      //Display screen text LCD
  */
  Serial.begin(9600);  // Begin Serial Connection to PC

  lcd.begin(16, 2);  // initialize the lcd for 16 chars 2 lines, turn on backlight
  pinMode(ButtonS, INPUT_PULLUP);
  pinMode(ButtonL, INPUT_PULLUP);
  digitalWrite(laserPin, HIGH);// used as a laser trip wire sensor
  start(); //GOTO Start FUNCTION
  //delay(8000);
  // Wait and then tell user they can start the Serial Monitor and type in characters to
  // Display. (Set Serial Monitor option to "No Line Ending")
  //lcd.clear();
  //lcd.setCursor(0,0); //Start at character 0 on line 0
}

void start()
{
  //-------- Write characters on the display ------------------
  // NOTE: Cursor Position: (CHAR, LINE) start at 0
  lcd.clear();
  lcd.setCursor(4, 0); //Start at character 4 on line 0
  lcd.print("WELCOME!");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print(" ->Insert Coin<-");
  loop();
}

void loop()
{
  sensorValue = analogRead(sensorPin);//read the status of the LDR attached to the analog pin for laser trip wire
  coinState = digitalRead(coinPin);   //coinPin value In the coinState
  lcd.setCursor(0, 0);        //Set the cursor's starting position at position(0,0)
  while (analogRead(sensorPin) < 1000)
  {
    lcd.clear();
    lcd.print("PLS. REMOVE ANY");
    lcd.setCursor(0, 1);
    lcd.print("OBJECT FRM TRAY!");
    delay(2000);
    start();
  }
  if (coinState == LOW)         //Condition
  {
    credits += 1;          //Calculate the value of the variable. It will increase each time. 5
    delay(500);                        //Delay schedule 500ms.
    lcd.clear();            //Clear command all LCD screen
    lcd.print("CREDIT:");         //Display LCD Display Message
    lcd.setCursor(8, 0);        //Set the cursor's starting position at position(8,0)
    lcd.print(credits);            //Displays the value of variable "credit" on the LCD screen.
    lcd.setCursor(12, 0);        //Set the cursor's starting position at position(8,0)
    lcd.print("PHP");          //Display screen text LCD
    lcd.setCursor(0, 1);
    lcd.print("PRESS TO PROCEED");

    //Wait for button input from user
    while (digitalRead(ButtonS) == HIGH || digitalRead(ButtonL) == HIGH) {

      //---------Servo A----------------
      if (digitalRead(ButtonS) == LOW && sensorValue > 1000)  {
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("VENDING:");
        lcd.setCursor(0, 1);
        lcd.print("LONG ONIONSKIN");
        delayTime = credits * longSizeFeedTime;
        digitalWrite(longSize, HIGH);//Turn on the feeder motor
        delay(delayTime); //calculation time for 2pc of onionskin
        digitalWrite(longSize, LOW);//Turn off the feeder motor
        lcd.clear();
        lcd.setCursor(3, 0);
        lcd.print("THANK YOU!");
        lcd.setCursor(0, 1);
        lcd.print("PLS. COME AGAIN!");
        credits = 0;//set the credits back to zero
        delay(3000);
        digitalWrite(resetPin, LOW);//optional for activation harware reset pin
        start();//GO to start function, kind of reset
        break;//this never actually happens :)
      } // when item is dispensed exit loop and return to wait for coin

      //---------Servo B-------------
      else if (digitalRead(ButtonL) == LOW && sensorValue > 1000) {
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("VENDING:");
        lcd.setCursor(0, 1);
        lcd.print("SHORT ONIONSKIN");
        delayTime = credits * shortSizeFeedTime;//calculation time for 2pc of onionskin
        digitalWrite(shortSize, HIGH);//Turn on the feeder motor
        delay(delayTime);
        digitalWrite(shortSize, LOW);//Turn off the feeder motor
        lcd.clear();
        lcd.setCursor(3, 0);
        lcd.print("THANK YOU!");
        lcd.setCursor(0, 1);
        lcd.print("PLS. COME AGAIN!");
        credits = 0;
        delay(3000);
        digitalWrite(resetPin, LOW);//optional for activation harware reset pin
        start();//GO to start function, kind of reset
        break;//Again, this never happens :)
      }
    }//End While Loop
  }//End If coin detect loop
}//End void loop()

PS: I have read somewhere that using millis could help solve the dual running problem or by using the correct while or switch-case loop. I'm not familiar much about how while, do-while, for, switch loops work.

the two scenarios are the same

@jsotola different coin was dropped for each scenario. the computation of product was also different because of the amount inserted

I'm not familiar much about how while, do-while, for, switch loops work.* You have to learn programming first. You are trying to drive without knowing what a steering wheel is.

Abbas and guys, i was wondering if its possible to remove the button code then make the code wait for a few seconds then it will check if the client dropped 1 cent or 2 cents then it will run specific command per value? i just started learning arduino coding. hope to hear form you soon guys

After several research here is the final working code and solution to the problem.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Constants

bool userSelect = false;
const int coinPin = 2;      // Defined as the receiving pin from the coin machine.
int coinState = 0;          // Determine the status of coinPin
volatile int credits = 0;   // Define a variable to display the credit.
int delayTime = 0;          // Define delay variable for number of onionskin feed duration
int resetPin = 12;          // Define reset pin for resetting after complete function
int sensorPin = A0;         // select the input pin for LDR
int sensorValue = 0;        // variable to store the value coming from the sensor
const int laserPin = 6;
const int shortSizeFeedTime = 5000;  // Duration for 2pc OnionSkin to pass feeder
const int longSizeFeedTime = 7500;   // Duration for 3pc OnionSkin to pass feeder
const int ledpin = 13;      // Define LED Pin at pin13
const int ButtonS = 4;      // Define button for short Size OnionSkin
const int ButtonL = 5;      // Define button for long Size OnionSkin
const int shortSize = 6;    // Define pin for motor pin shortSize
const int longSize = 7;    // Define pin for motor pin longSize

//I2C pins declaration for LCD
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//CoinInterrupt counter function
void coinInterrupt() {

  // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
  credits += 1;
  digitalWrite(ledpin, HIGH);
  digitalWrite(ledpin, LOW);
}

//Long OnionSkin Feeder function
void longSkinServe() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("VENDING:");
  lcd.setCursor(0, 1);
  lcd.print("LONG ONION SKIN");
  delayTime = credits * longSizeFeedTime;
  digitalWrite(longSize, HIGH);
  delay(delayTime);
  digitalWrite(longSize, LOW);
  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("THANK YOU!");
  lcd.setCursor(0, 1);
  lcd.print("PLS. COME AGAIN!");
  delay(3000);
  digitalWrite(resetPin, LOW);
  credits = 0;
  userSelect = false;
}

//Short OnionSkin Feeder function
void shortSkinServe() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("VENDING:");
  lcd.setCursor(0, 1);
  lcd.print("SHORT ONION SKIN");
  delayTime = credits * shortSizeFeedTime;
  digitalWrite(shortSize, HIGH);
  delay(delayTime);
  digitalWrite(shortSize, LOW);
  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("THANK YOU!");
  lcd.setCursor(0, 1);
  lcd.print("PLS. COME AGAIN!");
  delay(3000);
  digitalWrite(resetPin, LOW);
  credits = 0;
  userSelect = false;
}

void setup() {
  Serial.begin(9600);  // Begin Serial Connection to PC
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);  // initialize the lcd for 16 chars 2 lines, turn on backlight
  lcd.print("STARTING UP...");
  attachInterrupt(digitalPinToInterrupt(coinPin), coinInterrupt, RISING);
  pinMode(ledpin, OUTPUT);
  pinMode(resetPin, OUTPUT);  //Set Reset PIN as OUTPUT
  pinMode(shortSize, OUTPUT);
  pinMode(longSize, OUTPUT);
  //  pinMode(laserPin, OUTPUT);         //Laser PIN
  pinMode(ButtonS, INPUT_PULLUP);
  pinMode(ButtonL, INPUT_PULLUP);
  delay(2000);

}

// Main loop
void loop() {
  if (credits == 0) {//not yet running, there is no credit yet
    lcd.clear();
    lcd.print("ONION SKIN VENDO");
    lcd.setCursor(0, 1);
    lcd.write("-[INSERT COINS]-");
    delay(3000);
    lcd.clear();
    lcd.print("-[INSERT COINS]-");
    lcd.setCursor(1, 1);
    lcd.write("P1 or P5 ONLY");
    Serial.println("No Coin Inserted Yet...Waiting");
    delay (3000);

    //---Wait for Coin/Credit-----------
    while (credits > 0 && userSelect == false) { //if coin inserted stay in servo enable loop

      lcd.clear();            //Clear command all LCD screen
      lcd.print("CREDITS:");         //Display LCD Display Message
      lcd.setCursor(9, 0);        //Set the cursor's starting position at position(8,0)
      lcd.print(credits);            //Displays the value of variable "credit" on the LCD screen.
      lcd.setCursor(12, 0);        //Set the cursor's starting position at position(8,0)
      lcd.print("PHP");          //Display screen text LCD
      lcd.setCursor(0, 1);
      lcd.print("PRESS TO PROCEED");
      Serial.println("Credits:");
      Serial.print(credits);
      if (digitalRead(ButtonS) == HIGH || digitalRead(ButtonL) == HIGH) {

        if (digitalRead(ButtonS) == LOW)  {
          //execute short size motor
          userSelect = true;
          shortSkinServe();
        }
        else if (digitalRead(ButtonL) == LOW)
        {
          userSelect = true;
          longSkinServe();
        }
      }
      delay (80); // for while loop LCD refresh speed control
    }

  }

}

Also here is a circuit diagram.

Some may say that the coding is not efficient as using several if else..if statements, but hey, this solves the problem. Cheers!

Make it a state machine:
Initial state is idle, nothing on the tray, no credit
If a coin is entered then it counts the credits and displays it. (Should always be true)
If a button is pushed then only if credit is sufficient and tray is empty will something be vended (and credit is subtracted), otherwise show error for a few seconds.
Showing an error can be done by setting a global and a start time and duration:
long credit;
enum{noError, insufficientCredit, trayError, thankyou};
int error;
unsigned long messageTimestamp;
unsigned long messageDuration;

void updateLCD(){
    if(millis() - messageTimestamp > messageDuration)
        error=noError;
    switch(error){
    case noError: break;

    case insufficientCredit:

        //show insufficient credit error
        break;
    case trayError:

        //show tray error
        break;
    case thankyou:

        //show thankyou message
        break;
    }

    if(credit == 0){
        //show attract mode
    }else{
        //show credit
    }
}

You can do something similar for the motor:
bool motorOn;
unsigned long motorTimestamp;
unsigned long motorDuration;

if(motorOn && millis() - motorTimestamp> motorDuration){
    motorOn = false;
    digitalWrite(shortSize, LOW);//Turn off the feeder motor
}

this way you can also prevent the vending from starting again while the motor is still running by making an extra check on motorOn.

I agree with the state machine idea. Draw a grid showing all possible states (eg. no money, some money, waiting for button, dispensing goods, etc.). Then all possible actions (eg. adding money, pressing button) and work out what needs to be done in each state for each possible action.

Actually there is no amount of target credit, the base credit is 1cent. 1cent is suficient to run the feed motor/dispense product. if you add 2 cents, then you woud have 2 credits and 2 set of product will come out. the problem is with the code that i made, only the 1cent is recognised/counted, its like when it detects a pulse at the coinPin, its counts the first credit then moves on to the next function to wait for user input. what i need is for it to still wait for coin pulse detect while also waiting for the user input.

@ratchet If you would also kindly include the modification/correction in the main code. As I said I'm not familiar much into c++ programming. I don't know also in what part of the code to call the updateLCD() function, also where to insert/replace the solution you posted.

@ratchet freak Hi, any update? I'm still waiting and curious :) Thanks

@EngrAbbas if you want to scale the amount of product dispenced you can scale the motorDuration accordinly

@ratchetfreak I have modified the code, but it still cant work. here it is I made. https://pastebin.com/YPR48f7s
I think the problem is that I don't know where to insert your code. I have zero knowledge on how millis() work, i just read them on the internet that its what you use to multitask/ do two different things at same time. please help