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

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


text:
Weird Voltage Noise
I'm new to this forum, so hello to everyone out there.
So I have an Uno with A0 connected to the positive end of a chain of LEDs (they light up when a motion sensor goes off, clunky, but it works), and the negative end is hooked up to the GND of the analog side of the Uno. It runs the following code:
void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
}

void loop()
{

  Serial.println(printVals(A0));
}

float printVals(uint8_t pin)
{
  int sensorValue = analogRead(pin);
  float voltage = sensorValue * (5.00 / 1023.00);
  return voltage;
}

And when I open the Serial Plotter, I get a weird square wave for the voltage (when there is 0V on the LEDs, I used a volt meter).
Out of curiosity, I added a jumper cable from A2 to +5V (the red wire in the diagram) and added plotting for A2, and this solved the problem - except now, the read on A0 is about 0.53.
Now, I'm more of a software guy, so I figure just subtract 0.53 and move on (varies only +- 0.03V), but I want to know: What in the world did that jumper cable do?

There is a tiny capacitance in the ADC sampler, and if the signal you are measuring is weak, the stored charge in the ADC can affect the reading, depending on what else is going on.  Like multiplexing readings from A0 and A2.

A0 connected to the positive end of a chain of LEDs - you did what? Can you sketch up a schematic?

A square wave of what values?

The square wave is between 0 and roughly 0.5, and when I added the jumper, it was a mostly straight line at about 0.5V.

And this is a driveway motion sensor, so sense I don't have direct access to the trigger wires, I am connected to the indicator LEDs of the system, they have about 2-2.5V on them when lit, and they are only lit when motion is detected.

Just realized that the analog port being read from (intended to have the jumper on it) was A1, even though the jumper cable was connected to A2. Either that, or I was reading A2, but initialized A1 instead.

It is better to use an optocoupler. This will give the galvanic isolation between the devices. And use a digital input instead of an analog. Since the indicator has only two states.

@Ferba, my chain of LEDs is actually part of a circuit board for a driveway monitor receiver. When it detects motion, the LEDs light up and the voltage measured by analogRead increases by about a volt.
Also, as it turns out, the jumper to +5v was functioning as a pull-up wire... not a good idea. It burned out the chip in the driveway monitor by backfeeding an output.
In the end, I added an "_PULLUP" after the INPUT in setup and that solved the problem.

Why are you connecting a chain of leds to a pin setted as an input and then connected to GND? I think that is like connect the pin to nothing.
in the documentation of arduino they have a note about the funcion analogRead() and a fluctuation of data.
https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
i think if you need to read an input put a button (or maybe i didnt understand you scheme)

source: Stack Exchange

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

sort: votes


text:
What is this potentiometer for?
I am working on an anemometer project using Arduino. I don't know barely anything from Arduino and I am following this tutorial.
I have some doubts on the making part. This is what I have to make:
and this is the code:
//anemómetro con LCD
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

float veloc1 = 0; // entrada A0
int tiempo = 0;
int cnt = 0;
float v1 = 0;
float v2 = 0;

void setup() {
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.print("Anemometro EC"); // Aqui va el mensaje
  analogReference(INTERNAL);// pone como referencia interna 1.1V
}

void loop() {
  v1 = (analogRead(0)); // lectura de sensor a0
  veloc1 = (v1 * 0.190); // 0,190 corresponde a la pendiente de la curva aca deben poner el numero que calcularon
  lcd.setCursor(0, 1); // Ponte en la line 1, posicion 0
  lcd.print(veloc1); //muestra la velocidad del viento en el LCD
  lcd.setCursor(4, 1); // ponte en linea 1, posicion 5
  lcd.print("Km / h");
  lcd.setCursor(9, 1);
  lcd.print("Max");
  if (veloc1 > v2)v2 = veloc1, lcd.print (v2, 1); // muestra la velocidad maxima que alcanzo
  delay(1000);
}

What is the potentiometer doing here? Why is it necessary?
My lcd screen doesn't show anything. Does anyone knows why??

Thanks in advance.

What is the potentiometer doing here? Why is it necessary?

It's there to control the "offset voltage" of the LCD, which is what controls the contrast of the display.

My lcd screen doesn't show anything. Does anyone knows why??

Maybe you wired it wrong. Maybe you didn't put the potentiometer in the circuit because you didn't understand what it is for. Maybe you just need to adjust the contrast by turning said potentiometer. It's hard for us to tell. By showing us what you intended to build and then telling us that what you actually built doesn't work, there is nothing we can tell you. There must be some difference between what you intended to build and what you did build, but we can't see what you built, so we can't have any clue.

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


text:
Programming an arduino using only switches to give 0 or 1
I am not too experienced about the working of arduino but I know that it involves data in computer language  ( 0 and 1)
I have an array of 8 switches plus a few extra. As I am unable to (due to some reasons) program it through my pc, I wanted to know if it is possible to manually use switches to send data and program it? (complexity doesn't matter).
If yes, then could you tell me how I could do it (taking into consideration my limited knowledge).
If no then why?

Welcome. I'm not understanding your question. What is 'it'  you want to program? For programming an Arduino you need a PC. You can use switches without an Arduino, but I also don't understand what you  mean with 'send data' (to what?).

Ok, that sparks the question, why you cannot use a computer. As you are able to get an Arduino, I guess you could also buy other electronic components. If a PC is just too expensive, you could go with a Single Board Computer like the Raspberry Pi. Depending on which Pi board you buy, it costs 10 or 35$. 1 standard USB charger (with over 1.5A), an SD card (which can be bought with an OS on them), cheap USB Keyboard/Mouse combination and any HDMI capable display. And a USB cable for the Arduino of course. Then you are good to go. It is like a full fletched PC, just smaller and not that fast.

@chris Thanks for the suggestion!Well I have been having serious problems with my pc currently such that it won't compile nor interpret any code. That's why I had been looking for an alternative

Short answer: If you are unable to program your Arduino using a computer, you are unable to program your Arduino at all.
The Arudino is built to be programmed using a serial interface (usually USB) that interacts with the bootloader, plus an IDE on the other end of the cable. It is not set up to be programmed with switches.
You could conceivably build an Arduino programmer that would let you enter a program using 8 switches plus an enter button. Such a programmer would collect the program into a memory buffer, and then load it into the Arduino using the USB interface but it would take WEEKS of working constantly to enter the simplest of programs, and the odds that you could do it without multiple errors is pretty much zero. Plus, it would probably cost several hundred dollars to build such a programmer. It would be a pointless exercise in masochism.
(Not to mention the fact that you would have to somehow compile your Arduino program into machine code, and convert that into binary in order to enter it.)
Some of the earliest computers required that the operator enter the first few instructions via switches as you describe, and then the computer would read and begin executing the rest of its program from a tape drive. Those computers only had a few thousand bytes of memory, and even then, the instructions the operator had to enter were just enough to start the machine booting from tape.

The First Arduino had a "serial" port and the more recent have a serial USB interface. So to be correct, the Arduino is programmed with a serial interface.

@MatsKarlsson, thanks for the correction. I edited my answer accordingly.

While not physically impossible it would be a really silly thing to attempt.
However, if I were to attempt it I'd probably use just 3 switches (or rather 2 switches and one button though you could use a switch instead of the button).
I'd wire it up so that the RESET, MISO and SCK pins were all connected to the switches in such a way that I could hold the whole board in RESET for extended periods (i.e., switch between RESET and GND), set a HIGH or a LOW as needed on the MISO pin, and toggle the SCK pin HIGH and LOW (I'm not sure off hand if you need to idle LOW or HIGH with the clock - the datasheet will tell you).
Then I'd become extremely intimate with the ICSP protocol of the ATMega328P.
That would then allow me, extremely slowly, to act like a hardware programmer and instruct the ATMega328P to program itself with data I sent.
You might also like to attach a shift register to the MOSI and SCK pins with 8 LEDs on it so you can monitor the responses from the Arduino while programming.
It would take forever to upload even the simplest of programs, and the error rate would be far to high, but it could be done if you were really desperate and had nothing else to do (including eat or sleep) for a number of days.

Oh..thanks a lot!Atleast now I am getting to know the internal workings of the arduino a bit...But of course I won't attempt it

Oh wow. That's going really primitive. You'd need debounced switches though. I wonder how many KB of data you'd need to send through the serial interface in order to enter a trivial program like "blink"? Not to mention the work to hand-compile the code, and then map the program into the data-stream needed to program it.

@DuncanC Yep. Physically possible. Emotionally possible? Nah. You would need to be really really desperate for something to occupy your time, plus a coffee IV and colostomy bag...

@DuncanC: You can write “blink” in assembly in less than ten 16-bit instructions. It wouldn't take too long to assemble it by hand. But then, the overhead of the ICSP protocol may be a lot larger than the program itself...

but if you construct a punch card reader to switch the switches ... :-)

This projects sounds a lot like trying to program in the Brainf*ck language (google it if not familiar. It's a real thing.)

@DuncanC I remember it well... I once did write an actual program in it...

Oh this is bringing me back 45-50 years when I did this with a Z80 CPU, it was tedious and fun.... I would choose another processor than the Atmel AVR family.

@MatsKarlsson, did what? Programmed a Z80 with shift registers and switches? Or do you mean writing machine code by hand and entering it in hex? I've done a fair amount of that myself, but mostly on the 6502. (I've done a little Z80, but with an assembler)

It was writing assembler on paper, convert it to binary and then with dip switches or was it toggle switches, enter the code and then step to next address location for the next row. After that I did a hex keyboard and 7-segment led display.

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


text:
Getting boot mode 1.6 error
When I try to upload my script I get this in my serial monitor:

ets Jan  8 2013,rst cause:4, boot mode:(1,6)
wdt reset

The board I am using is Uno + Wifi
And this is my sketch:
/*
* Arduino Smart Thermometer
*
*/
#include <LiquidCrystal.h> // includes the LiquidCrystal Library
#include <Button.h>
#include <SteinhartHart.h>

//LCD constants
const int rs = 2, en = 3, d4 = 8, d5 = 9, d6 = 10, d7 = 11;

//Thermsistor variables
int ThermistorPin = 0;
boolean degreeChanged = false;
double temp = 0.0;

//Buttons
int decreaseDegreePin = 12;
int increaseDegreePin = 13;
int backlightSwitch = 7;

#define PULLUP false        //To keep things simple, we use the Arduino's internal pullup resistor.
#define INVERT false        //Since the pullup resistor will keep the pin high unless the
                           //switch is closed, this is negative logic, i.e. a high state
                           //means the button is NOT pressed. (Assuming a normally open switch.)
#define DEBOUNCE_MS 50     //A debounce time of 20 milliseconds usually works well for tactile button switches.

Button decreaseDegreeButton(decreaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
Button increaseDegreeButton(increaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
Button backlightSwitchButton(backlightSwitch, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button

//Variables
int wantedDegree = 20;
int backlight = 255;
int switchPin = 4;
double curTemp;

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers
unsigned long previousDegreeUpdateTime = 0;
unsigned long degreeUpdateDelay = 3000;

//Libraries
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
SteinhartHart thermsistor(ThermistorPin);

void setup() {
  //Initialize backlight
  analogWrite(5,backlight);

  pinMode(switchPin,OUTPUT);

  //Initialize display
  lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }

  //First display
  updateDegree();
  displayCurrentStatus();
}
void loop() {
  switchHeather();

  //Initialize backlight
  analogWrite(5,backlight);

  //Recalculate degree
  updateDegree();

  //Buttons initialization
  changeDegreeWithButtons();

  //If degree is updated, update display
  unsigned long currentDegreeUpdateTime = millis();
  if(degreeChanged){
    if((currentDegreeUpdateTime - previousDegreeUpdateTime) > degreeUpdateDelay){
      previousDegreeUpdateTime = currentDegreeUpdateTime;
      displayCurrentStatus();
    }
  }

}

void switchHeather(){
  if(wantedDegree > curTemp){
    digitalWrite(switchPin, HIGH);
  }
  else{
    digitalWrite(switchPin, LOW);
  }
}

void updateDegree(){

  curTemp = thermsistor.getTempCelsius();

  if(temp != curTemp)
  {
    temp = curTemp;
    degreeChanged = true;
  }
  else{
    degreeChanged = false;
  }
}

void displayCurrentStatus(){
    //Print degrees to LCD
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print(temp);
    lcd.print(char(223));
    lcd.print(" Celcius");
}

void changeDegreeWithButtons(){
  //Read buttons
  decreaseDegreeButton.read();
  increaseDegreeButton.read();
  backlightSwitchButton.read();

  if (increaseDegreeButton.wasReleased()) {
    wantedDegree++;
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print("Omhoog naar: ");
    lcd.print(wantedDegree);
  }

  if (decreaseDegreeButton.wasReleased()) {
    wantedDegree--;
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print("Omlaag naar: ");
    lcd.print(wantedDegree);
  }

  //Backlight switch
  if (backlightSwitchButton.wasReleased()) {
    if(backlight == 255){
      lcd.clear();
      lcd.print("Backlight: Off");
      backlight = 0;
    }
    else{
      lcd.clear();
      lcd.print("Backlight: On");
      backlight = 255;
    }
  }
}

Why does this happen and how can I fix it? When I use the same script on my Arduin Uno board it does work. The board Uno + Wifi however doesn't.
Also what I used is:

An LCD Screen
3 buttons with resistors
A thermsistor with resistor
A relay (only connected to arduino
External power source

This message indicates that you currently have the ESP8266 rather than the ATmega connected to the USB interface.
In order to upload Arduino sketches to the ATmega, you need to follow the instructions on the sale page to change the dip switches to USB<>ATmega328 mode.

The table is probably sufficient, if not you can puzzle out the German explanatory text or try machine translation.
It's possible you could also install ESP8266 support in your Arduino IDE and run your sketches on the ESP8266 part of the board instead of the ATmega part, however chances are mot of the Arduino headers go to the ATmega, so you would be limited in what peripherals you could connect.

Thank you this makes sense I thought I could just upload everything to ESP8266. But this leaves me with one question. The reason I use the ESP8266 part is because I need to pull data from the internet. If I upload my sketch to the Atmega part how do I pull the data from ESP8266 that I retrieved from there?

In example let's say I have a "String data" in ESP8266" how do I use this "data" variable inside Atmega?

That is both an entirely different question, and one which is too broad to be a fit here.
Do a web search for Arduino + ESP8266 examples and invest some time in studying and trying them.

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


text:
How do I know if I have a short circuit
I just got my first arduino starters kit so I'm a total noob in it. My simple LED blinker did work, afterwards I used a switch button with a debouncer script. It worked like I wanted but I wanted to try a buzzer instead of the LED, which did not work. Afterwards when I put the LED back in it didn't work anymore either.
The onboard LED does still work. Does this mean my breadboard had a short circuit? Is there any way I can know this for sure? And what exactly went wrong? Did I have to use a higher resistor?

I would highly recommend using a digital multimeter in this case. They are not too expensive and a must for electrical projects. Most have functions such as checking for shorts. In addition, you can check to see if the pin in question changes voltage when activated. The thing to remember is that heat kills electrical components, and high current causes heat (high power, really, but watch your current and you will be fine) get familiar with the formula v=I/R and don't put too much current through your buzzer or LED. LEDs have very little resistance.

Thank you for your advice, I should have a multimeter somewhere I will try it out. I thought my programming knowledge would be enough for Arduino but I think that won't cut it I will indeed look up and learn more about it.


text:
Newcomer at Arduino
I think it will become readily apparent that i have absolutely zilch programming experience as I am currently going out my mind with a problem i am having trying to get my first arduino uno project off the ground. I am simply attempting to acquire the necessary libraries including a TimeLib.h library file, but however i seemingly cant even figure out how exactly to complete that very simple first step. I am giving it a serious go trying to break into this interesting field and would greatly appreciate any advice anyone could generously provide.
With regards,
Newcomer

Please share your code attempts so we can see where you may be going wrong.

See How do I ask a good question? - if you read your own question you will see you have given us no details at all. Posting your code, plus any error messages, would be a good start.

OP seems to be asking for advice about how to start. Since they haven't gotten farther than including a header they probably have no code worth showing.

I'm voting to close this as too broad. If you would like to edit your question to be more specific and narrow in scope I'm sure we can help you. For example: "How do I find and install the library that contains the file TimeLib.h?"

If you are using the Arduino IDE then you first need to include the library then you can put #include <TimeLib.h> at the top of your sketches.
There is plenty of documentation online about how to use Arduino. To solve your immediate problem I would go here: https://www.arduino.cc/en/Guide/Libraries


text:
Powering 12V keypad through Arduino Uno
Arduino Uno
I'm currently working on a project which will involve entering a sequence on a 12V keypad. The keypad and its documentation can be found here: https://www.jaycar.com.au/digital-keypad-with-rfid-access-control/p/LA5353

They keypad wants 9-18V AC/12~24V DC. I'll be using the keypad to output 26 bit Wiegand to the Arduino. I'm just wondering the best way to power this system. The schematics included with the keypad show that the keypad and the controller  (Arduino) should be sharing a power source. See image attached.
How can I power the 12-24V keypad through the arduino without frying it?

How can I power the 12-24V keypad through the arduino without frying it?

If you power the Arduino with slightly more than 12V (through the barrel jack) then you can get 12V (or slightly less than you power the Arduino with) from the VIN pin.
However the Arduino's on-board voltage regulator does tend to get a little hot when such a high voltage is used to power it. Better is just to power the keypad separately from the correct power source.
And don't forget to connect the grounds together.

Thanks for the information Majenko. So there's no issue with using a seperate power supply for the keypad and then grounding it with the Arduinos ground pin? Also, can i plug the d0 and d1 lines directly into the Arduino, or do i need to manage the voltage?

@SirPattalot none at all.

I appreciate the help. I edited my question after you answered so swiftly, one final question: can i plug the d0 and d1 lines directly into the Arduino, or do i need to manage the voltage?

I think Wiegand is an open drain protocol. Turn on the internal pull-ups of your digital pins and the keypad pulls them down like buttons.

So in that case, direct into Arduino SHOULD be fine?

According to Wikipedia: The Wiegand interface uses three wires, one of which is a common ground and two of which are data transmission wires usually called DATA0 and DATA1, alternately labeled "D0" and "D1" or "Data Low" and "Data High". When no data is being sent, both DATA0 and DATA1 are pulled up to the "high" voltage level — usually +5 VDC. When a 0 is sent the DATA0 wire is pulled to a low voltage while the DATA1 wire stays at a high voltage. When a 1 is sent the DATA1 wire is pulled to a low voltage while DATA0 stays at a high voltage. -- so yes, it's fine.


text:
Beetle ble with SD card reader
I just started working on a project involving bluno beetle ble. For now, i'm sending the data from beetle to a android app i made.
But, for a fail safe mechanism in case the mobile is not in range or has disconnected from the device, i want to add a SD card reader to the device so i can save the data.
Is it really possible to add SD card reader to beetle ble? If yes, can someone provide any hint on what connections need to be made?
Thanks

Have you found an answer to this?

@RichardWinter check the answer

Eventually I got it working. The connections that i made are as follows:

SDA pin on beetle -> SDA pin on SD card module
SCL pin on beetle -> SCL pin on SD card module
GND pin on beetle -> GND pin on SD card module
VCC pin on beetle -> VIN pin on SD card module

Then upload the sample code present on arduino IDE, or you can find it here as well: https://www.arduino.cc/en/Tutorial/ReadWrite
There we go!
EDIT: The soldering is tricky for bluno beetle. Detailed instructions can be found here :


text:
Arduino continuously reading ADC value using interrupt
I have a mono jack audio act as analog input for arduino UNO. The microphone outputs voltage that varies in terms of amplitude (volume) and frequency. In order to get the high sampling rate, I use prescaler 16 and set high baudrate for serial communication to print the value. I save the analog read from that jack audio to buffer array with maximum value is 256 (8-bit). This is my code (I modify from the Nick Gammon's blog about ADC here) :
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 39;
  OCR1B = 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)
{
    results[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.println (results [i]);
  }
}

With that code, I got a nice result of sinusoidal graph represented audio value up to 4000 Hz like this :

But one thing that didn't work is if I change the volume or frequency (while displaying data) of analog input (jack audio), the graph I print and display via serial plot audio won't change. So I had to close it and open again to see the change. The question is how can I achieve the continuous and real time reading of this ? Thank you very much.

reset the resultNumber to 0 after you have written it to serial. and turn interrupts back on
void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

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

Okay I'll try that first


text:
Ethernet shield issues (defective shield?!)
I'm a newbie in using the Arduino Ethernet Shield v2 (Arduino product code A000024) and I'm experiencing some strange behaviours on a critical work with strict deadline.
The project involve some Arduino (both UNOs and MEGA2560s) sending sensor data via OSC to a couple of destination PCs for later processing.
To do that I'm using what it seemed to me to be a quite simple to use Arduino OSC library, the CNMAT one.
I've noticed this fact, which I think is related to some hardware malfunction.
I've found my code getting stuck even with a correct setup of the LAN. The code stops working, stops sending OSC messages, Ethernet shield is no more reachable with the ping. This persists also after loading again the code, or manually resetting the Arduino board. Initially I thought it was my fault but I've found that, substituting the shield with another one, the problem magically disappeared. On one of the problematic shield I've also experienced many continuous shutdowns and startups of the Arduino every 5 seconds (firmware restart from the setup)!
Are these ethernet shields known to be defective or having some issues?
The strange thing is that I've experienced this problem on 3 out of 8 of them: this is super critical!
Have you experienced something similar? Do you know of similar problems occurred before?

For debug purposes, here's a code test I've written and tried on a single Arduino UNO, always the same, using the same LAN setup (ethernet cable, IP addresses, Ethernet switch) switching two different Ethernet shields:
/* NET stuff ********************************************/
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
EthernetUDP Udp;

IPAddress ip(10, 3, 3, 210); // the Arduino's IP
byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x83, 0xCE };

#define DELAY 1000

// SETUP //////////////////////////////////////////////////////////////////
void setup() {

  Serial.begin( 115200 );
  Serial.println("setup");

  // Ethernet and OSC utilities **************************
  Ethernet.begin(mac, ip);

  // Hardware status check
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.");
  }
  else if (Ethernet.hardwareStatus() == EthernetW5100) {
    Serial.println("W5100 Ethernet controller detected.");
  }
  else if (Ethernet.hardwareStatus() == EthernetW5200) {
    Serial.println("W5200 Ethernet controller detected.");
  }
  else if (Ethernet.hardwareStatus() == EthernetW5500) {
    Serial.println("W5500 Ethernet controller detected.");
  }

  //Tells you whether the link is active.
  // LinkOFF could indicate the Ethernet cable is unplugged or defective.
  if (Ethernet.linkStatus() == Unknown) {
    Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500.");
  }
  else if (Ethernet.linkStatus() == LinkON) {
    Serial.println("Link status: On");
  }
  else if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Link status: Off");
  }

  while( Ethernet.linkStatus() == LinkOFF ) {
    delay( DELAY );
  }
}

// LOOP ///////////////////////////////////////////////////////////////////
void loop()
{

  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.print("Ethernet link broken!\t");
    Serial.println("please connect the Ethernet cable");
    delay( DELAY );
    return;
  }

  Serial.println("LOOP working as expected!");
  delay( DELAY );
}

When I try this code using the "defective" Arduino Ethernet shield the Serial monitor print something like this (note that I'm not doing anything, I'm leaving everything untouched):
[...]
14:25:17.906 -> setup
14:25:18.471 -> W5500 Ethernet controller detected.
14:25:18.471 -> Link status: On
[...]
14:26:41.545 -> LOOP working as expected!
14:26:42.542 -> LOOP working as expected!
14:26:43.538 -> LOOP working as expected!
14:26:44.535 -> Ethernet link broken!   please connect the Ethernet cable
14:26:45.531 -> LOOP working as expected!
14:26:46.561 -> LOOP working as expected!
14:26:47.558 -> LOOP working as expected!
14:26:48.555 -> LOOP working as expected!
14:26:49.552 -> Ethernet link broken!   please connect the Ethernet cable
14:26:50.549 -> LOOP working as expected!
14:26:51.546 -> LOOP working as expected!
14:26:52.543 -> LOOP working as expected!
14:26:53.540 -> LOOP working as expected!
14:26:54.570 -> LOOP working as expected!
14:26:55.567 -> Ethernet link broken!   please connect the Ethernet cable
14:26:56.564 -> LOOP working as expected!
14:26:57.561 -> LOOP working as expected!
14:26:58.557 -> LOOP working as expected!
14:26:59.553 -> Ethernet link broken!   please connect the Ethernet cable
14:27:00.550 -> Ethernet link broken!   please connect the Ethernet cable
14:27:01.546 -> LOOP working as expected!
14:27:02.576 -> Ethernet link broken!   please connect the Ethernet cable
14:27:03.572 -> LOOP working as expected!
14:27:04.569 -> LOOP working as expected!
14:27:05.566 -> LOOP working as expected!
14:27:06.563 -> LOOP working as expected!
14:27:07.560 -> LOOP working as expected!
14:27:08.557 -> LOOP working as expected!
14:27:09.587 -> LOOP working as expected!
14:27:10.583 -> Ethernet link broken!   please connect the Ethernet cable
14:27:11.580 -> LOOP working as expected!
14:27:12.577 -> LOOP working as expected!
[...]

In the meantime, the ping stops working and will not work again until I reboot the Arduino:
[...]
64 bytes from 10.3.3.210: icmp_seq=301 ttl=128 time=0.185 ms
64 bytes from 10.3.3.210: icmp_seq=302 ttl=128 time=0.171 ms
64 bytes from 10.3.3.210: icmp_seq=303 ttl=128 time=0.184 ms
64 bytes from 10.3.3.210: icmp_seq=304 ttl=128 time=0.229 ms
64 bytes from 10.3.3.210: icmp_seq=305 ttl=128 time=0.206 ms
64 bytes from 10.3.3.210: icmp_seq=306 ttl=128 time=0.278 ms
64 bytes from 10.3.3.210: icmp_seq=307 ttl=128 time=0.143 ms
64 bytes from 10.3.3.210: icmp_seq=308 ttl=128 time=0.229 ms
64 bytes from 10.3.3.210: icmp_seq=309 ttl=128 time=0.198 ms
From 10.3.3.165 icmp_seq=335 Destination Host Unreachable
From 10.3.3.165 icmp_seq=336 Destination Host Unreachable
From 10.3.3.165 icmp_seq=339 Destination Host Unreachable
From 10.3.3.165 icmp_seq=342 Destination Host Unreachable
From 10.3.3.165 icmp_seq=343 Destination Host Unreachable
From 10.3.3.165 icmp_seq=344 Destination Host Unreachable
[...]

As you see the "Link" seems to be on and than off repeatedly. I don't know why from the moment. I'm not modifying anything on my network setup (the LAN cable or anything like that).
I don't know why the ping stops working and will not work again even if the Serial monitor is telling the LINK is ON.
Let me know as soon as you can and thank you so much for your help and support.
bests
na
PS: I've posted a similar question on the Arduino forum but I had no way of understanding what kind of problem is this --> link
edit 11/02/2021
I've written a new code sketch to always print the status of the link. Here it is.
    /* NET stuff ********************************************/
    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    EthernetUDP Udp;

    IPAddress ip(10, 3, 3, 210); // the Arduino's IP
    byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x83, 0xD5 };

    #define DELAY 1000

    // SETUP //////////////////////////////////////////////////////////////////
    void setup() {

      Serial.begin( 115200 );
      Serial.println("setup");

      // Ethernet and OSC utilities **************************
      Ethernet.begin(mac, ip);

      // Hardware status check
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield was not found.");
      }
      else if (Ethernet.hardwareStatus() == EthernetW5100) {
        Serial.println("W5100 Ethernet controller detected.");
      }
      else if (Ethernet.hardwareStatus() == EthernetW5200) {
        Serial.println("W5200 Ethernet controller detected.");
      }
      else if (Ethernet.hardwareStatus() == EthernetW5500) {
        Serial.println("W5500 Ethernet controller detected.");
      }

      //Tells you whether the link is active.
      // LinkOFF could indicate the Ethernet cable is unplugged or defective.
      if (Ethernet.linkStatus() == Unknown) {
        Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500.");
      }
      else if (Ethernet.linkStatus() == LinkON) {
        Serial.println("Link status: On");
      }
      else if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("Link status: Off");
      }

      while( Ethernet.linkStatus() == LinkOFF ) {
        Serial.println("\tplease connect the Ethernet cable");
        delay( DELAY );
      }
    }

    // LOOP ///////////////////////////////////////////////////////////////////
    void loop()
    {

      int LINK_STATUS = Ethernet.linkStatus();

      if ( LINK_STATUS == LinkOFF) {
        Serial.print("Ethernet link broken!\t");
        Serial.println("please connect the Ethernet cable");
        delay( DELAY );
        return;
      } else if( LINK_STATUS == Unknown ) {
        Serial.println("LINK_STATUS: Unknown");
        delay( DELAY );
        return;
      } else if( LINK_STATUS == LinkON ) {
        Serial.println("LOOP working as expected! (LINK_STATUS: ON)");
      }

      delay( DELAY );
    }

After a while, it gave me this output on the serial monitor (at the same time ping said "Destination Host Unreachable"):
[...]
10:57:21.207 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:22.203 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:23.200 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:24.197 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:25.195 -> Ethernet link broken!   please connect the Ethernet cable
10:57:26.192 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:27.188 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:28.186 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:29.216 -> Ethernet link broken!   please connect the Ethernet cable
10:57:30.213 -> Ethernet link broken!   please connect the Ethernet cable
10:57:31.210 -> Ethernet link broken!   please connect the Ethernet cable
10:57:32.207 -> Ethernet link broken!   please connect the Ethernet cable
10:57:33.204 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:34.202 -> Ethernet link broken!   please connect the Ethernet cable
10:57:35.198 -> Ethernet link broken!   please connect the Ethernet cable
10:57:36.194 -> Ethernet link broken!   please connect the Ethernet cable
10:57:37.224 -> Ethernet link broken!   please connect the Ethernet cable
10:57:38.221 -> Ethernet link broken!   please connect the Ethernet cable
10:57:39.219 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:40.216 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:41.213 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:42.210 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:43.207 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:44.236 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:45.232 -> Ethernet link broken!   please connect the Ethernet cable
10:57:46.228 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:47.225 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:48.222 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:49.218 -> Ethernet link broken!   please connect the Ethernet cable
10:57:50.216 -> Ethernet link broken!   please connect the Ethernet cable
10:57:51.212 -> Ethernet link broken!   please connect the Ethernet cable
10:57:52.242 -> Ethernet link broken!   please connect the Ethernet cable
10:57:53.239 -> Ethernet link broken!   please connect the Ethernet cable
10:57:54.235 -> Ethernet link broken!   please connect the Ethernet cable
10:57:55.231 -> Ethernet link broken!   please connect the Ethernet cable
10:57:56.227 -> Ethernet link broken!   please connect the Ethernet cable
[...]

Adding some new elements here.
I've also noticed that, sometimes, even if the LINK status is ON, the ping is not working. It is almost clear to me that the two things are completely uncorrelated.
I've made some experiments in changing also the MAC address (setting a MAC address which is different from the one I see on the label on the shield). The "wrong" MAC address seems not to be cause of problems.
Can it be that a MAC address misconfiguration on the Arduino firmware can make the things work the wrong way?
I've also made many attempts in disconnetting and re-connecting the ethernet cable to the shield without powering the Arduino off and I've experinced a series of different behaviours.
1A) disconnecting the ethernet cable:

Serial monitor prints: "Ethernet link broken! please connect the Ethernet cable"
ping stops;

1B) re-connecting the ethernet cable:

on the Serial monitor LinkOn and LinkOff alternate between themselves, then, "LOOP working as expected! (LINK_STATUS: ON)" becomes stable;
ping still prints "Destination Host Unreachable";

2) reset of the Arduino Board (not the reset on the shield)

Serial monitor: "LOOP working as expected! (LINK_STATUS: ON)"
ping works again;

3A) Trying to repeat the same procedure as before (1A). Disconnecting the Ethernet cable:

Serial monitor prints "Ethernet link broken!  please connect the Ethernet cable";
ping stops;

3B) re-connecting the ethernet cable:

on the Serial monitor LinkOn and LinkOff alternate between themselves, then, "LOOP working as expected! (LINK_STATUS: ON)" becomes stable;
ping works again (which is a different behaviour from before!!!);

This problem is really difficult for me to debug. It seems we have a lot of variables to take into consideration here, which are not under my control: if I repeat the same procedure again and again, behaviour changes.
I'm not sure if it depends on the board, on the W5500 chip, maybe on other things happening on the net. Is it possible?
I don't know how to write a code to be capable of detecting these malfunctions.
Thank you so much for your help.
na

when your code prints "LOOP working as expected!", the actual status is not indicated, except that it is not LinkOFF

I've had similar issues with the Ethernet V2 shield, which were probably caused by the (unused) SD Card interface on the Ethernet V2 shield interfering with Ethernet functionality (both use the SPI bus). I've solved this by explicitly disabling the SD Card interface CS (by setting pin 4 to high) at the start of my setup() code with:
#define SDSelect  4
pinMode (SDSelect, OUTPUT);
digitalWrite (SDSelect, HIGH); This solved my issues.

Thank you @StarCat for your tip!
I've tried this on a "defective" shield and, in fact, things seem to be going a little better.
Now the Serial monitor is always reporting the link status as ON (without strange ON - OFF - ON status switching).
But today, after two days of continuous "ping" of the Ethernet shield bymy laptop, the console tells me icmp_seq=10493 Destination Host Unreachable.
Ping works again if I do a manual reset of the Arduino.
Why? Is there a sort of buffer on the W5500 that fills up over time and, because of this, prevents the ping from working?

I've had similar issues with the Ethernet V2 shield, which were probably caused by the (unused) SD Card interface on the Ethernet V2 shield interfering with Ethernet functionality (both use the SPI bus).
From what I could see in the Ethernet Shield2 schematics, there is no pull-up on the signal controlling the SD card Chip Select (D4/SD_CS), which means an unitialized I/O pin on the Arduino side could potentially cause random noise on the SD CS input.
My solution was to explicitly disable the SD Card interface CS, by setting pin 4 to high at the start of my setup() code.
I used the following code:
#define SDSelect  4

... Other initialization code

setup() {
    pinMode (SDSelect, OUTPUT);
    digitalWrite (SDSelect, HIGH);

    ... Code continues ...

This solved my issues with random crashing. I realize that I can't remember if there was an SD card present in the slot at the time.


text:
Compiling Assembly Script in External EEPROM to Arduino Code
I'm working on a simple game console, and I'm planning to use a cartridge system using an EEPROM. I know that you can read and write data from an EEPROM, but can you compile the data into executable Arduino code, and vice versa? If the Arduino can do it, we can probably too, right?
Thanks in advance!

there is no such thing as "arduino code" when the microcontroller executes it

have a look at forth programming language

@jsotola so is there some sort of compiler that turns arduino code into EEPROM code, and vice versa?

the microcontroller executes machine code ... in simple terms, the machine code is generated by the C++ compiler and loaded into the arduino ... the reason that i suggested forth is because forth is an interpretter that runs on the arduino ... it could possibly execute code originating from an EEPROM

@jsotola I see. I would use that, but I am using libraries to control the screen. I doubt that be converted into Forth, so that's my issue. I suppose I could control the screen manually, but it seems like a lot of work.

yes it would be a learning curve ... you did not describe your project, so it was unclear what component would need to be controlled

My project is basically a joystick connected to an LCD screen. So far I've just gotten a square to move around.
Here is the LCD screen I am using:
LCD Screen

I would suggest you investigate a different micro with external addressing or one that loads its code from an external memory such as flash like the ESP32s do.


text:
Trying to interface E18-D80NK sensor but the output is always one - what to do?
I'm trying to use a E18-D80NK but the output is always 1
Referring to the above link. I am facing the same problem. But unfortunately there is no solution in the given link. My code goes as follows:
#define SENSOR 2 // define pint 2 for sensor
void setup() {
  Serial.begin(9600);// setup Serial Monitor to display information
  pinMode(SENSOR, INPUT_PULLUP);// define pin as Input  sensor
}

void loop() {

  int L =digitalRead(SENSOR);// read the sensor

      if(L == 0){
    Serial.println(" Obstacle detected");

     }else{

     Serial.println("  === All clear");

     }
  delay(500);

}

Wiring:
Brown = 5V
Black = INPUT
Blue = Gnd

This is always giving me '=== All clear' as output. Also, would like to mention that, I bought a new sensor recently. Now i doubt is it a defective piece.
Could you please help.

your post needs to be self-contained ... the linked post could get deleted

Try connecting the sensor's power and measure the voltage of the input pin (disconnected from the arduino) with a voltmeter. If that works, then your sensor is good. Try then with the pullup disabled.

the datasheet has the pullup resistor incorrectly connected ... the note next to the wire color chart is correct ... you are using internal pullup, so you do not need an external resistor

please remove the ir tag ... your question is not about IR

Thank you, jsotola for your correction and reply. I tried what you suggested still no results.

Thank you, Mat for you reply. I just want a little clarification. I did not understand, what do you mean by 'sensor's power'? However, I simply tried with pullup disabled, but did not work.


text:
ESP32 ROS unable to sync
I am trying the example ros arduino publisher using an ESP32 Dev Module.
When I try to connect using rosserial I get "Uable to sync" error.
I have tried using different baud rates, 115200, 57600 and 9600
None of them worked. I clicked on the serial port monitor of the arduino IDE by mistake and saw this message:
Rebooting...
ets Jul 29 2019 12:21:46

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9232
load:0x40080400,len:6400
entry 0x400806a8

Not sure what to make out of the above error.
What am I doing wrong?
Thanks in advance.

That's not an error. That's just the normal boot sequence.

This message keeps on repeating itself. Does this mean it keeps on rebooting?

Sounds like it, yes. It's a software reboot, so some code is telling it to reboot.

It's a standard code, what can go wrong with that?


text:
Error trying to simulate temperature dynamically
I'm trying to simulate dynamic temperature using a small set of data with ESP32. I've just realized that the relay doesn't change the status if there is some variation of the temperature upper or lower the threshold.
If the temperature starts below the modeled temperature, the relay will turn on but, once it reaches the model's temperature or exceeds it, the status doesn't change, and the system will warm up till the next model.
Am I missing something in my code?
#include <OneWire.h>
#include <DallasTemperature.h>
#include <NTPClient.h>
#include <WiFi.h>
#include <WiFiUdp.h>

WiFiUDP ntpUDP;

NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 7200, 60000); //UTC+1 (Europe)

unsigned long current_time;

#define WIFI_AP "xxxxx"
#define WIFI_PASSWORD "xxxxx"
//WiFi SETUP
WiFiClient wifiClient;
int status = WL_IDLE_STATUS;
unsigned long lastSend;

const int oneWireBus1 = 0;
OneWire oneWire1 (oneWireBus1);
DallasTemperature sensors1 (&oneWire1);

const int relay1 = 02;

struct SetPoint {
  unsigned long time;
  float temperature;
};

#define DATA_SIZE  17

SetPoint scen1[DATA_SIZE] = {
  {1622652330,26.97},//18h
  {1622652390,25.62},
  {1622678400,24.87},
  {1622689200,24.16},
  {1622700000,23.86},
  {1622710800,25.17},
  {1622721600,26.41},
  {1622732400,27.22},
  {1622743200,26.78},
  {1622754000,25.83},
  {1622764800,25.1},
  {1622775600,24.6},
  {1622786400,24.24},
  {1622797200,26.81},
  {1622808000,29.35},
  {1622818800,29.38},
  {1622829600,30.5}
};

unsigned int pos = 0;

void setup() {
  Serial.begin(115200);
  sensors1.begin();
  pinMode(relay1, OUTPUT);
  InitWiFi();
  lastSend = 0;
  timeClient.begin();

void loop() {

  sensors1.requestTemperatures();
  float temperature1 = sensors1.getTempCByIndex(0);

  timeClient.update();

  long current_time =  timeClient.getEpochTime();

  if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
    if (temperature1 < scen1[pos].temperature) {
      digitalWrite (relay1, HIGH);
    }
    else if (temperature1 > scen1[pos].temperature) {
      digitalWrite (relay1, LOW);
    }
    pos++;
  }

  Serial.println(timeClient.getEpochTime());
  Serial.println(timeClient.getFormattedTime());
  Serial.println(pos);
  Serial.println(scen1[pos].temperature);
  Serial.println(scen1[pos-1].temperature);
  Serial.print("Temperature Censius - Sensor 1: ");
  Serial.print(temperature1);
  Serial.println(" ºC ");
  delay(3000);

}

(UPDATE)
Replacing the first if with while doesn't change anything.
The code works when taking if / else if out of nested if, but in this case I'm not able to increase time (the pos++ is also commented), and define limits according to the array size.
//  if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
    if ((temperature1 < scen1[pos].temperature)&& (current_time >= scen1[pos].time)) {
      digitalWrite (relay1, HIGH);
    }
    else if ((temperature1 > scen1[pos].temperature)&&(current_time >= scen1[pos].time)) {
      digitalWrite (relay1, LOW);
    }
//    pos++;
//  }

Tried changing if with while at while (pos < DATA_SIZE && current_time >= scen1[pos].time). But no change

The else if can just be an else. I'd start by making sure if if statement is being entered, then sanity-checking the two temperatures in the comparison. might also be beneficial to set up a test rig that compresses time and fakes the sensor data.

Thank you @DaveNewton. Yes, changed the else if using just else but seems to work likewise. Also, compressing time (in my case I set up an interval of 1 minute and 2 minutes), the relay doesn't' t change with simulated temp data.

So I think dumping out temperature1 and scen1[pos].temperature would be a good idea to sanity-check all assumptions. There's nothing obvious jumping out at me at the moment. (Changing from else if to else wasn't a fix, just a simplification.) I'd normalize all time values to unsigned long (you're currently mixing long and unsigned long comparisons, but the high bit isn't set, so shouldn't matter.

I've managed discarding the if (pos < DATA_SIZE && current_time >= scen1[pos].time) and using just if and if else/else. I kept both temperature1 and scen1[pos].temperature and the loop is working ok.
So, I could identify where is the issue. Obviously I have to see now how to add a statement/loop for time

I'm not sure what you just said, but if you're comparing hard-coded times against an actual time, you might be better off having only time offsets in scen1.time and adding a known "real"-time offset so they're in the future. It's not super-clear to me what you're trying to do here, but if you're trying to test something then I wouldn't be using anything "real" other than a simple on-board time difference check.

Thanks, @DaveNewton. Sorry I wasn't' t clear. Just updated the post with the previous info, so it is now easier to show how I tested and what is the current issue.

So the time comparison is likely failing (or it's blowing through the loop really fast if the time is always >=). Hence dumpling out the comparison values to check assumptions.

I have to remove the pos++ from if statement to have digitalWrite working again according to captured temperature:
  if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
    if (temperature1 < scen1[pos].temperature) {
    digitalWrite (relay1, HIGH);
    }
    else if (temperature1 > scen1[pos].temperature) {
    digitalWrite (relay1, LOW);
    }
   }

Obviously this isn't updating time and the system gets stuck at time 0 of the array.
(UPDATE)
As well observed by Dave Newton, the previous observation is pointless to really fix the problem.
The problem was fixed taking the if statement that control the relay from inside the one controlling the time.
Now I can simulate a time interval defined with the array and use the temperature (also present in the array) to turn on/off the relay that controls the heater and simulates environment temperature:
First I created a function that will work as a thermostat:
void set_thermostat() {
  sensors1.requestTemperatures();
  float temperature1 = sensors1.getTempCByIndex(0);

  if (temperature1 < scen1[pos].temperature) {
    digitalWrite (relay1, HIGH);
  }
  else if (temperature1 > scen1[pos].temperature) {
    digitalWrite (relay1, LOW);
  }
}

Then I can it at the loop function, outside the statement that increases the time, based on the one defined by the array:
  if (pos < DATA_SIZE && current_time >= scen1[pos].times) {
    pos++;
  }

  set_thermostat();

This reproduces exactly what I've been looking for, with real-time control of the temperature comparing the environmental one with the model.

So it's blowing through the loop, which still means the time comparison is failing. Hence the repeated suggestion to check your assumptions by looking at the times. There's zero way we can help you without knowing what the data values are that are being compared, and you won't share them. This isn't an answer to the problem, it's a work-around that breaks the program.

Thanks. Yes, I checked the times. I compared the current_time and the scen1[pos].time. Simplified the code and checked if current_time is equal or bigger of scen1[pos].time. The output is right (using different times and intervals). So I would expect the statement working fine. I don' t know the checking of assumptions means something else of that I've already done.

My point was that we cannot check your assumptions or provide any meaningful input without knowing what's actually happening. Comparisons generally Just Work, so if removing pos++ "fixes" it (ergo pos < DATA_SIZE forever) it means there's an issue in the time comparison. But we cannot see the any of the values being compared, so all we can do is guess.

I see and agree. Have updated the reply with the solution (this one really reproducing what I want).


text:
Parsing read SD file into 2 variables
Recently I started some tests controlling water heater with temperature sensor data as described in detail here
So far I've been testing a small dataset to control water temperature that is quite easy to write down by myself.
#include <NTPClient.h>
#include <WiFi.h>
#include <WiFiUdp.h>

//WiFi Conf
const char *ssid     = "ssid_addr";
const char *password = "wifi_password";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
unsigned long current_time;

// Sensors Conf (fixed value just to test relay response)
float temperature = 30.5;

//Relay Conf
const int relay = 26;

struct SetPoint {
  unsigned long time;
  float temperature;
};

#define DATA_SIZE  8

SetPoint scen1[DATA_SIZE] = {
  {1616952559, 32.4},
  {1616952739, 10.2},
  {1616952859, 10.4},
  {1616952867, 40.2},
  {1616952927, 20.4},
  {1616952928, 35.2},
  {1616952945, 22.4},
  {1616952947, 28.2}
  };

unsigned int pos = 0;

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

  pinMode(relay, OUTPUT);

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

  timeClient.begin();

}

void loop() {
  timeClient.update();

  long current_time =  timeClient.getEpochTime();

  if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
    set_thermostat(/*data[pos].temperature, temperature*/);
    pos++;
  }

  Serial.println(timeClient.getEpochTime());
  Serial.println(timeClient.getFormattedTime());
  Serial.println(pos);
  delay(3000);

}

void set_thermostat() {
  if (temperature < scen1[pos].temperature) {
    digitalWrite (relay, HIGH);
  }
  else if (temperature > scen1[pos].temperature) {
    digitalWrite (relay, LOW);
  }
}

But now I'm planning to use a larger file with different datapoints and an option is to store them in a sdcard and, then, the microcontroller parses each line to control the temperature with an interval of three hours.
There will be about 720 lines with the following structure ("Scen" is the temperature simulation scenarios that will be the reference to turn the relays on or off):
    Time,UNIX,Scen1,Scen2,Scen3
    21/04/2021 00:00:00,1618963200,"27.45","29.01","30.85"
    21/04/2021 21:00:00,1619038800,"26.16","27.82","29.75"
    21/04/2021 06:00:00,1618984800,"25.28","26.83","29.02"
    21/04/2021 09:00:00,1618995600,"24.62","26.49","28.51"
    21/04/2021 12:00:00,1619006400,"27.19","29.47","29.53"
    21/04/2021 15:00:00,1619017200,"30.65","34.07","30.50"
    21/04/2021 18:00:00,1619028000,"31.87","35.78","31.78"
    21/04/2021 21:00:00,1619038800,"30.43","35.20","30.88"
    22/04/2021 00:00:00,1619049600,"28.45","31.86","29.47"

The problem is that it is hard to find out how to parse data from the file into two variables (UNIX Time and temperature), for each temperature scenario, as used here:
struct SetPoint {
  unsigned long time;
  float temperature;
};

#define DATA_SIZE  8

//scenario 1 array
SetPoint scen1[DATA_SIZE] = {
  {1616952559, 32.4},
  {1616952739, 10.2},
  {1616952859, 10.4},
  {1616952867, 40.2},
  {1616952927, 20.4},
  {1616952928, 35.2},
  {1616952945, 22.4},
  {1616952947, 28.2}
  };

Is there an effective way to get what I'm looking for?

You can read the file line by line (surely that is rather easy to find with google). Then you can use strtok() on the resulting c-string (please avoid the String class). Note that strtok alters the c-string. Please try googling for a strtok tutorial and try it out. Maybe that is already what you need. (strtok is a bit difficult to understand at first, but it is a really good way to tokenize a string)

Thanks! Yeah, I managed to read line by line and today will go deep on strtok(). I update this question when I advance on it.


text:
Unable To Upload Source Code on Arduino UNO(Windows 11)
I was trying to upload the source code of a project to the Arduino UNO and this is the error that I keep on receiving.
After I closed and reopened it again, the Port option is gray. I tried everything (installing new drivers, uninstalling it) but nothing works. This board works on my PC (Win 10) but doesn't work on my laptop (Win 11).
avrdude: ser_open(): can't set com-state for "\\.\com3" an error occurred while uploading the sketch.

Is it a genuine Arduino UNO or a Chinese clone? If a clone, what USB chip does it have on the board?

@Majenko It's a Chinese clone with an Atmega328p chip

That's the MCU. What's the USB chip? Is it an ATMega16UI2 or a CH340G?

@Majenko It's Atmega16U2.


text:
ESP32 ADC <-> WiFi issue
I'm using the ESP32's ADC1 (not ADC2, which conflicts with WiFi functionality) to capture some analog data received at IO36 (an ADC1 port).
As soon as I uncomment the WiFi.mode(WIFI_AP_STA) line (even when the WiFi.begin() line is still commented out), analog readings go crazy!
Some side notes:

The hardware that processes the input signal to make it suitable for the ESP32 analog input uses the same power source as the ESP32 module.
A 100 μF SMD capacitor is connected to the source line of the ESP32 module just beside it to lessen the impact of its power consumption ripples on other devices.
I tried adc1_get_raw, which made no difference.
I tried this code on another ESP32 module; it also showed a huge difference in ADC1 readings before and after uncommenting WiFi.mode(WIFI_AP_STA).
Using root APIs such as esp_wifi_init & esp_wifi_set_mode & esp_wifi_start instead of Arduino wrappers like WiFi.mode didn't help.

New clue: Apparently the issue is with the WiFi Access Point mode (i.e. WIFI_AP), because setting Wi-Fi to Station mode (i.e. WIFI_STA) doesn't cause this issue.
In general anything related to WiFi causes the ADC to get unstable. No matter which ESP32 board you use, you could simply serial plot any ADC1 channel before and after the WiFi initialization command, even with floating ADC1 pins you can see the difference.

#include <WiFi.h>
float R = 0;

void setup() {
  Serial.begin(500000);
  // WiFi.mode(WIFI_AP_STA);
  // uncommenting this line analogread goes crazy, even while the following line is still commented out
  // WiFi.begin();
  analogSetAttenuation(ADC_0db);
}

void loop() {
  R = analogRead(36);
  Serial.println(R/12.21);
}

THANKS FOR ALL THOSE COMMENTS AND ELABORATIONS !!! I think I have found the answer HERE

I've just had the same problem. I just put all of the WIFI connecting code into a function, read the ADC2 data then called the function to send, ending with WIFI.mode(WIFI_OFF) to shut down the WIFI, read the data then started it all over again. I'm using ESPNOW so don't have to panic about hooking up to my network which would obviously take longer. With ESPNOW, the data is sent regardless and I have it sending every few seconds which is fine for me. I did try putting the connection code into loop, but it kept restarting the board. I've seen plenty of other stuff online about that. Putting it into a function seems to get around that.


text:
Use a simple LED with no digital pins to spare
Problem: I've made a circuit consisting of an 8x8 led matrix, which uses all of the digital pins on the Arduino UNO board, and I want to add an LED too it.
I tried looking around the internet but so far, I have not seen any solution on how to use a simple LED with no digital pins to spare.
So I ask, is it possible to connect an LED with no leftover digital pins? I just want to be able to turn the LED on and off.
Thanks.

Just found this:
https://forum.arduino.cc/index.php?topic=311099.0
Turns out you can use the analog pins of an Arduino UNO using this:
pinMode(A1,OUTPUT);
digitalWrite(A1,HIGH);

You just have to list it as an analog pin. Seems to be working, don't think there are any downsides, as far as I see.

Yup.  Though make sure you see the note there by CrossRoads regarding A6 and A7 on SMT based UNO (and other SMT 328P Arduino).

In a couple days time you'll be able to accept your own answer, and probably should assuming someone else doesn't provide another you like better.

Ok, yeah I'll do that later, unless I get a better answer as you said.


text:
How to transfer constants from one loop to next one
#include "VernierLib.h"

VernierLib Vernier;

#define led 13

float sensorReading;

void setup() {
  Serial.begin(9600);
  Serial.println(Vernier.sensorName());
  Vernier.autoID();
}

void loop() {
  float base_temp;
  base_temp = Serial.parseFloat();
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}

That's the code, I have a question. When I write the temperature to Serial, it lasts only until the end of one loop.
How to keep the same temperature in the next loop?

To keep the variable value through different iterations of a function, declare it as static. Though your code will overwrite that value, when you use Serial.parseFloat(). Though that is a programming question, not an Arduino question

@chrisl thanks, but i would like to keep the same constant for like 2, 3 loops and than change it again. How would i do that?

It is unclear to me, what exactly you mean. And why 2 or 3 loops? What are you trying to achieve?

@chrisl , i'd like to achieve that i could anytime change the constant temperature, and when i change it should stay the same until i change it again.

constants cannot be changed ... use a variable to hold changeable data

Also asked here: https://stackoverflow.com/questions/65512883/how-do-i-change-variable-after-each-2-3-loops . Please don't crosspost.

In addition to @chrisl comment, you need to use code such as if ( Serial.available() ) { base_temp = Serial.parseFloat(); }.

There are two things here you need to consider.
First is that your variable is a "local" variable. This kind of variable is created at the start of each iteration, then discarded at the end of that iteration.
There's two things you can do to "fix" this:

Make the variable "global" - that is, move the definition out of loop() to the "global" scope (put it at the top of your program). It is then only created once and never discarded.
Make the variable "static" - that is, add the static keyword to it. It is then created on the first iteration only, and never discarded.

The second thing to consider is that you have no "There is no value" concept. Every iteration you parse a new float, whether there is one there or not. And if there isn't one then it just gives you 0. So you need to come up with some way of saying "I have entered a number, so parse it". The simplest thing is just to assume that all values of 0 are "no number entered", but that of course prevents you ever entering 0 as a valid input.

A static variable is created before main() (or setup() on Arduinos) runs. It is initialized with a given explicit value or zeroed without.

@thebusybee Technically, yes, that's right. But the effect, as far as an Arduino user is concerned, is that it is created once on first run and stays around afterwards. Arduino users really don't need to know such technical minutiae just yet.

Something like this should work (untested, but you get the idea; the explanation is in the comments):
void loop() {
  static float base_temp = 21;     // Or whatever default starting value you want
  static float t = 0;              // A temporary store for Serial.parseFloat()

  t = Serial.parseFloat();         // Read t; if Serial.parseFloat() times out, it will return 0.00
  if (t != 0.00) {                 // If something else than 0.00 is in t
    base_temp = t;                 // Update base_temp with t
  }                                // Note: You can't set base_temp to exactly 0.00 with this set-up
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}

In this code 0.00 means that "no value was entered", so you can't set the temperature to exactly 0.00 with this set-up; 0.01 should work fine, though.


text:
Node MCU code is stuck in while (WiFi.status() != WL_CONNECTED)
I am using the Node MCu V3 board ESP8266MOD
Board Manager Version: 2.7.4
Arduino IDE: 1.8.12
My code is stuck in the while (WiFi.status() != WL_CONNECTED)
Here is code:
#include <ESP8266WiFi.h>        // Include the Wi-Fi library

const char* ssid = "ESP8266TestNet";  // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = "ESP8266Test"; // The password of the Wi-Fi network

void setup() {
  Serial.begin(9600); // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  WiFi.begin(ssid, password); // Connect to the network

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

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }
  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
}

void loop() {
  delay(10000);
  Serial.println(WiFi.status());
}

After downloading the code above for setup connection I am using mobile WiFi for connection.
In the mobile settings I can see the WiFi is connected to the ESP Board but when I monitor the Serial it seems that the code is stuck in the while loop.
If I comment out the while loop the board is giving a WDT reset.
Any ideas? I have been stuck for a long time.
Here I have attached the tools setting of the Arduino IDE:

Are you on a breadboard? Those can interfer badly with wifi, though it's weird that you see the esp connect to the access point... maybe, the connection fails right after it has been established and within the one second interval you're polling the wifi state (smartphones wifi settings are typically not updated immediately). You could try to remove the 1000ms delay for a test

Make sure the SSID and password match your WiFi Access point. 2) Make sure your WiFI Access Point is operating on 2.4GHz, not on 5GHz band because ESP only supports 2.4GHz.

"I can see the WiFi is connected to the ESP Board"  - what does that mean? Does your ESP run as Access Point? And if yes, why? NB: The WDT reset occurs because in "delay(10000)" the WDT is not fed, and Soft WDT timeout is much less than 10 seconds.

the settings in Tool are not right. select NodeMcu 1.0


text:
BLDC geared motor with encoder - How to wire the encoder? (6 wires)
I am quite a newbie to Arduino and currently stuck with an encoder.
I have a BLDC geared motor with encoder, all I want to do is to get values from the encoder.
There are 6 wires: out A, out B, out Z, +V, 0V, FG. How should I wire the six of them correctly?
Encoder specification says 5 VDC is OK to power it, and I want to make a circuit to power an encoder using an Arduino Mega board.

It depends on what kind of encoder it is. You need to know if it is an absolute or incremental encoder. Is there a description, model number, or other information?

Encoder model name is e40h8-5000-3-n-5.

This should be in the documentation of the motor or encoder, and that is the first place to look.
If you don't have any documentation, here is my best guess:
ABZ suggests it is an incremental encoder with channel A and B for quadrature encoding (giving direction and speed), with Z as the index pulse for getting absolute position once every rotation. FG is most probably Frame Ground, or maybe be the Fault signal.
How you wire it all depends on what you want to do with it, but knowing what each signal is should make it easy enough.


text:
Code is not running, servo does not even spin
I am trying to run a program which works as follows:
An LDR is integrated in a box. A block is placed on top. This box can be rotated by a servo. The program is supposed to make the box turn until the block slides and lifts off from the LDR.
At that point the servo angle is stored and used to calculate the friction coefficient.
Finally, the answer to this calculation is printed on an LCD and the program repeats by first returning the box to the original state. The entire programs runs on an Arduino and an Arduino Lotus. Why doesn't the servo rotate?
//servo
#include <Servo.h>

Servo myservo;
int previous_angle = 0;
int angle = 0;

//lightsensor
int lightsensor = 0;
int LIGHT = 800;
int DARK = 940;

//LED screen
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
  Serial.begin(9600);
  myservo.attach(6);

  pinMode(lightsensor, INPUT);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  delay(100);
}

void loop() {
  int i = previous_angle;
  int lightStatus = analogRead(lightsensor);

  if (lightStatus >= DARK) {
    delay(300);

    while (int i = previous_angle) {
      i<=90;
      i = i+1;
      myservo.write(i);
      delay(45);
    };
  } else if (lightStatus < DARK) {
    for (int i = previous_angle; i>0;) {
      delay(300);
      int angle = tan(i);
      display.clearDisplay();
      display.setTextSize(1.5);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.println(angle);
      display.display();
      delay(300);

      myservo.write(0);
      delay(45);
    };
  }
}

In the future, please format your source code using the {} on this site.  As it was it was very difficult to follow your code.  Also, please include a schematic of how your motor is connected.

Question: Have you been able to make your motor run with just a simple program?  It's often helpful to start out simple and add things one step at a time.

For starters: this bit is a strange mixture of for and while syntax:
while (int i = previous_angle) {
  i <= 90;
  i = i + 1;
  myservo.write(i);
  delay(45);
};

It will compile, but probably not do what you want it to do. It should probably be:
for (int i=previous_angle; i<=90; i=i+1) {
  myservo.write(i);
  delay(45);
}

Also, previous_angle is never changed in your code after initialisation; it is always 0.
That also means that the for loop below will not do what you want (and that loop also doesn't increment i anywhere):
for (int i = previous_angle; i>0;)

There may be more; make the suggested changes first and see what happens.

If I change it I get an error when verifying the code 'expected ')' before ';' token'

I blame coffee underflow 8-). Answer edited.

Changing to a "for" does resolve the error, I will check whether the code also properly as needed thankyou


text:
Interrupts Within Critical Statements
I've redone a previous Arduino sketch I posted in which I was having trouble capturing encoder counts within critical statements, having no luck properly attaching and detaching interrupts.  I've studied various ISR sketches but haven't been able to produce anything that caters to my needs.
I now have a switch case in which a DC motor with CPR encoder correctly rotates back and forth between specified boundaries if it alone is in the void loop.  However, once enclosed within a critical statement (I want this action to occur only if a button is pressed), the DC motor continues to rotate only one direction.
I need assistance in where to properly attach and detach these interrupts and how to correctly pass the encoder value to the next action.  Below is what I've done so far and any help would greatly be appreciated.
#define enA 9
#define in1 6
#define in2 7

const int button1Pin = 8;

int button1State = 0;

volatile long temp, counter = 0;

long local_counter=counter;

enum {IdleState, ForwardState, BackwardState} State;

void setup() {

  Serial.begin(9600);

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  Serial.begin (9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  attachInterrupt(0, ai0, RISING);
  attachInterrupt(1, ai1, RISING);

  pinMode(button1Pin, INPUT);

  State = IdleState;
}

void loop() {

  button1State = digitalRead(button1Pin);

   if( counter != temp ){
   Serial.print("counter = ");
   Serial.print (counter);
   Serial.print("     local counter = ");
   Serial.println(local_counter);
   temp = counter;
   }

   //if (button1State == HIGH) {

          switch (State) {

              case IdleState:
                halt ();

              if (counter<2000)
                State = ForwardState;
              break;

              case ForwardState:
                clockwise();

              if (counter>=2000)
                State = BackwardState;
              break;

              case BackwardState:
                counterclockwise();

              if (counter <=0)
                State = ForwardState;
              break;

          } // end switch
   //  }

}

void ai0() {
  if(digitalRead(3)==LOW) {
  counter++;
  }else{
  counter--;
  }
  }

void ai1() {
  if(digitalRead(2)==LOW) {
  counter--;
  }else{
  counter++;
  }
  }

void clockwise (){
    analogWrite(enA, 255);
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
  }

void counterclockwise () {
    analogWrite(enA, 255);
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

void halt () {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
}

An explanation of my setup is as follows:
My button is a tactile button on breadboard (connected to pin 8 of an Arduino Uno),  with 5V supply from Arduino. Pins 6 of the Arduino is connected input 1 of the L298N motor driver, pin 7 of Arduino connected to input 2 of the motor driver, and pin 9 of the Adruino connected to the enable of the motor driver.  Them motor driver is being supplied by an external 12V supply which is also power the 12V DC geared motor with encoder.  The encoder outputs are connected to pin 2 and 3 of the Arduino.

what is a critical statement?

For halt shouldn’t you turn that Enable pin back off?

Setting in1 LOW and on2 HIGH in halt() doesn't seem to be correct

The way I see it, the state should go back to IdleState if the button is not pressed. Just putting the switch-case inside the if-statement will result in the motor continue rotating the way it was rotating when the button is released.
if (button1State == LOW ) {
  State = IdleState;
  counter=2000;
}
else if(button1State==HIGH && State==IdleState ) {
  counter = 0;
}

switch(State) {
  ...

Depending on what it is you want to do, you might want to add another state (say StoppedState), where the motors are halted, just like IdleState, but you don't get a state change if counter<2000. Then you don't have to change the counter variable.
if (button1State == LOW ) {
  State = StoppedState;
}
else if(button1State==HIGH && State==StoppedState ) {
  State = IdleState;
}

switch(State) {
  case StoppedState:
    halt ();
    break;
  case IdleState:
    ...

PS please indent the if statements inside you cases.

I actually want it to continuously rotate back and forth, even after the button is depressed.  Later, I plan to add buttons to stop and to rotate in one designated direction. So if  I want this continuous back and forth motion to continue after the button is depressed, should the first IF statement (button == LOW) be altered?  I've tried removing it but that doesn't do the trick.

What part of your code would make it stop and go the other way?  Is that inside an if statement that only executes if the button is pressed?  Then it will only happen if button isn’t pressed.  Let button press choose a state.  Let the switch run all the time.

I suppose it would have to be the first part of the IF statement for when the button is LOW, being that "counter=2000", the condition for counterclockwise motion. I've tried changing or removing that condition without any success. Should I be focusing more on Gerben's second suggestion?  It seems to have a similar behavior as the first in my attempts.

I'm confused. Do you want to motor to do nothing, until the button is pressed? And then go back and forth no matter whether the button is pressed or not? If that's the case, go with the second solution, but leave out the State = StoppedState; in the if statement, and put that in the setup (instead of State = IdleState).

Will you marry me Gerben???!!! That's exactly what I wanted and it worked!!!  But the honeymoon is short lived  I added a second button to stop, but all it does is rotate counterclockwise when pressed:
      if(button2State==HIGH){
          State = StoppedState;
      }

Will the switch case not work with this setup?

The code you've provided looks okay, so I'm not sure what the problem is. Please post your code, as I'm still a bit confused. And you marriage proposal makes me even more confused q-;.  I think it would be best to create a new question.

Sorry, I'm a confusing person by nature, but there was also a problem with my code for halt (), which I corrected and now my second button correctly stops the motor.  But I've added a third button, when pressed, I want the motor to move continuously clockwise, so I added this:  if(button3State==HIGH){clockwise();} but it doesn't do anything.  Should I create another state or void function? <-- but that seems necessary to me.  I can indeed post this as another question if you feel it best.

Seems like you fixed our honeymoon issue. For the third problem use while(button3State==HIGH){clockwise();} instead. That way the switch statement isn't called right after it, and negate the clockwise rotation. Adding a separate state would also work, and will probably result in nicer and easier to read code.

That did work; however, it doesn't break from button 3 action when button 1 or 2 is pressed.  I also tried this:  while(button3State==HIGH&&button1State==LOW&&button2State==LOW){
clockwise();} but this really doesn't change anything.  We're so close!!!

I added another state, and button 3 works, but then button 1 no longer works AFTER button 3 is pressed (button 2 works at anytime).

Nevermind, I figured it out....and by "I" I mean 99% StackExchange and 1% me.  I had an issue with the counter value, it needed to be reset to 0 before button 1 could properly work.  I can't thank you all enough, for now we can go our separate ways...I guess we're getting divorced :(

It was 100% that searched SE. So "You" solved it 100% yourself. I guess it wasn't meant to be ;-p