text:
timer0_millis always returns 0
I am trying to make a simple debounce function as explained here but the condition if((millis()-timeCheck)>reboundDelay) is never met.
As you can see in my code below, I am trying to control a PWM with two push buttons. I am currently sending it on a LED.
With AS7 and vMicro I put some breakpoints and realized that timeCheck was stuck at 0 and was an unsigned int instead of the unsigned long I declared. With the debugger I looked inside of the millis() function and saw that timer0_millis wasn't increasing neither, stuck at 0.
Here is my short code (it's a sketch, it can surely be rewritten in a more efficient way) :
int PWM=9;
int dutyP=2;
int dutyM=3;
int duty=123;
bool stateP=0;
bool stateM=0;
bool prevStateP=0;
bool prevStateM=0;
unsigned long reboundDelay=500;
unsigned long timeCheck=millis();

void setup() {
  pinMode(PWM,OUTPUT);
  pinMode(dutyP,INPUT);
  pinMode(dutyM,INPUT);
}

void loop() {
  stateP=digitalRead(dutyP);
  stateM=digitalRead(dutyM);
  if(stateP != prevStateP || stateM != prevStateM) {
    timeCheck=millis();
  }
  if((millis() -  timeCheck) > reboundDelay) {
    if(stateP==1) {
      duty=duty+25;
    } else if(stateM==1) {
      duty=duty-25;
    }
    analogWrite(PWM,duty);
    prevStateP=stateP;
    prevStateM=stateM;
  }
}

And finally, the strange part. When I upload it on my Genuino Uno for like 30 seconds, the pushbuttons do nothing (it may be that the if works) and afterwards I can increase and decrease the duty cycle but without the delay that the condition should bring (the LED flashes really fast due to an overflow in analogWrite).
Any help is welcomed, the strange part is secondary to me but I would really like to make millis() work properly.

bool variables have two possible values true and false.  1 and 0 are technically ints, you might be OK but I wouldn't do it.  You should also check for wrap on duty.

Would it be possible to just do this loop?  loop(){Serial.println(millis());delay(500);} If you are right about millis not moving then this will prove it.  There may be something in the debuggers that interfere with millis.

I tried to but nothing happen in the serial monitor despite :
Port closed
Uploading to I/O board
Opening port
Port open

Should I write stateP==true or false instead of 1 or 0 ?

Did you try with an empty project?  If so you have a bigger problem :(

true == 1 false == 0, yes

Trying in a new project right away.

Do this on an Arduino Uno / Atmel ATmega328P.   There are many different kinds of Arduino boards with many processors.  They all do not work perfectly with respect to their boot loader software and SDK implemtations.  Also, I would not define the type and call a method to assign a value to the type outside of a method.  I would define "timeCheck" then assign it a value within the methods.

Sorry for the wait AS7 crashed... I made a new projet just inserted your lines in the loop function and started debugger on the .ino file... and it worked. Didn't I had to add the .cpp file before I could debug ? Anyway, there is still no sign of millis in the serial monitor.

@st2000 I didn't understood what you meant in the first part of your comment, should I configure something in a certain way ? I am using an genuino uno rev3 with an ATMega328P.
For the second part, the unsigned long timeCheck=millis(); it was a wild try, I forgot to clean it up before posting here. Thank you.

I tried in multiple ways, Serial.println() doesn't work at all. I might as well install AS6.2 and see if it works better.

There are many types of Arduinos.   And many use totally different processors.  The SDKs and Arduino boot loader quality for some are questionable.  You did not specify your Arduino HW.  And now-a-days, because of this problem, that is important.  But I see you are using an ATMega328P.  The same processor that is on a real Arduino Uno.  So if there is special hardware used to run the timer is should work.  I would next suggest trying one of the short example mills programs found at the official Arduino site.  Then work back to your program from there.

I think there is just a logic error that doesn't immediately jump out: When the button state is changed, it will always set timeCheck equal to millis(). For instance, as long as you are pressing "P", stateP will not be equal to prevStateP and so "timeCheck=millis()" will executed everytime thru the loop, so the difference will never reach 500.
if(stateP != prevStateP || stateM != prevStateM){
    timeCheck=millis();
}

Should be something like:
if(stateP == prevStateP && stateM == prevStateM){
    timeCheck = millis();
}

This will continually keep timeCheck = millis() until either button is pressed. Once the button is pressed, timeCheck will remain at the value of millis() read just before the press, until the debounce value is reached (unless noise/bounce and not a real press, or button is released early as 500ms is a relatively long time).
This is probably the simplest modification to the code I can come up with. Hope it helps.

I would suggest a few things:
1) comment on your code -> lay out the basic logic so that you and others can help you debug it;
2) use brackets liberally -> don't rely on memory (=faulty) on the order of operations. instead, define it explicitly;
3) check your logic -> make sure that your code does what you want it to do;
4) pay attention to data type: 8-bit vs. 16-bit, etc.
5) modularize your code -> this allows more efficient debugging and code reusing.
for example, your code can be simply described as
  button_state = read_button(); //read button state, with debouncing
  if (button_state = BUTTON_UP) pwminc_dc(pwm_dc); //increase duty cycle, with boundary checking
  if (button_state = BUTTON_DOWN) pwmdec_dc(pwm_dc); //decrement duty cycle, with boundary checking

with the code modularized, you just need to worry about getting individual pieces right.


text:
What do the numbers behind lcd (0x27) mean?
I can't seem to figure out what the numbers after 0x27 mean. I understand that 0x27 stands for the I2C address and POSITIVE stands for the backlight, but what do the other number mean?

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE)

Which LiquidCrystal_I2C library are you using? Usually you would call the constructor like this: LiquidCrystal_I2C lcd(0x27, LCD columns, LCD rows);.

My guess is they refer to the pins on the IO expander to use for the different pin functions. Without knowing what library you are using, or what LCD display and interface board you have, it's impossible to say.

A “4x20” LCD is one with 4 rows and 20 columns. You can guess a “0x27” has 0 rows and 27 columns. ;-)

It's a bit late, but I'm using Newliquidcrystal_1.3.5. I don't think it stands for columns x rows. I tried 16, 2 and the LCD didn't work.

Assuming You're using the same LCD library I'm using, there is a longer form of the constructor that takes pin assignments for the different pins on the I2C module, as Majenko says.
I'm at work, so I don't have access to my code, but your constructor looks a whole lot like the one I use for my module, which has non-standard pin assignment. (I got my LCD modules from oddWires, and they came without documentation. I had to do quite a bit of detective work to figure out how to make them work.)
EDIT
I use the Newliquidcrystal_1.3.5 library in my project, to interface the above-mentioned oddWires I2C LCD display. That library has various constructors, one of which takes all the parameters you list. Those extra numbers indicate the pins that connect to the I2C module.
My oddWires LCDs need exactly the settings you list in the constructor. Your milage may vary.
The long form is defined in the library header with
LiquidCrystal_I2C(
    uint8_t lcd_Addr,
    uint8_t En,
    uint8_t Rw,
    uint8_t Rs,

    uint8_t d4,
    uint8_t d5,
    uint8_t d6,
    uint8_t d7,
    uint8_t backlighPin,
    t_backlighPol pol
);

From the naming of the parameters you can deduce most of them:

En is an enable line
Rw is a read/write line?
Rs is ?
d4-47 are the data pins
backlightPin is the pin that turns backlight on and off
pol indicates the backlight polarity (POSITIVE probably means pull the line high to enable the backlight.

source: Stack Exchange

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

sort: votes


text:
How to control an 12V 2A Car lamp using relay or MOSFET in Arduino
I am working with the project controlling an 25W 12V Car lamp. I have a 12V car battery. I want to control it with the Arduino using a relay or MOSFET.
Any suggestion for my project would be appreciated.

You do it the same way as any other kind of light control. "Car" makes no difference.

But arduino output draws only minimum amount of current for 25W 12v lamp the current rating should 1.75A how to boost up the current to make the lamp ON

You already answered that in your question - use a MOSFET or a relay.

You can use a RFP30N06LE mosfet. It can support up to 60V 30A
Here is a wiring schema

and one more doubt....is ground can be common for different current rated loads....Example i am using 12v car battery in that load side i have 5W and 21W lamps can i connect ground of these 2 common....because i am using ground switching for output....supply is directly given to all lamps...

Ground have to be common. It won't works if they are not connected each other

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


text:
How to write a more compact ANDed conditions with if statement?
I'm working on the rfid module and found an example that do it well. But it has a long testing the 5 bytes of the rfid received bytes, and I've tried to write it in a more compact way.
I did it with a for loop, but how to AND the conditions of the if statement?
How to change this:
if(bt0[cnt-1] == rfid.serNum[0] &&
   bt1[cnt-1] == rfid.serNum[1] &&
   bt2[cnt-1] == rfid.serNum[2] &&
   bt3[cnt-1] == rfid.serNum[3] &&
   bt4[cnt-1] == rfid.serNum[4]){
   lcd.clear();
   lcd.print("card accepted");
   digitalWrite(green_led,HIGH);
   digitalWrite(red_led,LOW);
 }
 else{
    lcd.clear();
    lcd.print("card denied");
    digitalWrite(green_led,LOW);
    digitalWrite(red_led,HIGH);
}

To something like this:
    for(byte i=0;i<MXCD;i++){
      if(bt[i] == rfid.serNum[i%5]){
        cnt++;
      }
    }
    if(cnt==5){
      lcd.clear();
      lcd.print("card accepted");
      digitalWrite(green_led,HIGH);
      digitalWrite(red_led,LOW);
      cnt = 0;
    }
    else{
      lcd.clear();
      lcd.print("card denied");
      digitalWrite(green_led,LOW);
      digitalWrite(red_led,HIGH);
      cnt = 0;
    }

In this way, I did it with 'cnt' variable to count the number of successful matched bytes then test of the number is equal to 5.
Is there a better way than this one ?
Thanks for any comments or suggestions :)

Hint: There is a standard C function for this, memcmp(). You would use it like, if (!memcmp(bt, rfid.serNum, 5)) .... Ref. http://www.cplusplus.com/reference/cstring/memcmp/

wow thanks !! this function actually isn't new to me, but I didn't thought of it and its usage at this situation ! thanks again man ..

@MikaelPatel you should post that as an answer so the OP can accept it.

Yes, you're right.

Perch Eagle and @MikaelPatel, I want to learn something out of this question and your accepted answer, but I do not understand how it works. You write you want to compare elements of five different arrays (bt0[], bt1[], … bt4[]) with elements of one array (rfid.serNum[]). As an answer you are fine with a comparison with a new array bt[]. To make this work there must be a relation between bt[] and bt0[], bt1[], … bt4[]. Where in your sketch is this done or is this naturally but only I cannot understand?

There is a standard C function for this, memcmp(). It performs a memory block compare and can be used like this:
if (!memcmp(bt, rfid.serNum, sizeof(bt))) {
  lcd.clear();
  lcd.print("card accepted");
  digitalWrite(green_led,HIGH);
  digitalWrite(red_led,LOW);
}
else {
  ...
}

Ref. http://www.cplusplus.com/reference/cstring/memcmp/

Yep, it works perfectly! Thank you dude ..

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


text:
ESP8266 connected to a HIGH pin and DPDT only works sometimes. Works everytime if connected to 3V3 pin
I have a Wemos D1 Mini hooked up to a DS2Y-S-DC3V DPDT switch.
When I have the coil ends are hooked up to a pin (D2) and ground, it will click when I set the pin HIGH. It should click again when it goes low, and then again with high, etc. But after while, it stops responding. Measuring the voltage while hooked up to the DPDT is 1.7 V.  When disconnected from the DPDT, the D2 pin and Ground voltage is as expected, 3.3V.
However, if I connect the DPDT terminals to the ESP's 3V3 pin and G, it works all day as many times as I wish.
I have multiple DPDTs. And two of the 6 don't work as expected. Why does it work when I directly hook it up to 3v terminal but not a HIGH pin? Shouldn't both be 3v?
Any ideas?

please add a schematic diagram of the connections ... it is unclear what is happening when you press the switch

you damage the pin. it can't supply the current for the coil


text:
The arduino can't seem to output correctly
i am a beginner at python and I am average at Arduino and I had the idea of using both of them together for a project. I have been trying to make a Arduino + Python car which I can control with my computer. I have used Pyfirmata and the code seems perfect to me. When I run the code from CMD i have a weird bug/issue.
I have uploaded Standard Firmata to the arduino UNO. I get no errors while uploading or running its just that its output is messed up.
Here's the Python Code:
from pyfirmata import Arduino, util
import time

board = Arduino("COM3")

MotorLeft = board.get_pin('d:10:o') # Assigning output to PIN
MotorRight = board.get_pin('d:11:o') # Assisging output to PIN

play = True

while play:
    control = input(
        print("Enter W, A or D to move forwards, left or right. Enter 0 to exit"))

    if control != 0:
        if control == "W" or "w":
            MotorRight.write(1)
            MotorLeft.write(1)
            time.sleep(1)
            MotorRight.write(0)
            MotorLeft.write(0)

        if control == "A" or "a":
            MotorLeft.write(1)
            time.sleep(1)
            MotorLeft.write(0)

        if control == "D" or "d":
            MotorRight.write(1)
            time.sleep(1)
            MotorRight.write(0)

        else:
            print("Invalid Commmand")

    else:
        print("Exited Succesfully")

    play = True

Currently I have not built the car, I am using a pair of LEDs to do what the motors function and to test out the code.
Heres the CMD response:

Here is the link for the output video. I entered "W" which should ideally turn on both of the LEDs however, both of them turn on then off and then turn on off one by one.
https://youtu.be/DjUkkpzF0so

Is it possible to see what is your Arduino code?

@smajli, Arduino code is PyFirmata

I cannot check it, but I guess you have to change the or commands like:
if control == "W" or "w":

Change to
if ((control == 'W') or (control == 'w'))

And similar for the other if statements.
Also, you can do not need to check for control == 0, since it will not be a character otherwise.
Besides that, the elif (else if) construct is normally used in Python, so instead of:
if control != 0:
    if control == "W" or "w":
        MotorRight.write(1)
        MotorLeft.write(1)
        time.sleep(1)
        MotorRight.write(0)
        MotorLeft.write(0)

    if control == "A" or "a":
        MotorLeft.write(1)
        time.sleep(1)
        MotorLeft.write(0)

    if control == "D" or "d":
        MotorRight.write(1)
        time.sleep(1)
        MotorRight.write(0)

    else:
        print("Invalid Commmand")

You can write:
if ((control == 'W') or (control == 'w')):
    MotorRight.write(1)
    MotorLeft.write(1)
    time.sleep(1)
    MotorRight.write(0)
    MotorLeft.write(0)

elif ((control == 'A') or (control == 'a')):
    MotorLeft.write(1)
    time.sleep(1)
    MotorLeft.write(0)

elif ((control == 'D') or (control == 'd')):
    MotorRight.write(1)
    time.sleep(1)
    MotorRight.write(0)

else:
    print("Invalid Commmand")

Also, you can combine the or in a list (but I cannot check it, no python compiler at hand), e.g.
if (control in ['W', 'w']):

Thank You. I will try to make these changes

Thank You! This project works now! Do you know what causes this problem? so I can avoid this problem in the future.

Great to hear, you can accept my answer than, to let others notify the problem has been solved.

if control=='W' or 'w'     since 'w' is not equal to 0, this will always be true, its the same as writing if control=='W' or True


text:
Ultrasonic Flowmeter Using TDC-GP22 and Arduino Uno
I'm working on a project of Ultrasonic Flow Meter with TDC-GP22 using Arduino UNO. I used the library of leokoppel
In my code,the configurations of the registers are copied from the Application Note of GP22, from page 22 to page 25. I didn't use the temperature sensor so I jumped those steps related to that. No calibration neither. I just want to get some results of time of flight to be able to calculate the distance between two sensors for now.
My code for test:
#include "GP22.h"
#include <SPI.h>
#include <avr/io.h>

/*
 *
 * Test setup (Arduino Uno, through 5->3.3V level shift)

 *     10 -> SS
 *     11 -> MOSI
 *     12 -> MISO
 *     13 -> SCK
 *     2  -> INT
 *     5V -> VCC
 *     GND -> GND
 *     4 -> DS18B20 temperature sensor (optional)
 */

const bool DEBUG = 1;
const int FAST_MODE = 1;
const int PIN_INT = 2;

GP22 tdc(PIN_INT, DEBUG);

float cycleFactor_ns = 0;

void setup() {

  Serial.begin(115200);
  Serial.println("Go !");

  tdc.init();

  tdc.writeRegister(0, 0x430BE800);
  tdc.writeRegister(1, 0x21444000);
  tdc.writeRegister(2, 0xA0138800);
  tdc.writeRegister(3, 0xD0A24800);
  tdc.writeRegister(4, 0x10004000);
  tdc.writeRegister(5, 0x40000000);
  tdc.writeRegister(6, 0xC0C06100);

  tdc.printConfigRegisters();

  byte a = tdc.readRegister(READ_REG_1);

  Serial.println(a,HEX);
  Serial.println("Test communication: ");
  Serial.print(tdc.testCommunication());
 }

void loop() {

  tdc.sendOpcode(OPCODE_INIT);
  tdc.sendOpcode(OPCODE_START_TOF_RESTART);
  tdc.waitForInterrupt(10000000);

  delay(20);

  Serial.println(tdc.readRegister(READ_RES_3),HEX);
}

From oscilloscope I got the right number of fire pulses(20) with right frequency(1MHz):
Signal (the blue one is the signal of transmitter before amplification, green one is after amplification, yellow one is the signal of receiver)
But what I got from the code:

Go !

attached pinChangeISR_debug

Register 0: 0x430be800

Register 1: 0x21444000

Register 2: 0xa0138800

Register 3: 0xd0a24800

Register 4: 0x10004000

Register 5: 0x40000000

Register 6: 0xc0c06100

21

Test communication:

\/Test took 180 us

1

69978000

69978000

69978000

69978000

69978000

69978000

69978000

...

21 is the first byte of register 1, and 1 is the result of testcommunication(). These two means the test of communication is successful. But the results of reading RES_3 are always the same, and the  waitForInterrupt() doesn't work(maybe the code shouldn't be written like this) -- Timeout all the time.
What I expect, of course, is the result can change each time it measures.(impossible to get exactly the same measurement of ToF all the time)
Any help appreciated!

Have you solved your problem? I am also interested to read result of TDC GP22.

I've been working with the GP22. I was wondering if you ever got yours to work. I know the datasheet says to generate a start and stop pulse across the start and stop pins, that is the route I went. I was wondering if you've made any progress since your last post about it?

First of all, the example in the document are for STM32. Since you need to do debugging, you could start with the following:

Verify that the register configurations are correct and suitable for your specific setup. Since you mentioned copying from the Application Note, ensure that no steps were missed. Make sure that the configurations of your registers (0x430BE800, 0x21444000, etc.) are accurate for your application for the Arduino Uno. Any mismatch here can cause incorrect behavior.

Ensure the interrupt is correctly set up and handled. The waitForInterrupt function might need to be reviewed or modified to correctly capture the interrupt.

Check if the results reading method is correct and if you need to clear any flags or perform additional steps after reading the results. This might get your code stuck.


text:
Udp.endPacket fails
I am trying to send measurements over UDP, but the function Udp.endPacket continuously fails.
I use an Arduino Uno WiFi rev 2, WiFiNINA library version 1.4.0 and WiFiNINA firmware version 1.2.1 which seems to be the latest available.
WiFi connection setup works, obtaining a correct IP address in the 192.168.3.0/24 network.
This is a snippet of my code:

const char* udpDestIP = "192.168.3.126";
const int udpDestPort = 1844;
WiFiUDP Udp;

void loop() {
  // establish variables for distance result:
  long cm;

  // execute measurement
  cm = measureDistance();

  // check for false measurements and repeat if necessary
  if(minDist < cm && cm < maxDist) {
    Serial.print(cm);
    Serial.print(" cm");
    Serial.println();

    // Check WiFi connection and reconnect if necessary
    if (WiFi.status() != WL_CONNECTED) {
      connectToWifi();
    }

    // Send over UDP
    //if(!Udp.beginPacket("192.168.3.255", udpDestPort)) {
    if(!Udp.beginPacket(udpDestIP, udpDestPort)) {
      Serial.println("beginPacket fail");
    }
    String msg = "water_distance:";
    msg += cm;
    byte size = Udp.write(msg.c_str(), msg.length());
    if(DEBUG){
      Serial.print("Sending this message over UDP: ");
      Serial.println(msg);
      Serial.print("udp write: ");
      Serial.println(size);
    }
    if(!Udp.endPacket()) Serial.println("endPacket fail");

    delay(delayTime);
  }
}

Terminal output is as follows:
151 cm
Sending this message over UDP: water_distance:151
udp write: 18
endPacket fail
151 cm
Sending this message over UDP: water_distance:151
udp write: 18
endPacket fail
33 cm
Sending this message over UDP: water_distance:33
udp write: 17
endPacket fail
34 cm
Sending this message over UDP: water_distance:34
udp write: 17
endPacket fail
153 cm
Sending this message over UDP: water_distance:153
udp write: 18
endPacket fail

Which makes me conclude the beginPacket, and udp.write functions are executed correctly, but I see no reason why the endPacket function keeps failing. Does anyone have an idea? Thanks a lot.

add Udp.begin() to setup(). if it works I write an answer with explanation

This works, thanks a lot! As UDP is a connectionless protocol, is there any reason why one should open a port to listen for incoming UDP packets while the device is only acting as a client emitting UDP fragments?

The UDP packets have to come from somewhere. They don't just appear from nowhere. Like a faucet has to exist and be turned on for the water to come out of it.

The UDP.begin() function requires a source port as argument. For just sending UDP packets, it doesn't matter from which port the packets are coming, the OS can just select a random unused port. Just like it's done in Python or Java. Is there a way to make UDP.begin() use a random unused port as source?

UDP.begin(random(1024, 65536));

The Arduino Ethernet and WiFi library implementations require to specify the outgoing port with UDP.begin(port) before calling UDP.beginPacket().
But UDP.begin(port) starts listening for UDP messages on this port too, so it is not a clean API. Call UDP.end() to stop listening for incoming messages.

Top answer, thanks.

You can accept the answer to mark the question solved


text:
how does c++ understand which function must to use?
in this code:
    void AdptSendReply(const char* str)
{
    string s(strlen(str) + 2);
    s = str;
    AdptSendReply(s);
}

void AdptSendReply(const string& str)
{
    string s(str.length() + 2);
    AdptSendReply(s); // use the next one
}

void AdptSendReply(string& str)
{
    if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
        str += "\r\n";
        AdptSendString(str);
    }
    else {
        str += "\r";
        AdptSendString(str);
    }
}

i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!

You know the first and the second aren't same. Second one passes empty string. Also the first is possibly unnecessary, as const string reference can be initialized by "c-string" (const char *) - temporary object is created with implicit conversion.

this may answer your question  https://arduino.stackexchange.com/questions/3079/how-to-retrieve-the-data-type-of-a-variable#3080 ......... the compiler tests the argument of the function in a similar way

This is offtopic here you should ask it elsewhere, the main stackoverflow maybe? But yes this is overloading, and the compiler has rules to resolve which function to use; you can check the C++ manual, or a C++ Primer/tutorial for more information.

What is string? Why is this information missing from your question?

It's probably std::string judging by the code, however this isn't really an Arduino question but a C++ question which might be better asked at Stack Overflow. I see people are voting to close this question, and if it gets closed just ask at Stack Overflow. They are experts on C++. :)

Calling overloading function triggers a process called overload resolution, which uses argument types to select the proper function to call

If you supply an lvalue argument of type string, the compiler will call void AdptSendReply(string& str) version.
string s = "hello";
AdptSendReply(s); // calls 'string& str' version

If you supply an lvalue argument of type const string, the compiler will call void AdptSendReply(const string& str) version.
const string s = "hello";
AdptSendReply(s); // calls 'const string& str' version

If you supply an rvalue argument, the compiler will call void AdptSendReply(const string& str) version.
AdptSendReply(string("hello")); // calls 'const string& str' version

And so on. The full set of rules that govern overload resolution is quite extensive, especially when the context involves implicit conversions.

It is not clear what you mean by "must use". Normally, overloaded functions will do the same thing (functionality-wise), meaning that you are not supposed to worry about which function to use. Just call it with the argument you have available and the compiler will select the proper function to call.
Also, what is string? How are we supposed to know that? Without knowing it, your question make little sense.

The compiler decides which function to use based on the variable type information. Imagine you write
str += "test";

If you declare str as a constant, the above line will throw an error. So if you write AdptSendReply(str) instead, the compiler will call the const function. Likewise, if you declare str as a mutable variable, the above line will compile fine, and, should you call AdptSendReply(str), the compiler will use the non-const function.


text:
white screen : 2.8" TFT LCD Screen Module: HY-280TFT
i have a problem with my new  2.8" TFT LCD Screen Module HY-280TFT.i connect it with an Arduino Uno board like this way:
 Connect HY-TFT280 to Arduino UNO

LEDA -> 5V
LEDK -> GND
VCC -> 5V
RD -> 3.3V
GND -> GND
DB0->DB5 to D8->D13
DB6->A0
DB7->A1
DB10->DB17 to D0->D7
RSET->A2
CS->A3
WR->A4
RS->A5

i downloaded and installed the new UTFT library. then i tested the example : Arduino(AVR)->UTF_Demo_320x240 , but i always have a white screen.
In the code, i change
UTFT myGLCD(ITDB32WD,38,39,40,41); by UTFT myGLCD(ITDB32WD,A5,A4,A3,A2);

but i still have the white screen
please what can be the problem? thank you

Maybe the fact that the screen is an ILI9331 and not an ITDB32WD might have something to do with it. Looks like UTFT doesn't support that chip anyway. Maybe you should use the library they specifically link to on that Wiki page...?

thank you to reply me...the wiki page send me link . and there, they show us UTFT library

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


text:
Is there a way to play .mp3 files from an SD card on Arduino?
Is there a way to have mp3 files on an SD card in the SD card shield for the Arduino and play an mp3 file on that SD card with a buzzer?
If possible also with something like:
playmp3(thismp3.mp3);

So that if I execute that command, the Arduino will play thismp3.mp3 through a buzzer.
Thank you.

it's going to be much simpler to play .wav files from the sd card

You can easily play .wav files because they are basically the sound levels recorded with a certain frequency. Here's a guide how to make an .wav music player: tutorial

If you're not specifically trying to make the arduino itself do the decoding and playback, you can get something like the Mini DFPlayer which would let you do essentially what you're asking for and offloads the decoding and playback so your arduino can do something else while the audio is playing.

It's not as easy as that. The SD card and playing audio are two different things.
However, probably the easiest way is to buy an MP3 shield (but that spoils the fun to make it yourself).
On the other hand, to make it yourself, takes quite some effort.
Also, the audio quality will be very low.
Besides that, decoding MP3 is far from trivial.
In case you want to make it yourself:

First write a program to read (stream) bytes from the SD card
Write an MP3 decoder (maybe/probably there are open source variants)
Forward the MP3 bytes to the decoder
Forward the audio bytes to the buzzer

Of course, there are time constraints otherwise you hear gaps in the music.

MP3 decoder on an Uno...? I think not. Maybe on a Due (I ported one to the PIC32 for chipKIT a while back, and it kinda worked), but not an Uno. Not enough memory. I used to run MAD on a 25MHz Sun SPARC system, but that had megabytes of RAM, not a couple of kilobytes. For an Uno external hardware is a requirement, not an option.

Note that it is possible to add memory to an Uno ... I did a test with a 23LC1024 and it worked. Slower than internal memory, but it worked.  But I agree, the speed might be a problem too (that's why I made the time constraint remark). I don't know exactly what the requirements are for MP3 decoding, looks like more than the Uno can process.

You're not adding memory to the Uno there - you're adding an external peripheral that happens to have memory. Adding memory to the Uno would entail including it in the memory map so you can use it for variables, etc - something the AVR doesn't support. Yes, you could offload some data into there for storage, but you can't process it while it's in there. It wouldn't just be slow - it'd be unusable for audio processing. Yes, the technology is SRAM, but in actuality it's more like an SD card or hard drive.

True ... that's also the reason I didn't use it in my project. Because i had to make my own 'memory map' from variables to external SRAM.
For MP3, I thought it could be used to store a small chunk of decoded data and to process it to undecoded data. But yes, it will not be advantage for the limited CPU speed of a Uno anyway.

Yeah - the difference between page mapping (hardware implementation) and page swapping (software implementation). For the former you need the chip to have external memory in the first place, so you can switch in and out different physical banks of memory (like the C= 64, Spectrum +2/3, etc did to get round the 64k limit). For the latter the chip has to have an MMU or some similar form of page fault mechanism to implement a virtual memory map. Neither of those are available in the AVR... ;)

@Majenko my initial plan was to store some arrays in external SRAM. That is easy to reference from a pointer stored in Uno's SRAM. However, I needed linked lists and lots of small objects, so it is too complicated. So what I intended was some kind of 'user made' MMU). A bit too much outside the scope of the project (which I still wonder if I will finish it, even on STM32). But meanwhile I learn a lot doing side tests for my hobby projects, also thanks to your comments (so thanks again). Sorry for thiss off-topic comments.

I believe MP3 uses licensed software that is implemented on decoder chips like VS1053.
Usually one would use a board like this, with an SD card for holding the massive amount of info that makes a sound.
http://www.oddwires.com/mp3-decoder-module-vs1053-for-arduino/?gclid=EAIaIQobChMInKS7lJGm2QIVE4_ICh1kTQa4EAQYAiABEgIKH_D_BwE
You then send commands to the unit to tell it to start, stop, advance, etc.


text:
Send SMS Arduino Uno + SIM900A shield
I am working on a module to send messages. I write the message on the serial monitor + phone number and I have to send the message to the line.
Question:
How to send messages through the SIM900A shield?
Problem:
What am I doing wrong in my code? Because I do not get an error but it does not send the SMS using the shield.
Try:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);
char msg;

void setup() {
  mySerial.begin(9600); // Setting the baud rate of GSM Module
  Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop() {
  if (Serial.available()>0)
    switch(Serial.read()) {
      mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
      delay(1000); // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
      delay(1000);
      mySerial.println("sim900a sms");// The SMS text you want to send
      delay(100);
      mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
    }
  if (mySerial.available()>0) Serial.write(mySerial.read());
}

This is my shield

Other try:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);
char msg;

void setup() {
  mySerial.begin(9600);  // Setting the baud rate of GSM Module
  Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop() {
  mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
  delay(1000);
  mySerial.println("sim900a sms");// The SMS text you want to send
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

And the question/problem is?

There is still no question.

now? help me please

There was not really a question, but I do notice there is no case's in your switch statement..
example from here
// do something different depending on the range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability

a need send message to shield

Are you wanted to send all those commands when ANY byte is received from Serial.read()?

the switch is to see if there is data or not in the serial, the question is. How to send an SMS with the shield?

@R.Fernandez That's not how switch statement works.

println() also adds a newline ( \n ) to the end of what you are sending, not sure if your module expects that or not, but you also have a return ( \r ) in one of your messages,   need to check to see exactly what the module expects


text:
ATMega328P receiver and transmitter pins
I am trying to connect Bluetooth, GSM and GPS to the ATMega328P, but since it has only 1 RX and 1 TX, can I use the digital pins of ATMega328P as RX/TX pins.

Look up SoftwareSerial.

you have not done any research, have you?

a little bit but that time i was not able to come up with a solution.Now i have the solution

The ATmega328p is not a good match for projects needing this level of connectivity - it can be done, but only by a lot of software juggling.

It sounds like you are after the SoftwareSerial library.

The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

Although, SoftwareSerial does come with limitations. The major one is that only one serial port can receive data at a time.

Sounds like you need something with 4 hardware serial ports. 2560 processor.

Or an ARM part compatible with Arduino usage...

You can use SoftwareSerial as mentioned above, and just wire the TX/RX to the desired digital pins. You will have to enable and disable the serial ports when you want to read/write to a specific port (Bluetooth/GSM), but that is not terribly difficult. I wrote a blog post on SoftwareSerial with an HM-10 Bluetooth module - there you can see how I wired and coded the SoftwareSerial via digital pins.
Arduino IoT with Bluetooth


text:
How to analyse audio and to affect source?
I want to use the audio from my PC and have it going to the speakers and Arduino for some lighting effects. This project is a bit of a struggle because I don't know what the best way of analysing audio is. So for the lights I only want bass frequencies to affect the lights.

You need an FFT for that - and an integer based one, too. And an Arduino that can store enough audio samples to make it meaningful. And ideally a faster system to process it quicker. Basically, while an Arduino could do it, it would struggle and not be wonderful. Better to use an ARM or PIC32 based board with more memory and a fast 32-bit CPU. An FPU as well would help, then you could do it with floats instead of ints (though ints are fine). Even better would be a chip with a DSP in it (such as a dsPIC33), but then you're straying way outside the bounds of Arduino...

While i dont really understand what you mean with the arduino not being able to store enough sample i could try and use my raspberry pi (i think i remember it being something with ARM).

I usually use at least 1024 samples (though you can use less, but you get less FFT buckets). At 16 bits per sample (actually 10, but you there aren't 10 bit data types) that's the entire memory of the Uno. For simple LED control you could get away with maybe 128 samples and sample at a lower frequency, since you aren't interested in the higher frequency range, and it then becomes viable. The fewer samples you have the less frequency resolution you get, but the less memory it uses and the faster it processes.

I have actually just finished a project doing exactly that. I used a frequency analyser chip called an MSGEQ7 (Available from Sparksfun), here's the datasheet.
https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf
These little things are really easy to use. Give me a shout if you would like any help with it such as coding or wiring.

Thanks alot i am currently  loooking into it to see if its what i need :-)

There's many ways of achieving what you want - some in software, some in hardware.
Since you are only interested in the lower frequencies this opens up the possibility of a low pass filter - either a hardware one, or a software one.  The simplest hardware one is just a resistor in series followed by a capacitor in parallel:

simulate this circuit – Schematic created using CircuitLab
(representative component values: increase capacitance and/or resistance to decrease frequency)
Doing it in software is just as simple: you sample at a regular frequency through whatever means are suitable (there's plenty of resources for sampling at a specific frequency on the Arduino - google them), then you average samples together to remove higher frequency components. The more you average the lower your cut-off frequency. Each time you average you halve the frequency range. Note that the frequency range is already half the sample frequency.
For instance: if you sample at 8kHz (say 512 samples) you get a 0-4kHz frequency range in your sample set. Averaging each pair of samples (which results in 256 samples) gives you a 0-2kHz frequency range. Averaging again, for 128 samples, gives you 0-1kHz. Average again, for 64 samples, gives you 0-500Hz. Again, 32 samples, 0-250Hz.  Keep going, until you have your desired cut-off frequency.
Then you can scan the sample set for the maximum and minimum and take that as your peak amplitude for the sample set.
You have to make sure that your sample frequency is at least twice the highest frequency you are interested in (preferably more so that you can do some averaging), and that your sample set is large enough, at the chosen sample frequency, to contain at least one full cycle of the lowest frequency you are interested in.  For instance, at 8kHz sample frequency, if you are interested in responding to frequencies down to 50Hz, you need to sample for at least (1/50) 20ms, which at 8kHz means (8000 samples per second times 0.02 seconds) 160 samples. Since it's usually better to work with powers of 2 that means 256 samples is the next biggest "slot" that would do.
If you want to access more information about the actual frequency content of your sample set so as to light different LEDs when different frequency components are in the signal you need a Fast Fourier Transform (FFT). This converts the sample set into a collection of buckets (exactly half the buckets as you have samples) each representing a portion of the frequency range of your sample set. For 256 samples that gives you 128 buckets, each representing 1/128 of your total frequency range. So at 8000 samples per second, or a 4kHz frequency range, each bucket gives you a 31.25Hz resolution.
The problem with FFT is it is computationally expensive. It also needs more memory than simple averaging.
Depending on the algorithm you use, you will probably find you need 16 bit samples, and each sample should be in the form of a "real" and "imaginary" component, amounting to 32 bits per sample. Most algorithms require powers-of-two for the number of samples. For 256 samples that means you are using 1024kB of memory just for sample storage and processing, which is half of what the Uno has. You certainly won't be able to go over 256 samples on an Uno (the next step up is 512, which would want to use the entire memory leaving no room for any other variables).
There are two basic forms of algorithms for FFT: floating point, and integer. The floating point variant is great on a CPU that has an FPU with it to do the number crunching, but on an Arduino that just isn't possible. So the floating point version would take a massive amount of time to process making your results incredibly jittery. Far from desirable. So you need to find the integer version (one example) which runs much faster.
Calculating an FFT is done in two parts: first it calculates the real and imaginary components from the sample set, and second it converts those two components into a single vector, the length of which is the amplitude of the bucket. Whether or not you are using the integer FFT algorithm that second phase is going to be slow. It involves a square root (it's basically pythagoras: sqrt((r*r) + (i*i));) and that is almost always slow. Getting that to work fast on an Arduino is not at all easy. You can sacrifice accuracy for speed though and write your own square root approximation routine (as I have done before for 3D vector manipulation in a graphics library):
float quick_sqrt(float number) {
    int32_t i;
    float x2, y2;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y2  = number;
    i  = * ( long * ) &y2;
    i  = 0x5f3759df - ( i >> 1 );
    y2  = * ( float * ) &i;
    y2  = y2 * ( threehalfs - ( x2 * y2 * y2 ) );

    return 1.0/y2;
}

That uses a few tricks to do with the way a floating point number is stored to create an approximation of the square root.
With all that you can see that the Arduino can do FFT, but it's not the best solution for FFT. Ideally you need a faster, more powerful, chip with more memory (personally I use a PIC32MZ "EF" variant: 200MHz, 512kB RAM, FPU).


text:
Is something wrong with my Adafruit motor shield?
I think something may be wrong with my shield, as I looked at the other forums related to this question and still can not get help.
I know that I can't run it from a 9V source by itself, as the Adafruit website specifically said I can't. So they said to use a LiPo battery or 8 AA batteries. So I tried powering the shield with 8 AA batteries and the light comes on to confirm that.
I then added a 9 volt battery to power the Arduino itself. My motor is a DC motor from RadioShack that can work at 9V, 12V or 18V. I have the motor connected to M2. What am I doing wrong? Here is the site I am following.
Here is the DC motor.
Again, if anyone knows what I am doing wrong, that would be very helpful to know. Thank you for your time and effort.
Edit 1:
#include <AFMotor.h>

AF_DCMotor motor(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm

void setup() {
  Serial.begin(9600); // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  motor.setSpeed(200); // set the speed to 200/255
}

void loop() {
  Serial.print("tick");
  motor.run(FORWARD); // turn it on going forward
  delay(1000);
  Serial.print("tock");
  motor.run(BACKWARD); // the other way
  delay(1000);
  Serial.print("tack");
  motor.run(RELEASE); // stopped
  delay(1000);
}

Please describe what is not working

The motor is not spinning even though I know the motor is working. I think there was a thread called motor not spinning or something but that thread did not help. So what am I doing wrong that the motor doesn't spin?

Can you provide more information about how the 8 AA batteries are configured? Are they in series or parallel or some combination? How are you initiating the signal to motor that it should turn? Do you have some code?

The batteries are in series as they are in a battery holder that I got from radio shack. All battery holders are in series. I will provide the code at edit number 1.

Does anyone know what is wrong? I have been searching for days.

You haven't provided enough information yet. So far it could be a) the motor is not getting the signal to rotate, or b) if it is receiving the signal, then the motor can't source enough current from your battery setup. Without a code example we're just guessing.

That is the code. I gave the code. What are you talking about? Also, the motor is firmly attacked to the shield. I have the right current set up or at least I think I do. I said what it was, I have given the code at edit number 1. What other information do you need? Someone has got to tell me what information or else how am I suppose to give you the information needed?


text:
How to read a specific amount of data via serial?
I'm trying to send data via serial from my Arduino nano to my ESP. Its an integer from 1 to 4 digits
so something like 0, 13, 1234, 123, ...
Every thing works fine but when the data comes too fast it stopps the output and  then it print all the data on the screen.
I use this method to recieve data.
void loop() { // run over and over
        if (Serial.available()) {
                incomingByte = Serial.readString();
                Serial.println(incomingByte);
        }
}

how does it print data to screen when the output is stopped? ... it is not clear what you are saying

What stops?  The Arduino or the ESP?   And how do you know?  You haven't told enough for people to help.

https://majenko.co.uk/blog/reading-serial-arduino

From what you have posted, assuming this is the ESP code in the question, it is clear that for every character the Arduino sends the ESP the ESP will send 3 back. So at some speed this will likly stop working


text:
Fingerprint sensor Arduino IDE code errors (Arduino Uno)
This code is for a fingerprint sensor. I keep getting the "function definition is not allowed before '{' token" error on the Arduino IDE. Any further corrections would also be immensely appreciated.
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("fingertest");
  pinMode(12, OUTPUT);

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }

  finger.getTemplateCount();
  Serial.print("Sensor contains "); Serial.print(finger.templateCount); Serial.println(" templates");
  Serial.println("Waiting for valid finger...");
}

void loop()                     // run over and over again

{
  getFingerprintIDez();
  delay(50);            //don't ned to run this at full speed.
  digitalWrite(12, LOW);
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;

  // OK success!

  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);

  return finger.fingerID;
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;

  // found a match!

  digitalWrite(12, HIGH);
  delay(3000);
  digitalWrite(12, LOW);

  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);
  return finger.fingerID;
}

Here is the circuit diagram-

This program works for products like- https://www.flyrobo.in/finger_print_sensor
.The wire connection is as follows- fingerprint sensor white wire - pin 3, yellow wire - pin 2, red wire - “+5v” , black wire - “GND” servo wire - pin 4
Any and all help is appreciated.

check the braces {} ....  make sure that they all match .... it helps to copy and paste your code into a text editor such as notepad++ and use it to count the braces .... https://notepad-plus-plus.org/

Hint: Look at else block in setup and at your loop function


text:
BLE Shield v2.1
I have an Arduino Mega 2560 and a BLE Shield v 2.1 from RedBearLab. When I try to connect it through Bluetooth from my laptop to 'BLE Shield', it says 'Connected!'. When I try from a Windows phone, it also says 'Connected'.
But when I try to connect from an Android device, it gives me an error: 'pairing rejected by BLE shield' or 'couldn't pair with BLE Shield because of an incorrect PIN or passkey'.
What seems to be the problem?

I would guess that the problem is an incorrect PIN or passkey.
I've read from manuals for some gadgets that some devices/phones automatically try the PIN 0000 and some don't.  I have never seen my Windows phone ask for a PIN when the device hasn't got one set, so I'm guessing that Windows automatically tries 0000 and Android doesn't.  Is there a  setting on Android that will let you enter the pin (which is probably 0000) ?

Also, sometimes the pin is 1234 on default and can be changed through AT commands


text:
How to use a 4-pin ultrasonic sensor as a 3-pin ping sensor?
const int pingPin = A0;

void loop() {
  long duration, inches, cm;
  pinMode(pingpin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

How to change this code for a 4-pin ultrasonic sensor?

Its not possible to answer this question.  What sensors have you got (model numbers and names)?

Also why are you setting up the pin assignments in the loop() normally they would go in the setup function.

@Matt: the pin mode is dynamic to recycle the same pin for pinging and listening.

if you want to use that code, short the 2 pins in question.

The four pin Echo))) module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example here.
const int8_t pingPin = A0;
const int8_t trigPin = A1;

void setup()
{
  pinMode(pingPin, INPUT);
  pinMode(trigPin, OUTPUT);
}

void loop()
{
  // pulse on trigger pin:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // 10us is minimum trigger pulse duration
  digitalWrite(trigPin, LOW);

  // measure HIGH pulse duration:
  long duration = pulseIn(pingPin, HIGH);

  // and rest of the code:
  long   inches = microsecondsToInches(duration);
  long       cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}


text:
Arduino Mega not recognized by device manager
My lab partner and I are working on a project for school and we are using an Arduino Mega 2560 for prototyping. The board was working just fine until, out of nowhere, the board was not being recognized at all. I tried reinstalling the IDE but still it does not work. I checked to see if the Arduino driver was installed, but the board does not show up in the device manager. Also, the L LED on the board does not light up at all. Attached are photos to help understand the problem.

If someone could help, it would be much appreciated. Thanks.

Have you tried unplugging all the wires from the Arduino (other than USB) to verify it isn't a problem with something in your project shorting out?

The board was working just fine until, out of nowhere, the board was not being recognized at all - out of nowhere, huh? What was the last thing you were doing with the board when it was working?

The last thing was upload a simple stepper motor code.

Also, to answer Phil C, nothing is plugged to the arduino.

If you guys have any other tips or tricks or advice in general regarding this issue, anything helps.

hey i had the same problem, i am thinking because i installed atmel studio and then this started happening,
I then downloaded arduino from the microsoft store,(no change)
then i restarted the pc, now its compiling and uploaded normally but still does not show the name of the board that is connected just shows lets say just  COM22 with out saying what board


text:
How to receive more than 64 bytes on Arduino?
I am receiving about 90 bytes on the serial port. But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.
char c;

void read_response() {
  while(Serial.available > 0) {
    c=Serial.read();
    Serial.print(c,HEX);
    Serial.print(",");
  }
}

I tried using the above function to read the serial data, but it is able to read only 64 bytes.
Another approach I tried as follows:
char rxdata[]={};

void read_response() {
  while(Serial.available > 0) {
    int len= Serial.readBytes(rxdata, 90)
  }
}

With this approach too, I was receiving only 64 bytes.
Serial.flush() also doesn't work as it waits for current transmission to finish. And I do not have control on transmission. The transmitter is sending 90 bytes continuously.
Please give me some suggestions.

what baud rate? if you read the response without any delay after sending the request the Atmega should be fast enough to read the bytes from the buffer before it overflows

That read_response() function should work fine as it is - however you probably have a delay() before it that overflows the buffer. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

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

But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.

This assertion is nonsense. Certainly there is a buffer, but that lets you receive up to 64 bytes (put there by the serial interrupt service routine) before you retrieve a single one.
All you need to do is expeditiously retrieve the data (that is, do a Serial.read()) fast enough that you remove the data from the buffer and store it into memory.
You need to post a Minimal, Complete, and Verifiable Example (MCVE) that demonstrates your problem. For example, are you doing delay(1000) before attempting to read serial data?
See my post about receiving serial data without blocking and also Async (Serial) peripheral interface - for Arduino .

You will need to adjust your concept of serial communication so that you don't rely on the complete 90 bytes of data to be transferred to the serial input buffer before you read it into RAM.
Instead you need to continually empty the hardware buffer into RAM as often as you run through loop(), and avoid using delay(), which will stop your program from being able to drain the buffer.
To know when you have reached the end of the transmission, you should either ensure that the incoming serial stream has a marker at the end (such as a '\n' character) or is always a fixed length (such as always exactly 90 bytes.)
As an example, here is a program that looks for '\n' as the end-of-data marker:
#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}

Good answer, but note that: 1. Storing s_len statically is simpler and more efficient than calling strnlen() on each received character. 2. You don't need to NUL-terminate on every received character, only once per full message. 3. Flushing the input buffer is not needed, and that could discard the beginning of the next message.

Ok on point 1. For point 2, my preference is to not leave unterminated strings laying around. For point 3, the code snippet is from my personal cache where I want to be able to signal EOL on CR+LF by detecting the first and discarding all the rest, but you have an excellent point. I will update my sample code.

This new version (2018-04-18 19:11:50Z) is prone to a buffer overflow, as the condition s_len==MAX_INPUT is only tested when input is either CR or LF.

Fixed that buffer overflow error. My original sample may have been inefficient, but it worked ;-)

just comment for 2) - I would set the last byte to zero beforehand, then I will never meet unfinished string, at worse I would meet so-far-readed string with attached part of some previous string (up to first zero - else the last byte of buffer or first zero terminating that previous string)

@gilhad: The buffer is all zeros to start width, as with any global (or local static) variable that is not explicitly initialized.


text:
Using pushbutton to make Stepper motor rotate 90 degrees
Using a 28BYJ-48 Motor with a ULN2000 Driver. The motor works fine since I can rotate it using serial input.
Pushbutton is connected properly, Can light up an led if I connect one.
I want the motor to rotate 90 degrees everytime I push the button. When I run the code below the LEDs on the driver just blink rapidly, when I press and hold the button they stop blinking, keeping the state they were on already. e.g. if the LED A on the board was on at the moment I press the button, It stays on. If it was off, It stays off. you get the Idea.
code used:
#include <Stepper.h>;

 // pushbutton pin
 const int buttonPin = 2;

 int STEPS = 32;
 Stepper stepper(STEPS,8,9,10,11);

//create a variable to store a counter and set it to 0
int counter = 0;
void setup()
{
  pinMode(buttonPin, INPUT);
}

void loop()
{
 // local variable to hold the pushbutton states
  int buttonState;

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if (buttonState == LOW) // light the LED
  {
    counter++;
    delay(150);
  }

  if(counter == 1)
    stepper.step(512);  // zero degrees
  //else reset the counter to 0 which resets thr servo to 0 degrees
  else
   counter = 0;
}

EDIT 1: Modifying the code @Matej gave me, I was able to debug the problem that was causing the stepper to not rotate. the code:
#include <Stepper.h>

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 9, 10, 11);
int val = 2048;

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for aving last millis

void setup(){
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  stepper.setSpeed(1000);
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);
  //if the button is pressed incremen counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter = 1;
    Serial.println(counter);
  }

  if (counter == 1) {
    Serial.println("Please Write the desired angle");
    val = Serial.parseInt();
    delay(5000);
    counter = 0;
    if(Serial.available() > 0) {
    Serial.println("Stepping: ");
    Serial.print(val);
    stepper.step(val);
    counter = 0;
    Serial.println(counter);
    }
    else {
      Serial.println("ERROR LOOPING THROUGH IF STATEMENT");
    }
  }

}

The Serial output looks like this:
1
Please Write the desired angle
Stepping:
00
1
Please Write the desired angle
Stepping:
20480
1
Please Write the desired angle
Stepping:
20480

please note that In the first attempt, I wrote "2048" in Serial input to define the value of the integer (val), and nothing happened. in the second and third attempt, I also wrote 2048 (0 at the end is the counter variable) and the motor started shaking, but it didn't rotate.

i don't see any code that moves the servo 90 degrees

I'm moving a stepper motor, not a servo  ^__^

I edtied few things in your code. I am not sure if LOW value is correct, so I replaced it with HIGH. Second thing is timing. I removed all delay() functions instead of it you can see usage of millis(). That's for handling interval between button press and button release - second part of if will check if last time of button press is bigger than 200ms, if yes, move stepper. Last things is stepping. You can see here stepper.step(STEPS/4);. STEPS is variable which you declared on the top of code. It's called steps per revolution, one revolution is 360° so 90° will be STEPS/4.
Here is the code, read it and test it:
#include <Stepper.h>;

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 10, 9, 11);

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for aving last millis

void setup(){
  pinMode(buttonPin, INPUT);
  stepper.setSpeed(1000)
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter++;
    stepper.step(STEPS/4);    //90° degrees
  }
}

Still doesn't work :( in my old code the LEDs on the Driver where blinking when you weren't pressing the button, in your code they blink when I press the button.

@MTXShiftGames And that's correct when leds on the driver board blinks only during button press, right?

I and you both forgot to do stepper.setSpeed(1000); but that didn't help. the LEDs on the driver blink when I push the button but nothing happens. I forgot to mention I have the motor plugged into a breadboard and powered by a breadboard Power supply, in case that makes a difference.
EDIT: Please Check Question EDIT.

@MTXShiftGames And does motor work with example? Are steps per revolution 32 correct?

yup it works. I have a program that rotates the motor based on serial input and the STEPS/Revolution is defined as 32 and that works.

@MTXShiftGames Can you, please, post this code somewhere? For example on pastebin.com

Here it is: link

@MTXShiftGames I can see only difference in this stepper.setSpeed(1000);. If you put this to the setup(), does it work?

I already did, Can you please check the updated code in my question? Please you helped me a lot, I wasn't getting anywhere

@MTXShiftGames Oh, look at the pins on pastebin and pins here. They are swapped.

@MTXShiftGames I edited my answer. Try code now.

You are Such a legend, Man. it's finally working! Thank you so so Much.

@MTXShiftGames Great! You're welcome. :)

Just a quick Tweak:
Please note while using Adruino, using "INPUT" mode without enabling the internal pull-up resistor, you need to ensure that the switch is connected properly and that you have external pull-up or pull-down resistors in your circuit. In the code you provided, you haven't included the necessary external pull-up resistor.
To tweak and fix the code, here a simple quick option:
Usage of "INPUT_PULLUP" mode instead of "INPUT":
This is the simpler and recommended approach. Just change the line:
pinMode(buttonPin, INPUT); to pinMode(buttonPin, INPUT_PULLUP);

It will enable the internal pull-up resistor of the Arduino, eliminating the need for external resistors in your circuit.
Here is quick fixed code:
#include <Stepper.h>;
// Using Stepper Motor to rotate 90 degree
// Reference: https://arduino.stackexchange.com/questions/61260/using-pushbutton-to-make-stepper-motor-rotate-90-degrees

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 10, 9, 11);

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for having last millis

void setup(){
  pinMode(buttonPin, INPUT_PULLUP);
  stepper.setSpeed(1000)
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter++;
    stepper.step(STEPS/4);    //90° degrees
  }
}

Connection Setup:
To connect an external switch to an Arduino using the internal pull-up resistor, ie. using "INPUT_PULLUP" instead of just "INPUT" in your above code, you will need to make the following connections:

Connect one terminal of the switch to the digital input pin on the Arduino. Let's assume you're using pin 2 for this example.

Connect the other terminal of the switch to ground (GND) on the Arduino.

With this connection setup, you're essentially creating a circuit where the switch is connected between the digital input pin and ground. When the switch is not pressed, the internal pull-up resistor will pull the input pin's voltage to a high level (logic HIGH). When the switch is pressed, it will connect the input pin to ground, resulting in a low level (logic LOW).
Alternatively, In case, you use "INPUT" instead "INPUT_PULLUP" which would not be a best approach here. You may follow the below example:
Here's an example of the circuit and code using an external pull-up resistor:
Circuit:

Connect one terminal of the switch to the digital input pin on the Arduino.
Connect the other terminal of the switch to the junction point between a pull-up resistor (e.g., 10K ohm) and Vcc (5V).

Code Example:
const int buttonPin = 2;  // Pin connected to the external switch

void setup() {
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);  // Enable internal pull-up resistor
}

void loop() {
  // Read the state of the button
  int buttonState = digitalRead(buttonPin);

  // Perform your desired actions based on the button state
  if (buttonState == LOW) {
    // The button is pressed
    // Do something...
  } else {
    // The button is not pressed
    // Do something else...
  }
}

Kindly note to add below line of code inside void setup() to enable internal pull-up resistor as shown in above code
i.e.  digitalWrite(buttonPin, HIGH);  // Enable internal pull-up resistor
hope that helps. Great job Guyz, Happy coding.


text:
NPN sensor to Arduino
I have a beam sensor providing NPN and also PNP output. It as 4 wires and works on 24V. I hooked the brown(+) and blue(-) to a small 24V power supply and the sensor is working!!! Yeah!
Now I would like to recieve the signal in my arduino. I dont know where to plug the black and white and I dont want to frie everything. I know I need to have an NPN configuration but I dont know how to achieve that.
This is the sensor in question: https://literature.rockwellautomation.com/idc/groups/literature/documents/in/42ef-in005_-en-p.pdf
And a little shema of my conections:

If someone could help me.
Thanks,
Nicolas

Could you add add a schematic or wiring diagram to your question, as well as some information about the sensor, as PNP and NPN do not typically describe output types.

Yes, this is the sensor in question: https://literature.rockwellautomation.com/idc/groups/literature/documents/in/42ef-in005_-en-p.pdf

I would connect the - from the supply and the sensor to Arduino Gnd.
Then the NPN output can pulldown an Arduino input with pullup resistor enabled.
Brown to 24V, Blue to Gnd, White to Arduino input.  No resistor to Brown. Black not used.

simulate this circuit – Schematic created using CircuitLab

It worked without smoke and bad smell! Thanks again!

is 100r enough? 5v/100r = 50ma; that's pushing it for an AVR isn't it?

The resistor is internal to the  Arduino, ignore that value.  It's more like a 30K to 50K resistor.


text:
Serial connection two devices two power supplies
I'm trying to connect an ESP32-CAM to a 3d printer using a serial connection.
When powering the ESP from the 5V rail on the 3D printer(and using 3.3V zener diodes between tx, rx & gnd), everything works fine. The ESP expects 3.3V on the serial pins, hence the diodes.

circuit diagram
Common ground not shown.
Then when I try to run the ESP32 from its own 5v power supply, I cannot establish a serial connection, regardless of whether I connect the gnd from the 5v from the 3d printer with that of the ESP power supply.
In fact, the ESP doesn't function then.
Any suggestions?
PS: the ESP has its own power since it should trigger a relay to cut power to the printer.

use a logic level converter

The 3.3V zener diodes are connected backwards. The anode should be connected to ground and the cathode (banded end) to the GPIO signal. Zener diodes work in reverse bias...as you have them connected now they are forward biased and will clamp the signals to about 0.7V.
The zener diode on the line for data transmitted at 3.3V to a 5V input doesn't do any good. You need to increase that signal voltage to a proper 5V logic level. The best thing to do would be to get rid of the zener diodes altogether and use a proper logic level converter.
Also, you really should have resistors between GPIO output pins and the zener diodes, to limit the current through the zeners when the GPIO pin is at 5V.


text:
How to access variables by variable? (I.e. variable variables?)
Can Arduino handle variable variables?

function getLetterCode(char input) {
    int letter_a = 17;
    int letter_b = 42;
    int letter_c = 50;
    return letter_$$input$$; //pseudocode
}

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.

it would be limited, but you could try using an array with a char index, which is basically a byte ... letter['a']

No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime.  In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.
Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a struct) and iterate it looking for the right key to match with your input.  Or, if there aren't too many inputs, simply use a switch to select different values:
int getval(char input) {
    switch (input) {
        case 'a': return 17;
        case 'b': return 42;
        case 'c': return 50;
        default: return 0;
    }
}

Thanks! I just realise how much I am used to those high level languages.

I know. It's not even as if you can use Map in Arduino - the STL is seriously lacking...

Point of order: You could also do it in a compiled language with dynamic dispatch (e.g. Smalltalk or Objective-C.)

@DuncanC I don't count those as real languages.

@Majenko well that's silly. Smalltalk is the mother of all Object-oriented languages. So Python is a real language but Smalltalk isn't?

Python? That steaming heap of rancid badger vomit?!


text:
How to set "IPAddress ip" using a variable?
Created a "variableInput.h" file for editing variables in one place; instead of searching multiple lines of code, to find lines needing editing.
//   variableInput.h
//
//   User defineable variables; one location for editing variables

// Replace with your network details
#define host = "esp32"
#define ssid = "YOURSSID"
#define password = "YOURPASSWORD"

//NTP Time Servers
#define udpAddress1 = "198.50.238.156"  //NTP Time server
#define udpAddress2 = "132.163.96.3"  //NTP Time server

//publicIP accessiable over Internet with Port Forwarding; know the risks!!!
//WAN IP Address.  Or use LAN IP Address --same as server ip; no Internet access.
#define publicIP = "YOURPUBLICIP"
#define LISTEN_PORT  8030  //default listening Port 80 for "GET" requests.

//Graphing requires "FREE" "ThingSpeak.com" account..
//Enter "ThingSpeak.com" data here....
//iframes of graphed data are available from "ThingSpeak.com."
#define myChannelNumber = 123456
#define myWriteAPIKey = "E12345"

//FTP Credentials
#define ftpUser = "FTPUSER"
#define ftpPassword = "FTPPASSWORD"

//setting the addresses
#define ip(10,0,0,200);
#define gateway(10,0,0,1);
#define subnet(255, 255, 255, 0);
#define dns(10,0,0,1);

//Restricted access to client ip list.
#define Restricted = "/ANYNAME"

//OTA Credentials
//default username: USERNAME
//default password: PASSWORD

// "setting the addresses" is the part that I do not understand.

Segment of related code from "wifi_Start" function:
//setting the addresses
IPAddress ip;
IPAddress gateway;
IPAddress subnet;
IPAddress dns;

Is there a solution?
William

it is unclear what you are asking ... you included a badly formatted code listing, but it is unclear how it relates to your question ... please explain in more detail what you are trying to do ... also, please format the code listing

constants .h in my project https://github.com/jandrassy/Regulator/blob/master/Regulator/consts.h

you should not use #define for constants. #defines are directives for the preprocessor

You are not using #define correctly. The syntax is #define {name}  {value}.  There is no = between name and value so for your IP address lines you want #define myIp ip(192, 168, 1, 11)

Ended up with "#define ip {10,0,0,11 }" in the "variableInput.h" file and "IPAddress ip;" in the wifi-Start function.  Appreciate the help!

Here's how I do it (for an Arduino that connects to my Mosquitto server) using wired ethernet (WiFi works the same way):
#include <Ethernet.h>
#include <PubSubClient.h>
EthernetClient ethClient;
PubSubClient client(ethClient);

byte mac[]    = {
  0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe
};
IPAddress ip(192, 168, 1, 75);
IPAddress server(192, 168, 1, 11);
void setup() {

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);

}

I understand this is the usual, useage; I need to have variable for "192.168.1.11.".

You can build an IPAddress(0,0,0,0) struct and assign a value to it. You'll need to take a dotted decimal address vvv.xxx.yyy.zzz and multiply vvv256^3+xxx256^2+yyy256^1+zzz256^0 to get the value to assign.


text:
Arduino pow() making 9's
I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1.  So:
10*10 = 100

Then I would assume, 10^2 = 100
So if I had a variable i, that was equal to 2, and I asked arduino for 10 to the power of i, I would expect it to do 10^2, and then give me 100, but instead I get 99.  What am I missing?
void setup() {
Serial.begin(9600);
}

void loop() {
for (int i =0; i<5; i++){
   int power = i;
   Serial.print(power);
   Serial.print(":");

   int multiplier = pow(10,power);
   Serial.println(multiplier);

  }

}

^ is not power operator in C and C++. it is bitwise XOR

https://stackoverflow.com/questions/4843304/why-is-my-power-operator-not-working

I put this code into the IDE, and for n>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:
   int multiplier = pow(10,power);

to
   float multiplier = pow(10,power);

The results should be as expected.
(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).

pow() works with floating point numbers.
Floating point numbers are just an approximation.  You will very rarely get precise results using floating point numbers.
Instead you could write your own little integer-based ipow() function.


text:
DEVKIT V1 DOIT 30 pinout board could not read analog value when using wifi library
I am using DEVKIT V1 DOIT board and 30 pinout board.
When I upload this code for checking analog value from serial monitor:
    // Define the analog input pin for the IR sensor
const int analogPin = 13;

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

void loop() {
  // Read the analog value from the IR sensor
  int sensorValue = analogRead(analogPin);

  // Display the analog value in the Serial Monitor
  Serial.print("Analog Value: ");
  Serial.println(sensorValue);

  // Add a short delay to avoid rapid readings
  delay(500);
}

it came just normally fine.
But when I upload this code:
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "JANINA";
const char* password = "sayma01720";
const char* websiteURL = "http://192.168.1.105:4747/araf/phploginscript-master/sense_value.php?uid=56"; // Replace with your website URL

const int analogPin = 19;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  int sensorValue = analogRead(analogPin);
  Serial.print("Analog Value: ");
  Serial.println(sensorValue);

  // Prepare the temperature to be sent
  String temperature = "temperature=" + String(sensorValue);

  WiFiClient client;
  HTTPClient http;

  bool success = http.begin(client, websiteURL);
if (!success) {
  Serial.println("Could not connect to the server");
  return;
}

  // Set content type to application/x-www-form-urlencoded
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpResponseCode = http.POST(temperature);

  if (httpResponseCode > 0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    String response = http.getString();
    Serial.println(response);
  } else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }

  http.end();

  // Wait for some time before sending the next temperature
  delay(2000);
}

It stop read analog value.
This was the result shown in serial monitor,

Analog Value: 0 HTTP Response code: 200

Please help me SIR.

why are you using a different pin than the first example? ... is pin 19 an analog input pin?

No.... I was tried many pins 4, 22, 23, 19, etc. but I can not find the solution.


text:
afmotor saying "servo does not name a type"
I have made a sumobot with an arduino, an afmotor shield and a 4-pin ping sensor when I upload my code it keeps giving me this error: "'Servo' does not name a type" here is my code.
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIGGER_PIN  A0  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     A2  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

 //speed variables for the left and right motor
int Lspeed = 180;
int Rspeed = 255;

//declaring the left and right motors and attaching them to
//their corresponding connector on the motor shield
Servo leftMotor;
Servo rightMotor;

void setup() {
  Serial.begin(115200);
  //sets initial speed
  leftMotor.setSpeed(Lspeed);
  rightMotor.setSpeed(Rspeed);
}

void loop() {
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  unsigned int CM = uS / US_ROUNDTRIP_CM;

  if (CM < 15 && CM > 0) {
    int iteration = 0;
    while( iteration == 0){
      leftMotor.run(FORWARD);
      rightMotor.run(BACKWARD);
      iteration = 1;
    }
    delay(600);
  }

  //starts motors going forward
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);

  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

Try #include <Servo.h>

As a kindness to people reading your question and trying to answer please include your code in the question rather than linking to it. Also, including the code ensures that it will stay available.

ok, but the insert code thing kept glitching out and just showing garbled text in varying bold and code

also im using 2 paralax servos (large)

Possible duplicate of Why does it say "Servo" does not name a type

You are creating Servo objects instead of AF_DCMotor objects. Change this:
Servo leftMotor;
Servo rightMotor;

to this:
AF_DCMotor leftMotor(1);   // Change these numbers to the correct motor numbers
AF_DCMotor rightMotor(2);  // you are using on the shield


text:
Save Watchdog ISR Return Address in EEPROM
If the WDT ever fires, from the ISR I save some info in EEPROM for later diagnostics before I drive the reset pin. Stack size, heap size, etc.
It might also be useful to know where the code was when the WDT fired, i.e. the ISR's return address. How do I get that?

What architrcture?

AVR… Arduino Pro Mini atmega328p

GCC has a handy function __builtin_return_address(depth) which should do what you want.  To get the return address of the current function (which should be the same whether it's a normal function or an ISR on AVR) you set the depth to 0:
void *addr = __builtin_return_address(0);

EDIT
The address returned above is a word address. Multiply by two to get a byte address as found in the disassembly from avr-objdump -SC firmware.elf >disassembled.txt
The latter is found at ~/.platformio/packages/toolchain-atmelavr/bin/avr-objdump

Well, that was easy… thanks! Next exercise is to figure out where that is in the code.

I didn't articulate that very well… next exercise is to find out where that return address is in the code (or in space) to get a clue what went wrong.

@EricNelson: Disassemble the .elf file using avr-objdump -SC.

@EdgarBonet YES!! Oh, man, does this ever take me back to the 90s.  Poring over disassembled code, counting cycles, rearranging code to see if we can eke out a few more whatevers per second to win a benchmark.

"addr2line" might be a handy tool, too.


text:
Variables not saving
I'm trying to write web server code. However, I am having trouble with part of it.
Currently, to get it to save a bool variable I have it use a pin, as when I ran the code without it, after the page refreshes it resets the variable to its original value.
How do I get it to save the variable in this code without it using the pin?
digitalWrite (equalPin, server.arg("equal").toInt());
char equalText[80];
if(equalState) {
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
} else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = digitalRead(equalPin);

I also have several over copies of this for different pages but if I change 1 of them they all change and reset after 10 seconds.
The code follows the example on this site.

so you want to set it or leave it as is? in if and else you change it and then you revert to the value before if and else. perhaps learn coding first.

I want it to set it then potentially change again in the future. I remeber doing it in the past but ive completely forgotten how. How do I stop it from reverting?

I can't understand what you're asking. Perhaps someone else can, but perhaps writing the question more clearly would help you get more responses. Consider a minimal, complete, verifiable example (Google to find what that is).

What are your trying to achieve? The code you linked to presumably works fine. Please, state clearly the purpose of your modifications.

same code snippet without using pin
char equalText[80];

if (equalState){
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
}
else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = server.arg("equal").toInt();

but it does not make much sense to set the value if you already switched the state based on it's previous value

That seems to have worked it just doesnt auto refresh the page anymore but thats fine.


text:
Does the ESP8266 somehow remember wifi access data?
Today I did some tinkering with an ESP8266, trying out OTA and writing a webserver. To find an error, I reduced the sketch to just the following lines:
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200);
  server.on("/", []() {
    Serial.println("Sending response...");
    server.send(200, "text/plain", "Hi there!");
  });
  server.begin();
}

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

Notice that there is no code to connect to a Wifi network. However, the chip still connects to my local, WPA2-secured, network on every boot. I can ping the chip, my browser can get the "Hi there!" message via http, the Serial message gets printed.
How is this possible? Does the ESP8266 somehow retain the Wifi information, maybe because of some old OTA data that was not completely overwritten?
I'm using platformio. Here's my entire platformio.ini:
[env:d1_mini]
platform = espressif8266
board = d1_mini
framework = arduino

I posted the compile and upload log here: https://pastebin.com/BtGrFZiu

Yes, normally the last WiFi credentials will be saved in flash and the ESP8266 loads this data on bootup and reconnect to the last known WiFi. See https://github.com/esp8266/Arduino/issues/2843#issuecomment-334250100:

the SDK stores some info, including the wifi credentials, in a sector of the flash.
That sector is kept between flashings to allow for a quick startup after update. On boot, before your sketch is executed, the SDK will retrieve the wifi credentials and attempt a quick connection.

This behaviour can be controlled by using the function WiFi.setAutoConnect(autoConnect) as documented in https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst#setautoconnect. This in turn calls the Espressif SDK function wifi_station_set_auto_connect (API reference)

In short: This is normal behaviour. If you want to make sure that your ESP8266 does not connect to any WiFi unless you tell it do it explicitly, call WiFi.setAutoConnect(autoConnect) at the beginning.
Edit: From within the firmware code, you can use system_restore. The documentation says that it would reset WiFi related data. This should destroy previous settings. The function can be included from https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/user_interface.h within Arduino-ESP8266. I have not tried this myself nor can I say that it actually erases security-critical information from flash though.

Or, as you also have found out, hard-erasing the entire flash will purge the WiFi data with absolute certainty. This can be achieved by using esptool.py with the erase_flash option, e.g. python esptool.py -p COM6 erase_flash. Then you can flash the new firmware which will not use previous WiFi settings (but will probably open up the default access point again).
Then there's also ESP.eraseConfig which erases only the relevant flash sectors.

Thank you. Is there a way to erase credentials that were previously set from the flash? EDIT: Found that it's possible with esptool: https://www.esp8266.com/viewtopic.php?f=32&t=8204

@Geier updated.

WiFi.disconnect() removes the remembered credentials too


text:
Analog inputs on ATtiny85 don't work
I want to use a ATtiny85 to check the voltage of two 12 V batteries (later to control a relay). Therefore I'm using the analogRead() function. For programming I'm using an Arduino Mega 2560 board.
//                           +-\/-+
//  Ain0       (D  5)  PB5  1|    |8   VCC
//  Ain3       (D  3)  PB3  2|    |7   PB2  (D  2)  INT0  Ain1
//  Ain2       (D  4)  PB4  3|    |6   PB1  (D  1)        pwm1
//                     GND  4|    |5   PB0  (D  0)        pwm0
//                           +----+

For A1 this works perfectly fine. But for A2 or A3 I'm getting always a value of 15 V (thus the analog input gives 1023 respectively it thinks there is 5 V on the pin, which is not the case). I tried A0 as well, but it's the same.
For seeing the current value I put a serial - USB converter on RX, TX on PB3, PB4. So I guess they cannot work properly as analog inputs then. But still A0 does not work and without serial my LED is always on without having a voltage over 12 V.
At the moment I don't know what to do about it. No matter which of the analog pins I choose, I'm getting always a wrong value (except A1).
I'm not a hundred percent sure about A0. On some diagrams there is an A0 pin, on some not. But I tried to remove all the serial communication code and still having the LED 0 on high.
Thanks in advance!
void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  digitalWrite(0, LOW); // led for displaying the voltage
  digitalWrite(1, LOW); // blinking status led
  int sensorValue1 = 0;
  int sensorValue2 = 0;
  Serial.begin(9600);
}

void loop() {
  int sensorValue1 = analogRead(A1);
  int sensorValue2 = analogRead(A0);
  // <- the problem, A2, A3 do not work as well
  float voltage1 = sensorValue1 * (5 / 1023.00) * 3;
  float voltage2 = sensorValue2 * (5 / 1023.00) * 3;
  Serial.print(voltage1);
  Serial.print("--");
  Serial.print(voltage2);
  Serial.println();
  if ((voltage1 > 12) || (voltage2 > 12)) {
    digitalWrite(0, HIGH);
  } else {
    digitalWrite(0, LOW);
  }
  digitalWrite(1, HIGH);
  delay(1000);
  digitalWrite(1, LOW);
  delay(1000);
}

SOLUTION:
As suggested by Andrei Dragan the problem was the serial communication, which uses just the same pins as the analog inputs A2 and A3. When turned off, the problem disappeared.
As the serial communication is quite useful for me, right now I'm still using the serial communication but only with the pin for sending data. The pin for receiving data is turned off. It looks like this:
#include <SoftwareSerial.h>

#define RX    -1   // *** turned off
#define TX    4   // *** D4, Pin 3

SoftwareSerial Serial1  (RX, TX);

(I don't know if this is the best way, but it works for me.)
Once again, thanks for the help!

A0 is the reset pin. Unless you change the fuses (which you shouldn't) you can't use that pin.

Thanks for your advice! So then I have to use A2 or A3 but both are not working, do you have any idea?

So then I have to use A2 or A3 but both are not working: that contains very little information to help others help you. It is likely working but you just don't know yet.

Any type of communication protocol uses pull-up resistors (not 100% sure that all of them do but still, it's a rule of thumb) so using the serial trick on the attiny enables the internal pull-up resistors on PB3 and PB4. I can bet the ADC value is near 1023 isn't it? Disabling the serial communication should in theory fix your problem.

I though I already tested it without. But it seems as I made some mistake. After disabling the serial communication it seems to work.
Is there a way to change the serial pins to get the exact voltage via serial com?
Thank you! :)

You cannot get the ADC to work properly on the pins that the serial communication is using (that lines are going to be pulled up either by the attiny or the other thing you're trying to communicate with, in your case the usb-serial chip). In your current configuration you can't do much about it without losing some of the data you want: you can either measure both of the voltages at once with the help of 2 diodes or you can get rid of the serial communication. As an alternative you can use another chip (attiny84, which has 11 pins, 8 of which are ADCs)

At the moment I'm not sure what the final setup will look like. Originally I have not planned to use serial communication, this was more for testing purposes just as the two LED's, but I will need at least one output for controlling the relay. But I think having the exact voltage can be quite useful.
For now I have changed the serial configuration in that way so that I'm only using the TX pin (PB4) for sending the data. So I can read the exact results and using PB3 as A3 as sensor input. Everything is working now and I'm getting correct voltage values. Thank you again! :)

Yo wrote “Any type of communication protocol uses pull-up resistors”. No. I2C does use pullups, but neither SPI nor asynchronous serial does. The OP's problem has nothing to do with pullups: it's the serial ports (of the ATtiny and the one on the other end) actively driving the line to Vcc.

Take an SD card application, it's good practice to use pull-ups on the SPI line in this case because a floating line (in the order of milliseconds, until the SPI communication is initialized) can cause problems on the SD card, possibly injecting unwanted signals onto it. It's unlikely but at least one time in our life we've seen the "This media is corrupted, reformat it bla bla" message, that's where the pull-ups on the data lines come in handy, to help you avoid that.