text:
What are the FLASH_ARRAY/FLASH_TABLE macros in this code?
In this code for heating monitor, there appears to be macros called FLASH_ARRAY and FLASH_TABLE. I can't find any reference to them either in this code, Arduino, or on the Internet. What do they do?
FLASH_ARRAY(byte, VARIABLE_DEVICE_TABLE,
    DEVICE_LADDNING_RETUR,
    DEVICE_LADDNING_UT,
    DEVICE_TANK1,
    DEVICE_TANK2,
    ...
    VARIABLE_ID_LOAD,
    VARIABLE_ID_TIME_EMPTY);

and
FLASH_TABLE(byte, NUMBER_TEMP_TABLE, 7,
  {DEVICE_LADDNING_RETUR, 99,  5, 10,  7, MAIN_TYPE_TEXT_CELCIUS, 2},
  {DEVICE_LADDNING_UT,    99, 43, 10,  7, MAIN_TYPE_TEXT_CELCIUS, 2},
  ...
  {DEVICE_UTE,             0, 55, 15,  7, MAIN_TYPE_TEXT_CELCIUS_WITH_NEGATIVE, 103},
  {VARIABLE_ID_EFFECT,   114, 29, 10,  7, MAIN_TYPE_TEXT_VARIABLE, 2});

After further digging, this appears to be from Mikal Hart's Flash library.
The reason this library was developed is:

Storing static program data in flash/PROGMEM is a tricky part of
Arduino programming. To save precious RAM, a novice user already at
odds with unfamiliar C++ syntax must digest such daunting concepts as
prog_char, PSTR(), PROGMEM, pgm_read_word(), etc. Even seasoned users
get tripped up by the indirection and typecasting that are required to
retrieve valid PROGMEM data. Add to that a couple of apparent bugs in
the implementation, and it’s clear that PROGMEM is a complicated mess.
I have written a new library, Flash, which abstracts away most of this
complexity. It provides new String, Array, Table, and String Array
types that make ROM-based data collections as easy to use as “normal”
types. Each overrides the C++ [] operator, so to extract individual
elements one uses familiar array access syntax:

Specifically, these are macros and a simple helper class to make it easier to create arrays and tables of values in program memory.
The two macros are declared as so:
// Example: FLASH_ARRAY(float, temperatures, 98.1, 98.5, 99.1, 102.1);
#define FLASH_ARRAY(type, name, values...) \
  static const type name##_flash[] PROGMEM = { values }; \
  _FLASH_ARRAY<type> name(name##_flash, sizeof(name##_flash) / sizeof(type));

// Example: FLASH_TABLE(uint8_t, fonts, 7, {ON, OFF, ON, ON, OFF, ON, OFF}, {OFF, ON, OFF, ON, OFF, ON, OFF});
#define FLASH_TABLE(type, name, cols, values...) \
  static const type name##_flash[][cols] PROGMEM = { values }; \
  _FLASH_TABLE<type> name((const PROGMEM type *)name##_flash, sizeof(name##_flash) / sizeof(name##_flash[0]), cols);

The helper functions include size and override the operator [] so that they can easily be accessed like so
FLASH_ARRAY[0]

I disagree with zmo - this is more than boilerplate. The area of PROGMEM causes a lot of questions from Arduino users, and it is very easy to do things wrong when creating arrays in PROGMEM.

Could you add an explanation of the macros within the answer? This answer contains only a link and won't be of much use, if the link goes offline.

Cybergibbons, this is nice, handy and useful, but this adds definitely a non trivial overhead: it's encapsulating an object within a full instance. When you only got 2k of RAM, every byte is precious.

The flash array is from Mikal Hart's flash library as you show, and what it does is that they declare an array or a matrix (table) object in the PROGMEM memory:
#define FLASH_ARRAY(type, name, values...) \
static const type name##_flash[] PROGMEM = { values }; \
_FLASH_ARRAY<type> name(name##_flash, sizeof(name##_flash) / sizeof(type));

which is an instance of the _FLASH_ARRAY class defined in that same file, which is a facility to access PROGMEM/Flash memory.
Basically, it's a lot of boilerplate for what already does the PSTR() macro amongst other from pgmspace.h. I personally would avoid using that and prefer to use the original macros along with my own index and pointers.
BTW, except for some Arduono IDE magic, I don't think that can compile, as the Flash.h is not included.
EDIT:
To make another point against the FLASH_TABLE/FLASH_ARRAY boilerplate/overhead, since avc-gcc 4.8 has been introduced the __flash qualifier which is a replacement for the PROGMEM macro, simplifying the whole stuff:
// to use string literals without having to cast
#define FSTR(X) ((const __flash char[]) { X })

// create string pstr in the .progmem.data address space
const __flash char* pstr = FSTR ("foo");

and no more use of the pgm_read_*() functions, you can now access the content of the flash memory using *pstr, as shown is this thread. In case you want to keep a code compatible with older version of avr-gcc, here's a post that offers macros to deal with both systems.


text:
New UNO, BLINK not working
Finally got around to playing with my uno today for the first time. ( It's a branded sunfounder UNO R3)
First project. Simple blink. Using arduino 1.6.3, Windows 8.1 It is hooked up correctly.
void setup() {
   // initialize digital pin 13 as an output.
   pinMode(9, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(10000);              // wait for a second
   digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
   delay(10000);              // wait for a second
}

What I get is a fast blinking LED. I've tried multiple values and it doesn't change. No error on upload.
I've commented out everything except the digitalWrite(9, HIGH); and I get a fast blink.
I tried:
void loop() {
   digitalWrite(9, LOW);
   delay(5000);
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
}

And I get nothing, it doesn't even turn on.
Same if I remove the first digitalWrite();
So, I'm already a little lost here. I did a but of google searching tried adding a serial 9600 line, and a few other things. Nada.

For your second snippet, you will never be able to see a single blink, that's because a second delay(5000) misses, in the end of the main loop. If you have an oscilloscope, or anything that can measure a frequency, check if the embedded quartz beats at 16MHz

No oscilloscope, or anything else to check frequency.  This is my first attempt playing with hardware like this but even if it was at 16MHz wouldn't the blink speed still change?  I tried many different values in there and it never changed.

Do you have and LED (and resistor) connected to digital pin 9 or is it the on board LED (which is on digital pin 13) you are observing ?

I've tried pin 9 with resister and I've tried 13.  Same result with both.  Same fast blink that doesn't change no matter what delay value ( I've tried up to 100000).  I tried a previous version of the arduino IDE also. Same thing.

Have you corrected the code? You must change the pin state to LOW, then delay, HIGH and again a delay! Also, mind that the internal led is on pin 13!

@Spirine Corrected?  The original code is there, and yes I was changing to the correct pin.    There isn't much to this really its like 4 lines.  Should work.

What you've written in the second code (starting with void loop...) will never work: you put off the LED, then you wait 5 seconds, then you put on the LED, and the program goes to the beginning of the loop, which take circa 100 nanoseconds, you put off the LED, etc. So, if you're able to see a blink of a few nanoseconds, yes, your code will work.

That was only to test nothing else.  I'm just trying to get the original code to work.

Try a different sketch to check the internal timers are running ok e.g unsigned long time;
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.print("Time: ");
time = millis();
//prints time since program started
Serial.println(time);
// wait a second so as not to send massive amounts of data
delay(1000);
}

Ok did that.  All I get is Time: 0 repeating over and over in the serial monitor. Also, did not seem to pause for a second.

Sunfounder thinks it's a bad board.  Probably going to return it and buy  a real arduino and not a clone.

it may just be the fuses aren't set correctly. You can correct this by using the IDE to 'Burn Bootloader' making sure the correct board (Uno in your case) is selected first. Double check the board labelling as I've found some supposed 'Uno' boards from eBay were in fact Duemilanove's

Ok, tried that.  Got a bunch of "Not in sync" errors.  Not sure if I did it right though.  Connected usb, chose the right board, then burn bootloader.  Think I'm just going to cut my losses and get a working board.

You can sometimes get round that problem by manually resetting the board (using the reset button) and releasing the reset button at the correct time whilst attempting to 'Burn Bootloader', can take a few goes to get the timing right. Failing that you can add a couple of components to temporarily disable the auto reset, which normally occurs when you upload a sketch. Use a 120 ohm resistance connected between the RESET pin of Arduino and +5 V, and a 10µF capacitor connected with the positive pole to the RESET of Arduino and negative to GND.

What should I be choosing under "programmer" when I'm doing this?  I just left it on the default of AVR ISP.

Defective board.  Thanks to @br1an for the milli idea.  New board in the way,  not a clone.

it's @Bra1n but you're welcome anyway

Sorry for the typo, thanks again for all the help.

Added as new answer because comments limit was reached
Doesn't really matter which programmer you set because in this instance you're not actually burning the bootloader just setting the fuses (to those already stored in boards.txt for the Uno) but 'Using Arduino as ISP' is the nearest to what you're doing

source: Stack Exchange

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

sort: votes


text:
Programming question for Time Arduino
Can you program a sketch so that if the time is between 1m and 10m then it will reset itself?
Reset I found already, it is the if that I don't know.

Are you trying to reset your board every 1 minute? Because when it sees that time is a bit more than 1 minute it will reset. Is that what you mean?

Are you struggling with if() statements?

You can use the timer interrupts. For example:
#define F_CPU   16000000UL
#include <avr/delay.h>
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
...
ISR(TIMER1_COMPA_vect)
{

  //do something every seconds when interrupt is raised.

}
void setup()
{
/*the following code will setup timer register to generate interrupt
  when 15624 is reached, at a clock frequency of 16 MHz and 1024 prescaler. This means that     every second an interrupt is generated
*/
  cli();          // disable global interrupts
  TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B

  // set compare match register to desired timer count:
  OCR1A = 15624;
  // turn on CTC mode:
  TCCR1B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);
  // enable timer compare interrupt:
  TIMSK1 |= (1 << OCIE1A);
  sei();          // enable global interrupts
}

The code works on Arduino Uno. You should calculate the value of OCR1A for your frequency.

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


text:
How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino?
I have an arduino UNO with atmega 328 whose microcontroller got burnt. I bought a new atmega328. I have another working arduino with atmega8. I followed the instructions in http://arduino.cc/en/Tutorial/ArduinoToBreadboard but I got a little confused.
I burnt the bootloader into my new atmega328 using atmega8 arduino as described in the link above. Now, can I replace my old atmega328 with this new bootloaded atmega328 to upload sketches to it? Or should I follow the steps described in the link to upload sketches?

Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.

You can use the 328p as usual (for an Arduino), once the bootloader is burned.
Background: You just used your Atmega8 as an ISP (In-System-Programmer) to get a bootloader onto your new 328p. The bootloader now enables the 328p to be programmed via serial port.

Yes - though the baud rate configured for the board chosen in the IDE  will need to match what the bootloader expects, which might or might not be the same as the original one.


text:
Arduino secure mqtt example not subscribing to topic
I am wrestling with the below example.
I have a RasPi on the network running Mosquito with username and password credentials setup and I know this is working.
If I load the below example, I can confirm the following:

It does connect to my Wi-Fi
It does connect to the mqtt broker
It does publish the example data (confirmed in serial monitor window and MQTTBox running separately)
But, it never receives a message on the subscribed topic.

I also have a VM with Mosquito running without credentials and if I swap to that, then messages sent on the subscribed topic do appear in the serial monitor.
I am using an ESP8266 D1 and am perplexed. Any thoughts appreciated.
/***************************************************
  Adafruit MQTT Library ESP8266 Example

  Must use ESP8266 Arduino from:
    https://github.com/esp8266/Arduino

  Works great with Adafruit's Huzzah ESP board & Feather
  ----> https://www.adafruit.com/product/2471
  ----> https://www.adafruit.com/products/2821

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

/************************* WiFi Access Point *********************************/

#define WLAN_SSID       "my_network_ssid"
#define WLAN_PASS       "my_network_ssid_password"

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "ipaddress for a raspberry pi only running mosquitto with username and password enabled - tested and working"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "mosquitto_username"
#define AIO_KEY         "mosquitto_password"

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiClientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell");

// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/mytestfeeds/onoff/");   //have changed the topic from default

/*************************** Sketch Code ************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

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

  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

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

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&onoffbutton);
}

uint32_t x=0;

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  // this is our 'wait for incoming subscription packets' busy subloop
  // try to spend your time here

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &onoffbutton) {
      Serial.print(F("Got: "));
      Serial.println((char *)onoffbutton.lastread);
    }
  }

  // Now we can publish stuff!
  Serial.print(F("\nSending photocell val "));
  Serial.print(x);
  Serial.print("...");
  if (! photocell.publish(x++)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
  /*
  if(! mqtt.ping()) {
    mqtt.disconnect();
  }
  */
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

Have you tried listening to all topics? Just mytestfeeds/#? It's also typically not recommended to start or begin topics with a '/'.

Also, this should help pin down the issue.

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


text:
Re-using built-in USB port to charge battery
I'm dipping my toes into using LiPo batteries for supplying power to small devboard projects, currently with an LOLIN S2 mini.
So I got hold of a MH-CD42 module, which seemed like a safe way to start with.
I came up with this example schematic to illustrate what I'm trying to do: to use the onboard USB port to power the board and charge the battery when connected, and to power the board with the battery if USB is disconnected. In this schematic I would need to flip the switch to accomplish this but I wonder if there is a way to wire this up so that a switch is not needed and the board does not reset when (dis)connecting the USB connection. Any thoughts on this are appreciated.

"to power the board and charge the battery when connected", you can't charging the battery while connecting to the load (which is your ESP32 board). You need a load sharing switch, read Li-Ion Battery Charger and Load Sharing System.

Wemos is probably not optimised for battery power operation. A board designed for battery operation requires attend to the specification of every components it used and with the proper charger and load sharing circuitry. Such as  Sparkfun ESP32 Thing which has load sharing circuitry and low dropout voltage and low sleep current for battery operation.

I can see what you are trying to do (make use of the already present USB connector), but I think that you are looking at it the wrong way, as well as trying to make the MH-CD42 work (or rather, connect it up) in ways that it isn't really meant for.
Forget about using the onboard USB of the WEMOS.
You should connect the VOUT to the VBUS as you are meant to (check the usage and diagram in the link to the MH-CD42 that you provided):

Provide a separate female USB connector (or alternate power supply connector) to VIN of the MH-CD42, and apply power that way (instead of trying to gain "dual usage" from the USB connector onboard the WEMOS).
In this manner, you are using the MH-CD42 correctly - it will automatically do the "switching" for you and no power glitches will occur when the USB (or whatever) power supply is removed (from VIN).
In addition, you no longer have to worry about dual-purpose/dual-direction power lines - that seems like a recipe for disaster.

An alternative method (without the MH-CD42) can be found in this answer to How to create automatic dual battery changeover/switching circuit for uninterruptible power?

Thanks! Do you think the idea is bad in general or just in combination with the MH-CD42? I'm just interested if it is possible to do it since the principle seems useful and elegant to me, but I lack EE knowledge so it's currently hard for me to understand if this is just a bad approach in general. I could imagine something along these lines could be more easily achieved when designing your own pcb but that's not something I plan to do due to safety risks, hence my use of devboards and modules like this.

It just seems like a bad idea, if you are using a MH-CD42,, as the MH-CD42 is designed to do the switching for you, so let it do so. However, if you don't use a MH-CD42 then your "switching" idea is a good one, and that is basically what the additional link to Olin's answer (on SE.EE) does. However, if you are already using a unit (i.e. the MH-CD42) that basically does what Olin's answer does, then just let that unit do the work for you. Why bother re-inventing the wheel? Forget about the onboard USB connector. The devboard is just that... for development. Later, a production unit would ...

... use a standalone ESP-8266EX (or whatever variant) IC (without the devboard PCB - you would be using a custom PCB of your own making), that has no USB connector (at least not a USB connector wired to VBUS, but to VIN instead), and so your design will still work. Hopefully that makes sense. :-) See also, What IC does the MH-CD42 battery/5v power board use? as it is an interesting read.

FWIW, a variant of Olin's answer has just been posted, with a mechanical switch, as an answer to a different question, over on SE.EE.

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


text:
Arduino fails to upload Elegoo Uno R3 (resp=0x73)
I have an issue uploading the program to Elegoo UNO R3. Here is what I have tried:

I tested 2 Elegoo UNO R3 boards, but both Elegoo Uno R3 do not work. Arduino IDE found the board and stated the board was connected, but it failed to upload the program.
I've uploaded the same program to Arduino UNO R3 board and Elegoo Mega2560 R3 board. They are working fine
I removed and reinstalled the driver, but it does not work
I reinstalled the Arduino software version 2.3.2, but it did not improve the situation.

What else would I try? Here is the error code:
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x73

An official UNO R3 and Elegoo R3 (using AVR transceiver) are indistinguishable from the perspective of the computer/avrdude/ide. They use the same transceiver, same bootloader, same VID:PID, etc. If these boards are behaving differently one is broken or more likely information is missing or from the question or incorrect. Provide more information. Pictures of what you actually have, entire verbose avrdude output, links to what actually bought, etc. Barring something really subtle (e.g. power issues) anything causing "not in sync" would affect both of these boards in exactly the same way.

Do you have the choice between different (versions of) bootloaders? Did you try different ones?

A bad cable maybe?

I guess they are without a bootloader. burn the bootloader.


text:
Running code inside void loop() vs inside a separate function with an infinite loop in it
I'm writing a program for running a stepper motor at a high RPM using accelStepper on a NodeMCU esp8266. Super New to the accelStepper but reading, experimenting and learning as I go
When the code to cycle the stepper one way and then the other is inside the void loop() it works as expected, but there's a bunch of other inputs I need to check in there for setting up the system and when they are all inside the void loop() they slow down the cycle noticeably as it does various digital and analog reads.
While the stepper is cycling I only really need to watch one e-stop input instead of everything so I figured to create a separate function with an infinite loop in it, call the stepper code there and just check the one input and return out of the function when done
Testing this and it partially works but the stepper only makes it part way to its end point and then abruptly stops (instead of decelerating) and then reverse and same thing.
Probably not even the right way of trying to solve my issue but it's what I came up with tonight.
Any help would be much appreciated.
Here's the entire test code I'm using. When I un-comment the block of code inside the void loop() and comment out the call to the go_to function it works perfectly fine. When that basically exact same block of code is run inside the go_to instead, it gives the weird results
    #include <AccelStepper.h>

    const int DIR = D6;
    const int STEP = D7;

    AccelStepper stepper(1,STEP,DIR);

    int EndPoint = 50000

    void setup()
    {
      stepper.setMaxSpeed(8000);
      stepper.setAcceleration(10000);
      stepper.setMinPulseWidth(10);
      stepper.setCurrentPosition(0);
      delay(2000);  // need to prevent partial run when loading
    }

    void loop()
    {
      /*  if this code runs it works perfectly
      stepper.run();
      if (stepper.currentPosition()==EndPoint)
        {
        NewEndPoint=0;
        stepper.moveTo(NewEndPoint);
        }
      else if (stepper.currentPosition()==0)
        {
        NewEndPoint=EndPoint;
        stepper.moveTo(NewEndPoint);
        }
        */

      go_to();

    }

    void go_to()
    {
      for(;;) // have tried while(true) also, same results
      {
      stepper.run();
      if (stepper.currentPosition()==EndPoint)
        {
        NewEndPoint=0;
        stepper.moveTo(NewEndPoint);
        }
      else if (stepper.currentPosition()==0)
        {
        NewEndPoint=EndPoint;
        stepper.moveTo(NewEndPoint);
        }
      }
    }

The reason I'm trying to get this to work is for the full program, there's several digital and analog reads than need to be done for speed, distance, number of cycles etc. that all must be in the void loop(), or called from there, and if they are in the same loop where the stepper.run() is it slows the RPM down a lot so I'm trying to get the stepper.run() into it's own loop where it's not looking at any inputs it doesn't need to but I ran into this problem and don't see why it's reacting the way it is.

both of the codes do the same thing ... the second code never exits back to loop()

They were supposed to do the same thing. It's the exact same code but when it's inside the separate function the stepper only goes part way towards the endpoint and then stops hard, delays a bit and then starts the reverse direction, goes part way and stops hard, then repeats. I never bothered adding the way out of the function since it's not working the way I expected.

there may be some housekeeping done at each iteration of loop() ... the loop inside go_to() prevents it from executing

If the stepper motor code has to be serviced quickly then you have to focus on the other code that you have removed from the loop() for this demonstration and which slowed it down. You must eliminate any blocking code such as delay() or complex float or other time intensive calculations. An alternative is maybe to move to the ESP32 platform where you can use RTOS to run fast and slow code more or less in parallel.

look at the random example sketch in the accelStepper library ... use distanceToGo instead of currentPosition for simpler code

Your problem lies in a part of your code that you have removed. Please, post a complete, testable (and tested!) example.

I've added the complete code that I'm testing, it's only the setup that is missing. This is the actual code I'm testing that works inside the void loop but only moves the steppers part way if run inside the separate function.

Can you try this on an AVR-based micro, an Uno or a Mega? My expectation is that you will see the motor run as expected, whether executing within loop() or within go_to().On an ESP8266, a lot more happens between calls to loop() than does on AVRs. It seems likely that some one or more of these background tasks on the ESP between calls to loop() is necessary for your motor code to execute properly. But when you run the motor in go_to() on an ESP, loop() never returns and those background tasks don't get done.

I can wire it and try on a mega tonight and see if that works. What you're saying about the background tasks between loop calls being missing makes a certain amount of sense. Will post back results

Or, an even simpler test, possibly even a fix: still using the ESP: just add a call to yield() inside the for(;;){} loop at the top or bottom of it. yield() is designed specifically to allow long-running processes such as yours to give the background an opportunity to do its necessary chores, at a point of the programmer's choosing.

So the original problem of the steppers acting differently inside a different function than the loop() certainly seems to be because of the "additional code that needs to run between iterations of the loop function", "On an ESP8266, a lot more happens between calls to loop() than does on AVRs" that was pointed out. Adding a yield() to the separate function fixed the stepper issue... I'll say that this problem is solved. Unfortunately it also brought up a different problem with my process so back to the drawing board.
Thanks so much for the insight and suggestions, I'm going to go and try some

The ESP8266 has additional code that needs to run between iterations of the loop function.  If you are going to trap it elsewhere in some while loop, then you need to also be sure to call delay(0); or yield; in there so that it can handle its other business.  If the code around loop doesn't get run in time, then the board resets from the watchdog IIRC.  I believe that is the symptom you are seeing.
And like the others say, there is no good reason for a blocking loop in your code.  Let the loop function be the loop.

I'd like to have it in the main loop but I haven't figured out how to prevent the digital and analog reads that have to happen in there from slowing this run() down. Bad enough I'm still going to have to have a single digitalRead of the e-stop switch happen with this run(). Maybe using a interrupt (attachInterrupt()? ) would be a better option than the digitalRead().

Put those reads in an if statement so they only run when the other part isn't.  You're not running anything concurrently, so however you have it structured now you could just move the function back into loop.

No, an interrupt will just make it more complicated.  You need a boolean variable that tells which part should be happening and then a couple of if statements in loop to decide if loop is reading inputs or running steppers.  Really it should be able to do both.  There's really no reason that the stepper code needs to be blocking.  But for some reason everyone is reluctant to try to learn non-blocking techniques.

Adding the yield() to the end of the go_to() function resolved the weird behaviour of the stepper motors and now they act the same as they did when running the code within the loop(). BUT it's not treating the function as something that needs to be completed before returning to the main loop.... I've got some more reading to do on that command I guess. But it answers the question of why the test code wasn't working.

You shouldn't code it to need to be complete before returning to the main loop.  That is a poor blocking design.  Code it like a state machine so the loop can still run while the steppers are moving.

loop already runs indefinitely, hence its name. You don't need to add another loop in your go_to function. Remove that and it should be functionally identical.

The simplest way to fix all of this is going to be to keep your stepper code within the loop function, but keep a variable that "remembers" when the stepper is running. Use that variable to know when not to do the time-consuming tasks. Let loop() return after each iteration whether the stepper is running or not. No yield() call will be needed. Just make sure to know when the stepper is running and don't do the long jobs if when is.
Perhaps something like this (untried!) code-structure:
void loop()
{
   static bool isStepping = false;
     :
   if( !isStepping ){
      /* call time-consuming tasks here; */

      if( time to start the stepper now ){
         /* set up any stepping conditions you need to here; */
         isStepping = true;
   }

   if( isStepping ){
      /* run one iteration of the stepper code; */
      if( stepping is complete ){
         isStepping = false;
      }
   }
}  // let your loop() return after each stepper iteration

I'll have to try some of these other approaches since the separate loop doesn't seem to work the way I was hoping, the yield did work to fix the stepper stopping but it created a different problem in the sub-function so I'm going to re-read all of these answers and suggestions and try a different approach.


text:
TRIAC Pulse driver for Spot Welder (help needed with programming)
I have designed and built a transformer driver board for my spot welder. It is powered from mains electricity (230 V) and consists of the following segments: triac drive and protection, zero cross detection, controller input, connections. The board operates correctly when voltage is manually applied. However, I'm not able to make it work with Arduino.

What I want it to do is:

Read the potentiometer(R10), and assign to it value a phase angle, at which triac is going to receive pulse to turn on.
Read Potentiometer (R9), and assigned to it value number of pulses(1-100) for a triac,
Read switch (Power_pulse) that when high start triac firing procedure (angle and duration determined by pots)
I have an I2C display 16x4 that(can be driven directly from SCL and SDA on Leonardo) I might use to display welding parameters(optional goal)
The code I found on "electronoobs.com"
   int detectado = 0;
    int valor=0;
     int last_CH1_state = 0;

   void setup() {

  PCICR |= (1 << PCIE0);    //enable PCMSK0 scan
  PCMSK0 |= (1 << PCINT0);  //Set pin D8 trigger an interrupt on state change. Input from optocoupler
  pinMode(3,OUTPUT);        //Define D3 as output for the DIAC pulse

}

void loop() {
   //Read the value of the pot and map it from 10 to 10.000 us. AC frequency is 50Hz, so period is 20ms. We want to control the power
   //of each half period, so the maximum is 10ms or 10.000us. In my case I've maped it up to 7.200us since 10.000 was too much

   valor = map(analogRead(A0),0,1024,7200,10);
    if (detectado)
    {
      delayMicroseconds(valor); //This delay controls the power
      digitalWrite(3,HIGH);
      delayMicroseconds(100);
      digitalWrite(3,LOW);
      detectado=0;
    }
}

//This is the interruption routine
//----------------------------------------------

ISR(PCINT0_vect){
  /////////////////////////////////////               //Input from optocoupler
  if(PINB & B00000001){                               //We make an AND with the pin state register, We verify if pin 8 is HIGH???
    if(last_CH1_state == 0){                          //If the last state was 0, then we have a state change...
      detectado=1;                                    //We haev detected a state change!
    }
  }
  else if(last_CH1_state == 1){                       //If pin 8 is LOW and the last state was HIGH then we have a state change
    detectado=1;                                      //We haev detected a state change!
    last_CH1_state = 0;                               //Store the  current state into the last state for the next loop
    }
}

Finally the question: What do I need to add to this code to make it work in my application?
PS.  Issues regarding safety are addressed by another board that have fuse and over voltage protection.
PPS. I have 5V supply dedicated to driving the board and Arduino.
enter code here
void setup() {

}

 int faza=0;
 int cykle=1;
 bool wcisniety;

  void loop() {

    faza=20000 * analogRead(2) / 255;// Pot 1
    cykle=100 * analogRead(3) / 255; //Pot2

  if(digitalRead(4) && (! wcisniety))// if cheacks for button pres to activate function
    {zgrzewaj();}

   wcisniety=digitalRead(4);

   }

 void zgrzewaj(){

   while (digitalRead(0)){

    }

  for (int i=0; i < cykle;i++){

delayMicroseconds(faza);

digitalWrite(1,HIGH);

delay(10-faza/1000);

digitalWrite(1,LOW);// fireing TRIAC
 }
}

This is what i come up  with. While it looks simple and proprly build still dont hav any output.
All coments appreciated.

Link to project page at electronoobs: http://www.electronoobs.com/eng_circuitos_tut20.php @Pioter, the arduino leonardo has an other microcontroller than the arduino uno and at electronoobs they use an arduino uno.

The higher level functions do the same, for example digitalWrite( 13, HIGH). Everything below that is different.


text:
ATmega328 drop-in replacement with more flash memory
Is there a ATmega328 drop-in replacement with more flash memory?
Needs to be 28 pin DIL to fit the socket.
Alternatively, is there a board that has the exact dimensions and pins as an Arduino UNO, but with more flash memory?
Everything in my project works fine, but I need more program memory. Can unfortunately not use a different board layout or size.

What did you try to find out? Did you visit the manufacturer's web site? Did you visit Arduino's web site for other models?

Would it be possible for you to use an external flash memory? Something like the Macronix MX25R6435F.

@Cowboy_Patrick: Thanks for the suggestion, but unfortunately not.

the  wemos D1 (not mini) has an uno form factor and a bajillion times more ram. it is 3.3v though. You probably could make a custom PCB with uno layout and an ESP32s2 and integrated logic level shifters. might be a useful project for many,

@dandavis Thanks, great suggestion. I looked at the Wemos D1 a few weeks ago, and if it had 5 V logic levels, it would be the board for me. I was hoping to get away with not making a custom PCB.

Is there a ATmega328 drop-in replacement with more flash memory?

No

Alternatively, is there a board that has the exact dimensions and pins as an Arduino UNO, but with more flash memory?

Yes, but it'll be probably something with ARM (UNO R4 minima has even 5V ARM), However libraries might be an issue
As for AVRs, there are for example AVR128DA28 but as far as I know, it's definitely not pin compatible.
However you could use some proto board for UNO and wire it up somehow on it.  (128kB, 28pin).
Also Atmega644/1284 (in pdip 40) could be used on proto board and it's much more compatible

Thanks, great answer. Will probably get the UNO R4 minima.

Well then aware it doesn't have such strong output drivers (8mA tops), mentioned libraries compatibility and it's relatively new, so even bugs in arduino core are possible


text:
Transmit/Receive data Nodemcu(V3) + Bluetooth Module HC-05
I am trying to communicate with the HC-05 Bluetooth module for quite long time now, but with no success.
I am using the Nodemcu(V3) ESP8266 module.
I connect the HC-05 to Nodemcu in following sequence:
HC-05             Nodemcu
-----             -----------
RX       -->      Pin 1 (Tx)
TX       -->      Pin 3 (RX)
Vcc      -->      +3.3V
GND      -->      GND

For starters, i want to check if my Nodemcu is communicating properly with my HC-05 module.
I have written the following code to read the response of AT commands:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(3, 1); // RX | TX
char Bluetooth_Name = ' ';

void setup()
{
    // Arduino IDE serial monitor
    Serial.begin(115200);

    // HC-05 default serial speed for AT mode is 38400
    BTserial.begin(38400);

    // Wait for hardware to initialize
    delay(1000);

    // Print debug string
}

void loop()
{

   // Keep reading from HC-05 and send to Arduino Serial Monitor
   if (BTserial.available())
   {
      reading = BTserial.read();
      Serial.println(reading);
   }

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

However, i do not get response for any AT command at all. The serial monitor just shows blank.
Thanks in advance
EDIT:- I connected the "EN" pin on the HC-05 to Vcc. Now, the led on the HC-05 blinks slowly, which means that the HC-05 is configured in command mode. However, i am still not able to receive the response for any AT commands. I have also selected "Both NL & CR" in the serial monitor, configured the baud rate correctly and double-checked the hardware connections.
Everything seems to be correct except that i don't get response for the AT commands.
Please help!!!

what output do you get, if any

No, i did not get any output on the serial monitor

I just modified the question to check the basic step if HC-05 is working with Nodemcu or not?

I changed the line
SoftwareSerial BTserial(3, 1); // RX, TX

to
SoftwareSerial BTserial(D4, D3); // RX, TX

And got it to work!

I had the exact same problem and got it to work doing these changes:
I had to add this under my library include statements
#ifndef D5
#if defined(ESP8266)
#define D5 (14)
#define D6 (12)
#define D7 (13)
#define D8 (15)
#define TX (1)
#endif
#endif

and changed
SoftwareSerial BTserial(3, 1); // RX, TX
to
SoftwareSerial BTserial(D5,D6);
I used D5 and D6 on my esp8266 instead of D1 and D3 but shouldn't matter


text:
ESP8266: Interfacing MAX485 TTL-to-RS485 on serial port
I am using the ESP8266 NODEMCU.
I am aware that the CH341 on the NodeMCU is bridged to the serial pins GPIO3(Rx) and GPIO1(Tx).
Hence, any data send on Rx and Tx is also visible on the serial monitor.
I need to interface MAX485 TTL-to-RS485 to the ESP8266 on different serial pins (other than GPIO3 and GPIO1).
Is there a way to configure other pins as Rx and Tx?
Please suggest any other ways to achieve this.
EDIT-1:
I need to use two serial ports at the same time (one with the CH341 and another with TTL-to-RS485). Please help with this.

You need to use the MAX3485 on 3.3V devices.

You can't redefine pins on the ESP8266. You can, though, use SoftwareSerial to emulate a serial port. There's plenty of examples.
Also you need to use the MAX3485 on 3.3V devices. The MAX485 is for 5V devices.

I get the MAX3485 part. However, my main problem is to use two serial ports at the same time (one with the CH341 and another with MAX3485). Need help with this problem.

Regarding this:

Please suggest any other ways to achieve this.

The SoftwareSerial mention in Majenko's answer is one of those other ways.
There's also a .swap() function on the Serial interface that will remap the UART from its normal position talking to the host to GPIO15 and GPIO13.  If you only need to talk to one device at a time, that may also be an option.
There's also a second transmit-only UART (also mentioned in previous link), so if you only need to transmit on one of the interfaces, that is an option.  And there's the possibility of using the transmit-only UART together with using SoftwareSerial (or something like it) to complete the receive half.
Another option might be interpose a SPI-interfaced UART chip, between the ESP8266 and the RS485 transceiver, so that it's just SPI from the ESP8266 side.  It is also possible to find chips that are combined SPI-UART/RS485-transceiver, although the only one I've noticed thus far is a 5V part.


text:
I got a problem in sending voice file
I wrote a code that can send a file.
If I send a text file it will work perfectly, but when I try to send voice it will send the whole file form the Sender side, but in the receiver side he won't understand some data or he won't read it i don't know what happened
i tried to send 50k byte and the  receiver only receive 20K
. I tried to send .wav .mp3 .m4p.
the Sender code
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <SD.h>

const int push1 = 2;

File myFile;
char a[168];
int c= 0;
int counter = 0 ;
unsigned long data;
unsigned long result;
unsigned long remaining ;

// network parameters
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
IPAddress localIp(10,131,41,72);    // local ip address
IPAddress destIp(10,131,41,74);      // destination ip address
unsigned int port = 9631;               // destination port

// EthernetUDP to send and receive messages.
EthernetUDP Udp;

// timing

// setup the arduino and shields
void setup() {

    pinMode(push1, INPUT);

  //Initialize serial and wait for port to open:
  Serial.begin(9600); // 19200
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // start ethernet and udp
  Ethernet.begin(mac, localIp);   // static ip version
  //if(Ethernet.begin(mac) == 0) {     // dhcp version
  // report failure to obtain network parameters
  // Serial.println("DHCP error");

  // no point in carrying on, loop indefinitely:
  // while(true)
  // ;
  //}

  // open UDP port
  Udp.begin(port);

  // show the local ip address (useful for dhcp)
  Serial.print("Local IP: ");
  Serial.println(Ethernet.localIP());

}

// do tasks
void loop() {

if(digitalRead(push1) == LOW){

    myFile = SD.open("SV12.wav");
     data = myFile.size();

//     result = myFile.position();

  if (myFile) {
    Serial.println("inside the file there's");
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      a[c] = myFile.read();
       Serial.print(a[c]);
       c++;
      if ( c==168){
        Serial.println("");
      Serial.println("i will send now");
      Udp.beginPacket(destIp, port);
      Udp.write(a,168);
      Udp.endPacket();
      delay(250);
      Serial.println("Sending UDP message");
       counter++;
       Serial.print("Sending packet#");
       Serial.println(counter);
//         for (int x = 0 ; x<c ; x++){
//
//         a[x] = '\0';}
         c=0;

  Serial.println("clearing");}

//  Serial.println(result);
    }

          if ( c<168 ){ // if (remaining)
      Serial.println("i will send now");
      Udp.beginPacket(destIp, port);
      Udp.write(a,168);
      Udp.endPacket();
      Serial.println("Sending UDP message Last segment");
//      counter++;
//         for (int x = 0 ; x<c ; x++){
//
//         a[x] = '\0';}
         c=0;}

    // close the file:
    myFile.close();
     Serial.println("im here");
    Serial.println(counter);
    Serial.println("END");
  } else {
   // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
 }

}
}

the Reciver code
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SD.h>

int LED = 8;
int x=0;

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x06
};
IPAddress ip(10,131,41,74);
IPAddress remIp(10,131,41,72);

unsigned int localPort = 9631;      // local port to listen on // 123456

File myFile;
char y[100];
int c= 0;

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

char packetBuffer[168]; //buffer to hold incoming packet,
//UDP_TX_PACKET_MAX_SIZE
void setup()
{
  // start the Ethernet and UDP:
  Ethernet.begin(mac, ip);
  Udp.begin(localPort);
  pinMode(LED, OUTPUT);
  Serial.begin(9600);//change and try
  Serial.print("Local IP: ");
  Serial.println(Ethernet.localIP());

    if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

}

void loop()
{

  int packetSize = Udp.parsePacket();

  if (packetSize)
  {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i = 0; i < 4; i++)
    {
      Serial.print(remote[i], DEC);
      if (i < 3)
      {
        Serial.print(".");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    Udp.read(packetBuffer, 168);
    Serial.println("Contents:");

    RandS();
    Serial.println(x); //to check the message

  }

}

void RandS(){

   myFile = SD.open("Last123.mp3", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.println("i'm Writing what i got from UDP");
    myFile.print(packetBuffer);
    x++;
    // close the file:
    myFile.close();

    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

}

Can someone help please?

Could you show the serial output?

Check: Does Udp.write(a) terminate on zero? Shouldn't it be something like Udp.write(a, c)?

how do you know that the problem is caused by the type of file? ..... have you verified that the problem is not related to file size?

I kind of solved the old problem and other problem showed up, i modify the question above hope you can see it and help, thx.

Hint: Add a sequence number and you might be able to detect dropped UDP packages. You might want to use TCP instead.

i printed that arrived packet there's no packet are dropped, I'm Trying to do audio streaming UDP is the best choice, the problem here is when I try to store the arrival packet on the SD card something wrong happened and it store only few bytes


text:
Can I configure pairing for HC-05 and Arduino, and use the HC-05 without Arduino after?
I have a system that is outputting data via its serial, and I need to relay that data to my PC wireless-ly. If I were to setup an Arduino and HC-05 at the system's side to relay the data, that would mean I need to use two serial ports. I know this could be done with SoftwareSerial library. However, I would like to know if I could set up the pairing between master and slave with arduino, then unplug the HC-05 from the Arduino, and connect it directly to the system's serial output. Would this work?
Edit for clarification:

I do not want to use SoftwareSerial
I do not want to use an MCU during normal operations
I want the HC-05 to take in serial data from a system's serial, and transmit it via bluetooth to my PC
Only during pairing configuration, will I want use an MCU (Arduino) to set it up. I want to know if the comms will still work when I take out the Arduino and connect the system's serial data output to HC-05's Rx instead.

Is this possible?

configure the HC-05 and pair it, then power it down .... power up again and run a sketch like the one in this question and test connectivity with serial monitor .......  https://arduino.stackexchange.com/questions/61469/does-baud-rate-for-hc-05-bluetooth-module-need-to-match-the-serial-monitor/61510#61510

I haven't built anything yet, I am just going through design planning before building it. Preferrably, I do not want to use SoftwareSerial. My idea is to pair it up with Arduino, and get the HC-05 to trasmit whatever serial data that comes into its Rx from the system - without an Arduino in place.

i understand your requirements .... the comment describes a process for confirming that the HC-05 retains its settings when powered off

IIRC, you can pull up (or leave unconnected) the KEY pin of the HC-05. Then it will act as the transparent serial connection you want.


text:
DS18B20 doesn't work reliably
like discribed in the title my temperature sensor goes to -127 after a few minutes of run time, it works again after a restart, I have already replaced the sensor and I'm using the same code for the temperature which I had used before which has been running flawlessly for almost 6 months now, I really have no clue what I did wrong hopefully someone got an idea.
Thank you!

There's not much information there to figure out what happened. Did changing the sensor fix the problem or did it continue with the new sensor? Providing a schematic of your sensor connection to the Arduino(?) would help. So would seeing a minimum sketch that still reproduces the problem. Both of those edited into your question, please.

Thank you for your reply but I just used a diferent library now.

decimal -127 is binary 11111111 ... reading all 1 bits is usually a wiring issue

Reading '0xFF' could be caused by poor grounding or insufficient power supply, incorrect pull-up resistor value or simply bad/fake chip. If the code you posted below as an "answer" is the code that you are  running, you are also causing the sensor self heat-up by constantly looping it. DS18B20 supposed to be read at once every second to avoid self heating.

There's a problem with using OneWire and Wire/I2C in one Sketch at once.
I believe this is because OneWire takes too long not sure, but this is probably why the temperature reading went to -127 after a while to fix thi.
I used an NTC 10K at 20°C. Below you can see code to make the NTC work and how to wire it!
Hope this helps!
Code:
#include <math.h>
const int thermistor_output = A1;

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

void loop() {
  int thermistor_adc_val;
  float output_voltage, thermistor_resistance, therm_res_ln, temperature;
  thermistor_adc_val = analogRead(thermistor_output);
  output_voltage = ( (thermistor_adc_val * 5.0) / 1023.0 );
  thermistor_resistance = ((5 * (10.0 / output_voltage)) - 10);
  thermistor_resistance = thermistor_resistance * 1000 ;
  therm_res_ln = log(thermistor_resistance);
  temperature = (1 / (0.001129148 + (0.000234125 * therm_res_ln) + (0.0000000876741 * therm_res_ln * therm_res_ln * therm_res_ln)));
  temperature = temperature - 273.15;
  Serial.print("Temperature in degree Celsius = ");
  Serial.print(temperature);
  Serial.print("\n");
  delay(1000);
}

Wiring:

Hi @Dennis, the point of this and the many other stack exchange web sites are to accumulate clear, concise and well-worded Questions and Answer to help others w/similar problems.  There is absolutely nothing wrong w/answering your own question. Consider editing your Title, Question & Answer to make it clear what was not working and how you fixed it.  Copy any important information from the comments and integrate them into the Question and Answer. Thanks.

Is this the solution to your own question, or is it meant as an addition. -- If the latter, you urgently need to take the [tour] to learn how this site works, it is not a forum. Then edit your question and add this content to it, then delete this non-answer.

-127 is the default code for an open wire.


text:
Detecting distance moved by accelerometer?
I have an accelerometer connected to an Arduino Uno board, is there a way I can detect the distance it this accelerometer moved on each of the 3 axis?

No, not with any meaningful accuracy, as has been previously explained each of the many times this has been asked on the various stack exchange sites.

Check out the way I calculated the distance traveled by an elevator using the ADXL345. It's not the most accurate or even easy, but I go through the whole process on my blog: https://engineersportal.com/blog/2017/9/25/accelerometer-on-an-elevator Let me know if you have any questions!

This is normally referred to as Dead Reckoning.  The processes of determining position using known values, such as acceleration.
First we have to relate acceleration, velocity and position mathematically.  Velocity is the integral of acceleration with respect to time:

Similarly, position is the integral of velocity with respect to time:

Here is an explanation that should tie this all together.  However, it appears this explanation goes in the reverse order.  That is using derivatives of position to find velocity.  And derivatives of velocity to find acceleration.  Simply put, finding a derivative is the opposite process of finding an integral.
A final note, this all works well on paper.  In reality Dead Reckoning based only on acceleration does not work very well.  For instance, I believe most vehicle GPS systems tend to use steering and speed if Dead Reckoning is to be used for guidance.
Added later...
Found this web site where someone talks specifically about Dead Reckoning using an Arduino. He is simply using the deltas of filtered acceleration readings:
velocity(i) = velocity(i-1) + acceleration (i)
position(i) = position (i-1) + velocity (i)

But goes on to say accumulated errors causes drift and positioning errors.

Comments are not for extended discussion; this conversation has been moved to chat.

Think about it:

Accelerometers measure acceleration.
Acceleration is a change in speed.
Distance travelled is speed multiplied by time.

If you know the starting speed (e.g., stationary) and you know how much you have accelerated between two points in time you can calculate the average speed for that time period - and since you know the time of that time period (one would hope) then you can get an approximation of the distance travelled in that axis.
I say approximation, because you are working with finite time points (quanta) and only looking at the acceleration at those points in time. It's far from perfect, but it can give you a rough ballpark figure. The smaller your quanta the better your accuracy - but it will never be anything more than a guestimation at best.
Now it's just, as they say, a SMOP.

Distance is the double integration of acceleration.

I downvoted this because it suggests you can get "an approximation" or "rough ballpark figure" when in reality you're not going to get anything useful out of this approach. The most important issue is that any inaccuracy in your acceleration measurement is going to blow up massively when you integrate to get position.

@TomvanderZanden I mentioned that it was a guestimation at best...  A guestimation, by the way, is worse than an estimation. An estimation is based on good data - a guestimation is based on guesswork, so is quadruply inaccurate. The link to SMOP is of course supposed to discourage the OP from taking this route since the programming would be outside his ability sphere.

@TomvanderZanden you still get usable figures depending on what precision you expect. And you can increase the quality using other sensors and filtering data. The dead reckoning technique can get extremely complicated, but the accelometric input is the base of most


text:
Detect movements of a person?
I'm working on a Virtual Reality game. I want to detect the position or movement of most of the bones in the human body(e.g. Knees, elbows, shoulders, hands and legs). This person may wear special equipment. How should I detect this?? I also want to get the distances between a certain position(e.g. The Arduino board) and each bone. Any ideas?

google for "arduino kinect" and you will get lots of ideas.

I'm sorry but saying you want to do some massively complex project and then asking for "any ideas" does not fit into the question-and-answer format of this site. Please narrow your question down somewhat.

What you're looking for is called motion capture. If you google it, you'll find a Wikipedia article that can give you a starting point for deciding which of the many available techniques will suit your project. Youtube also has several videos explaining motion capture, and different technologies.

The problem is that the player is not going to be visible

Please elaborate.

The player is going to be in a giant hamster ball, and he wouldn't be visible, so I need to use some kind of suit.

Bigger problem is that we are not a design bureau.  If we were, I doubt we would use Arduino for this in the first place.


text:
Unclear GET request mixed values
In my Uno code, I access to a page in my server and retrieve that value and make decision upon that value.
I get this kind of response,
Connected to server
on
on
off
off
on
off
[WiFiEsp] TIMEOUT: 116

Disconnecting from server.

Which should just be on or off.
This is my code for testing :
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif

char ssid[] = "RPi";            // your network SSID (name)
char pass[] = "raspberry";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.50.1";

// Initialize the Ethernet client object
WiFiEspClient client;

int c =0;
int testLED = 12;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET /simple.txt HTTP/1.1");
    client.println("Host: localhost");
    client.println("Connection: close");
    client.println();
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
  if (client.available()) {
     c = client.read();

     switch(c){
          case '0':
                 Serial.println("off");
                 digitalWrite(testLED, LOW);
                 delay(2500);
                 break;

          case '1':
                 Serial.println("on");
                 digitalWrite(testLED, HIGH);
                 delay(2500);
                 break;
      }
        }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true);
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

My simple.txt file just has 1.
Why this code outputs a gibberish value? Is it a problem with the way I retrive data?
Raspberry pi is working as my network server.
Thanks in advance.

What's with the huge delays?

@Majenko I put delay just for testing LED. It was not giving the result even without delay()

why are you using http if you connect to your raspberry?

@Juraj I connect to Raspberry-pi's web server.

When you send a GET request in HTTP you get a HTTP response back, not just the contents of the file you requested.
For instance, your request may result in a response of:
HTTP/1.1 200 OK
Date: Thu, 28 Dec 2017 11:02:21 GMT
Server: Apache/2.4.25 (Ubuntu)
Last-Modified: Wed, 05 Apr 2017 09:40:30 GMT
ETag: "2c39-54c682ee19688"
Accept-Ranges: bytes
Content-Length: 3
Vary: Accept-Encoding
Connection: close
Content-Type: text/plain

1

As you can see there's plenty of occurrences of 0 and 1 in there to trigger your LED.
You need to parse the incoming data better. Read it line by line and only start reacting to the content after the blank line that indicates the division between header and body.

Yes, I understood that. But how to parse those unwanted data from the response.

Keep a flag that says if you are in the header or not. The blank line tells you to change the flag, the flag tells you whether to interpret the data as commands. All the rest you ignore. If you want to read character by character then react to the end of line character and count the characters in a line. If the count is (not including the EOL characters) 0 then you have a blank line. You don't care what is in the header.

Can you provide me an example or a link to do these task. I just began Arduino

Discard everything up to a blank line. Then process that.

I found the answer for my question. @Majenko's answer helped me a lot.
I removed HTTP response given by the server and just changed few line in my original code. Also added # in-front of the number in my server's simple.txt file.
Also this arduino-forum post
void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
while(client.available() > 0)
{
  char c = client.read();
  if(c == '#')
  {
     while(client.available() == 0) { } // Do nothing while we wait for the next value
     c = client.read();
     if(c == '1'){
        Serial.println("On");
        digitalWrite(testLED, HIGH);
        delay(2500);
     }
     else if(c == '0'){
        Serial.println("Off");
        digitalWrite(testLED, LOW);
        delay(2500);
     }
  }
}

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    //client.stop();

    // do nothing forevermore
    while (true);
  }
}


text:
ATMega328P-PU and 328P-AU
im planing to make my very own arduino design based on the Arduino PRO mini. I picked this board instead of the UNO mostly because it's way more simpler compared with the UNO since the USB-to-Serial part is missing. As many of you know the MINI uses the 328P-AU which is the SMD version of the 328P however since the AU version is too small for me i would like to use the PU (UNO's chip) instead. From the datasheets the only difference is a small change in the pins position. And the one million dollar question is: Is there any difference on those 2 chips? If i try to use the same design just with the PU model is it gonna work?

There is no difference as far as Arduino is concerned. I think the AU has a couple extra pins (analog ins), that you might want to route to header locations in a surface mount design, but if your design is based on an Uno, them you can also just leave those pins disconnected with no impact.

I would go with the PU version because you can work on a breadboard with it for testing. If you are going to make a surface mount this to a PCB then use the AU. Regarding the actual difference forgetting about form factor, there is none.

You are wrong, the SMD version has two additional ADC inputs (ADC6 and ADC7).


text:
Internal volts in arduino for percent battery
I'm working on a small project that is creating me a headache. I know arduimo (ATmega 328P .... etc. ..) has an internal voltage source code millivolts, but I would like to know how the full source code become percentage where 3 volts = 0%  and 4.2 volts = % 100% ??? . I appreciate the help because in codes is not my forte. I leave the code so Help me complete. Thank you.
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

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

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

Mind you that the band gap reference is reasonably stable over time, but its absolute value in not very accurate. You may want to 'calibrate' the returned result from your readVcc function.

The charge on my arduino and something I'm doing wrong it gives me error :-(

Where did the code you posted come from? That's some pretty cryptic code.

"3 volts = 0% and 4.2 volts = % 100%" This sounds a lot like you are dealing with a battery, probably lithium of sorts, and you should be aware that battery remaining charge has some very non-linear regions. You will need something more complicated - a higher order equation, multiple regions, or a lookup table and interpolation.

Hello Duncan C sorry for replying so late but my job car electronics I removed my long wire-level and breakdowns but not at the programming level (low level) and I'm trying to develop a car burglar alarm so I need help . The source code I've taken from this website .  https://code.google.com/p/tinkerit/wiki/SecretVoltmeter

Hello Chris Stratton, if it comes to lipo batteries and discharge curve I got from this website: https://learn.adafruit.com/li-ion-and-lipoly-batteries/voltages

map()
unsigned char level = map(readVcc(), 3000, 4200, 0, 100);

You need to find a C language tutorial very badly, because you have no clue what you're doing, and you're not doing yourself or anyone else any favors like this.

sorry did not mean to, I just needed help, so asked.Thanks anyway

I do not in any way mind answering questions. The thing is that the fundamentals required to understand my answer are missing. Please take some time to familiarize yourself with C language structures.

@IgnacioVazquez-Abrams, I agree with your comment about needing a grounding in C. However, your answer uses the map function, which is part of the Arduino libraries, not straight C.

@DuncanC: Sure, but understanding how functions and function calls work and interrelate is.

Any idea why there's no comment button on the original question? I want to see if the code is the OPs or somebody else's.

@DuncanC: I'm almost certain it's not theirs.


text:
Arduino Based Solid State Drive
I've searched high and low for something to get me on the right track, it's making me think it might not be possible.
Basically, I want to create a cheap SSD using Arduino (or another microcontroller if it is too weak). I know I would have to implement the SATA protocol on the device and an OS driver for the disk drive. Assuming I could jump those two hurdles, what else would bar me from implementing a rudimentary SSD? I'm not even talking about full production quality, just a SATA wire coming from a mother board plugged into a socket on a breadboard. Do I need flash storage or would I need another kind of chip to handle the data needs?

Do you understand what SSD is standing for? Maybe you mean just some kind of SATA-connected storage?

If you want to do this just for fun, implement USB Mass Storage on a Leonardo backed by an SD card or SPI flash.  It will be painfully slow, but the concept will be there.  Outside of the Arduino realm, I expect you could find an existing project to do this with the STM32F4 Discovery board (which is cheaper anyway).

This is such an awesome quest, Creating a storage device from scratch to be used from a computer. I really hope you succeed and please post updates if you make it :)

The good news is that SATA drivers are fairly generic so you don't have to write the OS side. The bad news is everything else.
just a SATA wire coming from a mother board plugged into a socket on a breadboard
Let me stop you there. The minimum data rate for SATA is sufficiently high that you need a PCB. If you try and do this with wires or breadboards it will simply not get through; it will be lost to parasitic capacitance.
(Many years ago as a student I tried to do something vaguely similar with a wire-wrap board. At just 20MHz you could see a clean signal go in one side and a noisy unreadable mess come out the other side. Actually seeing it on a scope drove home the importance of shielding.)
Do I need flash storage or would I need another kind of chip to handle the data needs
Where would you put the data otherwise? It might be an entertaining first step to create a read-only drive with constant contents, but it's not very useful.
You need a chip with a SATA interface. This will almost certainly be an ARM and almost certainly not in DIP. I can't remember at the moment whether SATA master and slave "PHY" interfaces are different or whether it's all defined in software, someone else can answer that.

Sweet thanks for the info. I guess the Arduino is a very "beginner's" setup so I would want to get a more advanced controller for such an undertaking. Thanks for the info.

@pjc50 - He could implement a Write Only Memory - perhaps an emulation of the Signetics 9C46XN / 25120


text:
Using arduino mega with linear encoder to control movement of dispenser
My goal is to deliver very small quantities (100 microliters) of fluid to the (approximate) center of a 25mm x 75mm surface. My first idea was to repurpose an old inkjet printer for the project. I thought I'd load the fluid dispensers (probably 3ml syringes) into the unit where the ink cartridges would go and use an arduino to manipulate the linear encoder used by the printer to tell the dispenser unit where to go.
Main problem at the moment is that I'm having trouble getting the dispenser unit to go exactly where I want it to. I've tried incorporating the PID library into my code to get the head to oscillate around the desired position until it stops at the right location. However the oscillation never stops and the head always moves beyond the desired position.
I'm trying to figure out the easiest way to get this done. Maybe that'll mean moving away from using the inkjet printer but I'd like to get some feedback here before I make any decisions.
Code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
#include <PID_v1.h>

//
//// Interrupt information
//// Int 0 on pin 2
//// Int 1 on pin 3 Not used
//
#define encoderI 2  // Interrupt 0 is use
#define encoderQ 4 // Only use one interrupt in this example
#define maxPos   3733 // left hand side
#define minPos   0    // right hand side
#define maxSpeed 150
#define minSpeed 0
#define Freq     1600
#define maxWait  500 //12 millisec before stopping the motor
#define maxPositionError 10 //max error from actual desired position. It is approximately 0.032 of an inch
#define PIDsampleTime 25

//
//// Tuning parameters
double kP=0.37; //Initial Proportional Gain
double kI=2; //Initial Integral Gain
double kD=0.020; //Initial Differential Gain
double Drive = 0;

int outputSign;
//
double Setpoint, Input, Output;

PID myPID(&Input, &Output, &Setpoint,kP,kI,kD, DIRECT);

volatile int ActualHeadPosition; //current position will be modified with each interrupt
volatile int PreviousHeadPosition; //Previous position will be modified with each interrupt
volatile uint8_t Speed = maxSpeed;                      //Speed for the dispenser head
volatile unsigned long lastPositionTime;
volatile int setPoint;
volatile int Err;
volatile int lastError;
volatile int Integral;

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
//
//// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *dispenserDCMotor = AFMS.getMotor(1);
//
void setup() {
     Serial.begin(9600);           // set up Serial library at 9600 bps also this is the baud rate per second for the input?
     pinMode(encoderI, INPUT); //pin #2 is assigned as an input
     pinMode(encoderQ, INPUT);
     attachInterrupt(0, handleEncoder, CHANGE);
//
     AFMS.begin(Freq);
//
//    // Set the speed to start, from 0 (off) to 255 (max speed)
    dispenserDCMotor->setSpeed(Speed);
    dispenserDCMotor->run(FORWARD);
//    // turn on motor
    dispenserDCMotor->run(RELEASE);
//
  Setpoint = 1800;
  myPID.SetSampleTime(PIDsampleTime);
  myPID.SetOutputLimits(minSpeed, maxSpeed);

    //turn the PID on
    myPID.SetMode(AUTOMATIC);

     //Initialize procedure should be the first thing
    Initialize();
}

void loop() {
  Serial.print(", ActualHeadPosition: ");Serial.print(ActualHeadPosition);Serial.print(", SetPoint: ");Serial.println(setPoint);

  setPoint = 1800;
  Input = ActualHeadPosition;
  outputSign = myPID.Compute();
  Err = setPoint - ActualHeadPosition;
  Serial.print("PID Output");Serial.print(Output);Serial.print(" Error: ");Serial.println(Err);
  Speed = Output;
  if (Err > 0){
    moveLeft();
    Serial.println("moveLeft");
  }
   else if (Err < 0){
     moveRight();
     Serial.println("moveRight");
  }

};
//
void handleEncoder(){
  lastPositionTime = millis();
   PreviousHeadPosition = ActualHeadPosition;
   if(digitalRead(encoderI) == digitalRead(encoderQ)){
     //dispenser is moving to the left
     ActualHeadPosition++;
   }
   else {
     //dispenser is moving to the right
     ActualHeadPosition--;
}

 }

void moveLeft(){
  uint8_t i;
  dispenserDCMotor->run(FORWARD);
  dispenserDCMotor->setSpeed(Speed);
}

void moveRight(){
  uint8_t i;

  dispenserDCMotor->run(BACKWARD);
  dispenserDCMotor->setSpeed(Speed);
}

boolean isMotorMoving(){
  if (((millis() - lastPositionTime) > maxWait))
    return false;
  else
    return true;
}

void Initialize(){
    //Move to origin
    moveRight();
    while (isMotorMoving()){
  //    Serial.println("MOVING!");
  delay(10);
    }
    ActualHeadPosition = 0;
    PreviousHeadPosition = 0;
    dispenserDCMotor->setSpeed(0);
    dispenserDCMotor->run(RELEASE);

}

maybe you just have to tune your pid settings

The easiest option, using the code you have, is to spend a little time tuning the PID algorithm. The lines you are interested in are these
double kP=0.37; //Initial Proportional Gain
double kI=2; //Initial Integral Gain
double kD=0.020; //Initial Differential Gain

PID takes a setpoint and a current location, calculates error, and uses it to make a new output that should sent the location to the setpoint. It does this by adding
P*(error)+I*(all historic error added together)+D*(recent change in error)
By changing the multipliers P, I, and D, you change how it reacts to different situations. In your system, the D value will have very little effect (at least in my experience). You should probably keep that where it is, or even just set it to 0.
The P value controls direct response to error, and should be the main component in your setup. Try increasing this to make it move faster, and mildly decrease the oscillations.
The I value controls how much all historic error affects output. It is the factor leading to all the oscillations. Lowering it will make your output settle sooner. It also assists when fighting other constant forces, or if static friction keeps the head locked in one position too close for the P term to overpower. My guess is in your isolated and low friction system, it should be very low.
Increment these values slowly (.05 at a time maybe) and experiment, you should be able to fix your oscillations and make the system behave how you want.

Based on the description, the system is underdamped, and increasing D may help a lot.  Decreasing I can help too - I is most useful in correcting standoff errors - when it never actually reaches the target.

"I" is useful for such errors, but I suggest lowering it because the inkjet printer rails should not have much problem with friction or outside forces. In my experience, "D" is nearly inconsequential in similar systems, but I encourage experimentation. In any case, an underdamped system should need the damping ratio increased to 1, but increasing "D" would lower the damping ratio if my math is correct, based on this article: https://en.wikipedia.org/wiki/Damping#Example:_mass.E2.80.93spring.E2.80.93damper

I haven't worked with inkjet printers, so I may be offbase. I was working off my memory, reinforced by this As I understand it, when the error is dropping quickly as you approach the target, D dials down the gain, helping prevent overshoot.

I was referencing a model of PID as altering the coefficients on a 2nd order Diff EQ, but your link directly on the tuning of PID could be more accurate, depending on the actual characteristics of his system. experimentation is key.

The reason why your slide/microarray microdispenser continually oscillates about a point rather than dispense the fluid containing your cells/DNA sample specifically at a particular specified/designated point on your slide/microarray is due to your code below:
if(digitalRead(encoderI) == digitalRead(encoderQ)){
     //dispenser is moving to the left
     ActualHeadPosition++;
   }

   else {
     //dispenser is moving to the right
     ActualHeadPosition--;
}

which tells the Arduino to actuate the motor regardless of the values stored in the vars encoderI & encoderQ.

You can try changing this part of the code to the following instead:
`if((digitalRead(encoderI) == digitalRead(encoderQ)) && ActualHeadPosition != setPoint){
//dispenser is moving to the left
ActualHeadPosition++;
}
else if (ActualHeadPosition != setPoint) {
//dispenser is moving to the right
ActualHeadPosition--;
}
Also, make sure to changeSetpoint = 1800;in 'void setup()' tosetPoint = 1800;` instead. Please note that due to comment limitations in Stack Exchange, in places where there are large spaces, this is actually a line break.


text:
Can I use ATtiny48 as a board in Arduino?
I have seen people using ATtiny45 and other boards and there are hardware configurations files for them. Can we use ATtiny48 as a processor for Arduino?
If so where can I get a boards.txt file that supports it? Alternatively how can I write such a file?

@Gerben that is "MEGA48" ...


text:
Two Arduinos Send data via Analog Pin?
What I want to do is allow Arduino A to send some constant value to Arduino B.
I sense something inherently wrong with my approach, but I cant figure out what it is.
So in the diagram below you will see Arduino A setting its Analog Pin 0 as OUTPUT and write a value 2 every 500ms. On Arduino B we have Analog Pin 0 set as INPUT to receive and print data to Serial. The GND pins of both Arduinos are also connected.
When this setup is executed, Arduino B is constantly receiving data in the form of a 3 digit number starting with 3XX. I am starting to believe this is voltage value?
What is inherently wrong with this idea?

No I do not live in the EE world, but I can try! Excellent answers here, I am trying to absorb it all. Will update soon.

@lucidgold The summary at the start of my answer tells you exactly what to do. The rest tells you why.

This answer provides both Arduino specific knowledge and general electrical knowledge - both are necessary for a good solution (unfortunately).

Summary
To carry out Arduino analog to analog transfer:

Use analogWrite(pin, value) on a valid digital pin (see below)
Use analogRead(pin) on a valid analog input pin.
Connect a series resistor between the two pins - say 10k.
Place a capacitor from the analog input to ground, say 100 nF to 10 uF.

The R & C act as a low pass filter to convert the PWM to DC.
Details below.

Arduino analog pins are ONLY for analog input, not for analog output.
So trying to do analog out on an analog pin dooms your attempt to failure.
Arduino analogWrite(pin, value) only works on DIGITAL pins and then only on the subset of digital pins that have PWM capability. This is typically digital pins 3 5 6 9 10 11.
"analogWrite(pin, value)  produces as others have said - a PWM signal - rail to rail square waves with mark space ratio that varies so the mean DC value changes. For a 5V system  =
V_DC_mean ~~= value/256 x 5V.
Where 'value' comes from analogWrite(pin, value)
To convert the PWM to good-enough DC a low pass filter with a cutoff somewhat below the PWM frame rate is needed. AFAIK Arduino PWM frame rate is about 800 Hz -  so components are usually higher than that. A simple RC filter where R x C is usefully more than about 0.001S will start to work . Larger RC is smoother but with secondary effects. Using a 10 uF ceramic cap and a 10k resistor is probably OK. 10 uF x 10k = 0.1S. 1uF and 1k = 0.001 s = marginal. An electrolytic cap can be used but leakage current may slightly affect accuracy. So -

From somewhere in Arduino land (unknown) I copied the material below.
This is NOT in the basic reference, but should be.

Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.
On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.
The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.

analogWrite() on the Uno doesn't actually output an analog value. It outputs a PWM wave whose average is equivalent to that value. If you want to turn it into a true analog value then you need to put it through a low-pass filter in order to remove the components that make it a PWM wave instead.

This is hardly unique to arduino/ATmega; very few microcontrollers contain true DACs, excepting sigma-delta blocks uniquely tailored to audio.

If your aim is to send a constant value from Arduino A to Arduino B, then a really easy way is to use SoftwareSerial.
Let's say you are using Arduino Uno - you can use pins 2 and 3 for SoftwareSerial (see which pins are supported for which device at http://arduino.cc/en/Reference/SoftwareSerial)
Cross connect pin 2 and 3 from Arduino A to pin 3 and 2 of Arduino B. You can send any random data between the two Arduinos by uploading a sketch like the following on to each. You can use a program like CoolTerm to have a "SerialMonitor" open to each Arduino (using the Arduino IDE, you can open only one monitor at a time)
The advantage of this approach over using AnalogWrite/AnalogRead is that with AnalogRead, you can only get 1024 values, which is based on the voltage. With SoftwareSerial, you can send any arbitrary data.
// include the SoftwareSerial library so you can use its functions:
#include <SoftwareSerial.h>

#define rxPin 2
#define txPin 3

SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

void setup() {
    pinMode(rxPin, INPUT);
    pinMode(txPin, OUTPUT);

    mySerial.begin(9600);

    Serial.begin(9600);
 }

void loop() {

    if ( mySerial.available() )
    {
         while ( mySerial.available() )
             Serial.write(mySerial.read());

         Serial.println();
    }

    if ( Serial.available() )
    {
        delay(5);

        while ( Serial.available() )
            mySerial.write( Serial.read() );
    }

}

As others have pointed out, your original suggestion will not work.
You could use PWM output and a filter which may work (you will need quite a large capacitor and/or resistor). The input at the other end would only be an approximation of the output (you could calculate based on detailed knowledge of component values and frequencies). Depending on the rate at which the value changes you may get different values on each read.
There are better ways. As suggested, serial will work (either hardware or software depending on other factors), and is probably easiest. You could use any of the common communication protocols (I²C or SPI) or even send values via IP.

The Analog In does exactly what it says - it only reads (samples) analog voltage levels.
Using AnalogWrite(0,2) does not make pin A0 in Analog In to output the voltage of 2*AVCC/1024, but instead makes the pin D0 to do that instead. (Most D0 pins on Arduino boards do not have a PWM output associated with them, so the behaviour would be undefined.) In the mean time, your A0 is doing nothing.
(I suspect it's floating / not connected, hence the 3xx value. Could check the datasheet to be sure.)
So what should we do instead? For a start, connect Arduino B's A0 to Arduino A's pwm pin. If you're using Uno, you can connect to any of the pins 11,10,9,6,5,3. Then you can use the code:
int PWMPin = 11;
int SignalLvl = 2;
analogWrite(PWMPin,SignalLvl);
Give that a try. And you'll see that it works... sort of.
But then there's a problem. your readings will be close to what you want, but quite erratic. The reason is partly because analog signals are super unreliable and is filled with noise. But the main reason is really that Arduino's analogWrite is actually NOT designed as an analog signal output. It is a PWM, which outputs GND and AVcc levels at variable periods at a fast speed so that it approximates the voltage level you want when averaged.
If you want to experiment with this, you can connect a resistor and capacitor to the output, creating  a low pass filter. (Here's more info: http://provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/)

Having said all that, I guess the question most of us would like to ask is: is there a reason why you want to send data via analog? Analog signals are prone to noise. If data fidelity is critical, your best best is to use serial communication as highlighted by most answers here.
For simplicity, I suggest I2c which uses only 2 wires to communicate. If speed is of essence (like, writing to 10,000 bytes of data every second) you could try SPI or even parallel communication.
Hope this helps and good luck!

As has been mentioned above, using analogWrite won't work. (I suppose you could sample the supposed analogue signal with a fast loop and measure the duty cycle...)
Why not use SoftwareSerial to send data between the two Arduinos?
It's a library which creates another serial port, entirely in software, so it's independent of the main UART on the USB port.
It's already part of the IDE and it's easy to use - in fact the demo code on the help page will already work for you, transferring any characters from the USB serial port to the software serial port.

AnalogWrite is perfectly OK as long as a simple 1 x resistor and 1 x capacitor filter are added (see my answer). There may be good reason to use analog which is not evident here.


text:
Disable verification of certification SSL A7670SA
I have the code below and it doesn't work with my URL. I receive a

715(Handshake Failed)

This code below works normally, but with my API it doesn't work.
I'm using a A7670SA with Arduino Mega 2560.
My API is on Heroku and uses an Automated Certificate Management by Heroku, that uses the Let's Encrypt.
String sendATCommand(String command, String expectedResponse = "", unsigned long timeout = 5000) {
  Serial1.println(command);
  Serial.println("Command send: " + command);

  unsigned long startTime = millis();

  String response = "";

  while (millis() - startTime < timeout) {
    if (Serial1.available() > 0) {
      char c = Serial1.read();
      response += c;
    }
  }

  response.replace(command, "");

  Serial.println(response);

  delay(500);
  return response;
}

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

  delay(1000);

  Serial1.begin(115200);

  sendATCommand("AT", "OK");

  sendATCommand("AT+CGREG?");
  sendATCommand("AT+CGDCONT=1,\"IP\",\"claro.com.br\"", "OK");

  sendATCommand("AT+HTTPINIT");  // Iniciar ambiente HTTP

  sendATCommand("AT+HTTPPARA=\"URL\",\"https://httpbin.org/\"");

  sendATCommand("AT+HTTPACTION=0", "OK", 1000);

  sendATCommand("AT+HTTPREAD?");

  sendATCommand("AT+HTTPTERM", "OK");
}

void loop() {}

what is your specific question?


text:
IR sketch keeps getting the same code: 4294967295
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremote.h>

// Khai báo địa chỉ I2C của màn hình LCD
LiquidCrystal_I2C lcd(0x27,16, 2);

// Khai báo chân analog A0 (cảm biến độ ẩm)
const int moisturePin = A0;
// Khai báo chân analog A1 (cảm biến nhiệt độ)
const int tempPin = A1;
// Khai báo chân analog A2 (cảm biến ánh sáng)
const int lightPin = A2;

#include <Servo.h>
Servo myservo1; // Khởi tạo đối tượng Servo
const int servoPin1 = 2; // Chân điều khiển Servo 1
Servo myservo2; // Khởi tạo đối tượng Servo
const int servoPin2 = 3; // Chân điều khiển Servo 2
Servo myservo3; // Khởi tạo đối tượng Servo
const int servoPin3 = 4; // Chân điều khiển Servo 3
Servo myservo4; // Khởi tạo đối tượng Servo
const int servoPin4 = 5; // Chân điều khiển Servo 4

int servoPos = 0; // Biến lưu trữ vị trí của Servo

// Khai báo chân điều khiển relay cho đèn (dựa trên độ ẩm)
const int lightRelayPin = 13;
// Khai báo chân điều khiển relay cho quạt
const int fanRelayPin = 12;
// Khai báo chân điều khiển relay cho đèn (dựa trên nhiệt độ)
const int tempLightRelayPin = 11;

// Ngưỡng độ ẩm quy định để mở relay (độ ẩm cao hơn sẽ mở relay)
const int moistureThreshold = 500;
// Ngưỡng nhiệt độ quy định để bật quạt
const int highTempThreshold = 300; // Nhiệt độ cao hơn sẽ bật quạt
// Ngưỡng nhiệt độ quy định để bật đèn
const int lowTempThreshold = 100;  // Nhiệt độ thấp hơn sẽ bật đèn

// Ngưỡng cường độ ánh sáng quy định để thực hiện hành động
const int lightThreshold = 30; // Giá trị cường độ ánh sáng

// Biến lưu trữ trạng thái chế độ (auto hoặc manual)
bool autoMode = true;

// Khai báo đối tượng IRrecv và mã học từ remote
const int RECV_PIN = 8;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  // Khởi tạo cổng Serial với tốc độ 9600 bps để ghi log dữ liệu
  Serial.begin(9600);

  // Khởi tạo màn hình LCD
  lcd.init();
  lcd.setCursor(0,0);
  lcd.backlight(); // Bật đèn nền LCD
  lcd.display();

  // Đặt chân điều khiển relay là output
  pinMode(lightRelayPin, OUTPUT);
  pinMode(fanRelayPin, OUTPUT);
  pinMode(tempLightRelayPin, OUTPUT);

  // Kết nối Servo với chân điều khiển
  myservo1.attach(servoPin1);
  myservo2.attach(servoPin2);
  myservo3.attach(servoPin3);
  myservo4.attach(servoPin4);

  // Khởi tạo đối tượng IRrecv
  irrecv.enableIRIn();
}

void loop() {
  // Kiểm tra nếu có dữ liệu từ remote
  if (irrecv.decode(&results)) {
    // Lưu giá trị mã học vào biến code
    unsigned long code = results.value;
    Serial.println(code);
    // Xử lý dữ liệu từ remote
    if (code == 4294967295) { // Mã học của nút "Auto Mode"
      autoMode = !autoMode; // Chuyển đổi chế độ tự động
      // Hiển thị trạng thái chế độ lên LCD
      Serial.println(code);
      lcd.clear();
      lcd.setCursor(0, 0);
      if (autoMode) {
        lcd.print("Auto Mode: ON");
      } else {
        lcd.print("Auto Mode: OFF");
      }
      delay(1000); // Đợi 1 giây để tránh việc nhận các lệnh liên tiếp từ remote
    }
    irrecv.resume(); // Tiếp tục nhận dữ liệu từ remote
  }
}

Ignore the mess that I have made on the top.
I tried the script in a simulator and found out that every button I pressed gave me the same code, which is 4294967295.

yoir code is very cluttered ... comments are not part of the program, put some space between the code and comments

what happens if you change the 4294967295 to a 4294967294?

It could be a problem with the simulator (you don't say which simulator you are using), they aren't necessarily an accurate representation of the actual hardware. See How to simulate Arduino? for more info.
However, assuming that the simulator is working correctly...
The value 4294967295 is 0xFFFFFFFF (or MAXINT).
If you receive this MAXINT value then the remote button may be repeating.
Try this sketch (which apparently works well in TinkerCAD):
#define DECODE_NEC
#define IR_RECEIVE_PIN      3

#if !defined(RAW_BUFFER_LENGTH)
// Maximum length of raw duration buffer. Must be even. 100 supports up to 48 bit codings inclusive 1 start and
// 1 stop bit.
#define RAW_BUFFER_LENGTH 100                                                                                \
// #define RAW_BUFFER_LENGTH  112    // MagiQuest requires 112 bytes.
#endif

#define EXCLUDE_UNIVERSAL_PROTOCOLS   // Saves up to 1000 bytes program space.
#define EXCLUDE_EXOTIC_PROTOCOLS      // saves around 650 bytes program space if all other protocols are active

#include <IRremote.hpp>

void setup()
{
  Serial.begin(115200);
#if defined(__AVR_ATmega32U4__) || defined(SERIAL_PORT_USBVIRTUAL) || defined(SERIAL_USB) || defined(ARDUINO_attiny3217)
  delay(1000);
#endif
  Serial.println(F("START " __FILE__ " from " __DATE__ "\r\nUsing library version " VERSION_IRREMOTE));
  Serial.println(F("Enabling IRin..."));
  IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);
  Serial.print(F("Ready to receive IR signals of protocols: "));
  printActiveIRProtocols(&Serial);
  Serial.print(F("at pin "));
  Serial.println(IR_RECEIVE_PIN);

  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8,OUTPUT);

}
void loop() {

  if (IrReceiver.decode()) {
    //IrReceiver.printIRResultShort(&Serial);
    switch(IrReceiver.decodedIRData.command) {
        case 0x10:  Serial.println("1");  // Button 1
                    digitalWrite(5,HIGH);
                    break;

        case 0x11:  Serial.println("2"); // Button 2
                        digitalWrite(5,LOW);
                        break;

        case 0x12:  Serial.println("3");  // Button 3
                    digitalWrite(6,HIGH);
                    break;

        case 0x14:  Serial.println("4"); // Button 4
                    digitalWrite(6,LOW);
                    break;

        case 0x15:  Serial.println("5"); // Button 5
                    digitalWrite(7,HIGH);
                    break;

        case 0x16:  Serial.println("6"); // Button 6
                        digitalWrite(7,LOW);
                        break;

        default: Serial.println(IrReceiver.decodedIRData.command);
    }
    IrReceiver.resume(); // Receive the next value
  }
}

If this sketch works, and it verifies that your hardware is OK, then you can adapt this to make your own sketch work.

References

Problem with the IR Remote