text:
Running Python on Arduino
I've been using Python for quite long, and I was wondering if it can be used as a programming language for Arduino, rather than C/C++.
When I'm using the Arduino IDE, the sketch is compiled into a hex file that contains the program binary.

Knowing that micro controllers execute only binary, I would like to know if there is a tool to convert Python code into binary, so that I can upload it directly to Arduino using AVR or other programmers.
I read about Micro Python, a lightweight adaptation of Python that can fit in boards, but can only work with PyBoard, which I have never used yet.
I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in IOT.

Python is an interpreted language with a lot of libraries.  You would need either an interpreter squeezed into the Arduino, or a compiler that makes assembly code from Python (maybe by way of C.)  Too much hassle for too little gain.

And I say that as someone who uses Python extensively in personal projects.  I like Python - but not on my Arduino

Adafruit has a few boards that run microPython. As far as I know, those will interpret code, so don't require precompiled binaries.

@Gerben Do you know some examples ?

Their website has whole range of board that run their version of microPython. See https://www.adafruit.com/circuitpython

To my knowledge, there is not a "python to ATMega architecture" compiler out there.
However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.
Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.

Can the arduino mega run Python ?

The GitHub repo, ports directory, indicates no support for ATMega processors, which is what is in an Arduino Mega.


text:
ARDUINO IDE debug level for stack trace only (nodeMCU 1.0)
What is the minimum debug level (TOOLS tab) which will display the stack trace on crash?
I would like to reduce information clutter in the serial monitor.
I understand that debug port must point to my serial monitor.
In case it makes a difference, it is a NodeMCU, running C++, in Arduino IDE on a Ubuntu 16.04 machine.

The crash report is printed to 'standard output' by __wrap_system_restart_local in core_esp8266_postmortem.c in esp8266 Arduino core.
The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by Serial.setDebugOutput(true);.
At compile time the initial debug output is controled by -DDEBUG_ESP_PORT=, for example -DDEBUG_ESP_PORT=Serial1. The Tools menu "Debug port" sets the DEBUG_ESP_PORT define. The crash report is not controlled by "Debug level" setting.

Tks.  Compiles.  Testing.  Is it your evaluation that a question regarding the purposes and effects of Debug Level would be appropriate?

take a look into the boards.txt file in the esp8266 boards package installation folder

source: Stack Exchange

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

sort: votes


text:
Servo motor (HSR-1425R) not running continuously
I'm trying to programme a servo motor to reach certain positions. I have a 360 degrees servo motor, so I can not use the Servo library and I can only control the speed. Therefore I want to regulate the time for the pulse. The setup is simple, 5 V, GND and pin 9 from the Arduino to the motor.
int servo1 = 9;

void setup{
    Serial.begin(9600);
    pinMode(servo1, OUTPUT);
}
void loop{
    digitalWrite(servo1, HIGH);
    delay(5000);
    Serial.println(digitalRead(servo1));
    digitalWrite(servo1, LOW);
    delay(5000);
    Serial.println(digitalRead(servo1));
}

Expected:
I expect the code to run the servo motor at full speed for 5 seconds.
Actual:
The motor runs at the first impulse and pauses for 10 seconds.
How can I improve the code to do what I expect?

what are your hardware connections and why are you reading an output pin?

My hardware connections are the three wires from the servo directly to the Arduino. I wanted to see what signals were sent.

Why do you think you cannot use the Servo library?  With continuous rotation servos it generally works where 0 spins one way 180 spins the other and something close to 90 stops it.

Also, to control that servo you don't just set the pin HIGH.  You have to send a specific pulse length that tells the servo how fast and what direction to rotate.  It is the same sort of signal that tells a regular servo what angle to go to.  That's why the Servo library is normally used to control these.

Apply some impulse which you need your servo to work on

Look at how servo motors are typically controlled. As far as I know there are no servos that can just be "enabled to rotate" like you seem to expect.
Usually a servo's position is set by applying a pulse of a specific length. This means you can apply a PWM signal with proper frequency. Then the duty cycle should be proportional to the servos position. From my experience timing is quite critical when controlling a servo, so going the way you do (timing a gpio's output state with delay()s) will not work well. You have to use the atmega's hardware modules (which already is the case when using the arduinos digital write) to achieve adequate timing.

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


text:
C++ trim char array
I have a char array of length 10.  It gets filled with an unpredictable number of chars, usually up to 6.
char charDummy[10] = "";

When i concatenate the char array with another, I get spaces, which are unwanted in later parsing.
char postStr[300] = "";
strcat(postStr, "&field1=");
strcat(postStr,dtostrf(rain05m,6,2,charDummy));

How do I trim a char array directly?
Workaround: loop thru the array and copy valid characters to a new char array with perfect number of rows.  Due to memory constraints, I need to be parcimonious with the amount of variables created.

Your problem is that dtostrf() right-aligns the value in the space allotted to it.  The simple answer is to tell it to left-align instead:

Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the possible '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.
AVR LIBC Manual

So, just make your width negative and it will left align.

@tony gil: The string terminator (ASCII 0) has nothing to do with NULL and is never referred to as NULL. NULL is a completely different, unrelated thing in C and C++.


text:
Best way of storing extra data for Arduino project
I am an arduino beginner and I am trying to make a speed camera alert system, it would start beeping if I am above the speed limit and getting close to the speed camera. There is this website where I can get all the data I need, coordinates, direction and speed limit of every 36000 speed cams in my country.
I would need some extra memory space to be able to store all this data, would an eeprom chip do the job? and would it be able to keep up with a for loop going through all those 36000 speed cam locations to check if i am close to it and above the speed limit?
Edit: since going through all those locations on a loop would be a lot for the processor to handle, someone recommended the creation of a temp file that would narrow that list down by direction, and when that direction changed it would recalculate that temp file. This is what I came up with:
void setup() {
  int tempDirection = gpsDirection;
  writeTempFile();
}

void loop() {
  //this will recalculate the temp file when the gpsDirection changes
  if(gpsDirection > tempDirection +5 || gpsDirection < tempDirection -5){
    tempDirection = gpsDirection;
    writeTempFile();
  }

  for(temp file){
    if(distance <= 100 && speed > speedlimit){
      //start beeping
    }
  }
}

void writeTempFile(){
  //this will write a temp file with every cam with a direction that's similar the gps direction
  for(each line of the file){
    if(gpsDirection + 10 > camDirection || gpsDirection - 10 < camDirection ){
      add cam to temp file;
    }
  }
}

SD card and ordered data

EEPROM would works. SD is probably easier to keep up-to-date, and about the same price.

EEPROM writes are limited to about 100k cycles.  They are for permanent or semi-permanent data (like your absolute speed threshhold - 120kmh, for example).
You should not store your speed camera base here.
Get a MicroSD adapter and save your data there.  Looping thru 36000 speed trap locations is going to put a toll on your processor and memory.  I recommend that you determine a binding box (+/- 2 degrees, for example) and save a temp file with only those traps inside the box.  recheck every time your position changes a full degree (N/S or E/W).
Notice: in some countries, Brazil for example, distributing information regarding speed trap locations is illegal (obstruction of justice).

I edited my post adding some code based on that binding box idea of yours to improve the processing. Would you give me your thoughts on it?

Been working wih GPS applications since 1995:i wouldnt work with direction, youd have to go into more complex calculations, which will eat your clock.You could store them by latitude (file21S.txt, file22S.txt, file23S.txt,...) and, depending on the lat you are on, you open the specific file.  Or you could have smaller files with latLon (file22S51W.txt, file22S52W.txt, file21S51W.txt and so on)


text:
ATMega328P chip on breadboard does not work properly
I wanted to get some help about my ATMega328P on my breadboard. I programmed a simple clock like this -
#include <LiquidCrystal.h>
#include <dht.h>
#include <DS3231.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
dht DHT;
DS3231  rtc(SDA, SCL);

void setup() {
  rtc.begin();
  lcd.begin(16,2);

}

void loop() {

  int chk = DHT.read11(9);
  delay(1000);
  lcd.print("Temp: ");
  lcd.print(DHT.temperature);
  lcd.print(" ");
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humi: ");
  lcd.print(DHT.humidity);
  lcd.print(" %");
  lcd.setCursor(0,0);

  delay(5000);

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Time:  ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());
  delay(5000);

  lcd.clear();
 }

The code works when ATMega328P is connected on the Arduino Board itself, everything is showing correctly. But when I remove the chip (when it's already programmed) and place it on the breadboard, do all the necessary wirings, it only outputs me the words Humi and Temp without even showing the proper values (-999.0 degrees it shows me). I triple-checked my connections and found nothing. And after those 5 seconds of waiting, I finally got Time, and nothing is there, only the text, not even those weird numbers. And it doesn't even reload back to Temp and Humi, it just stays on Time word forever.
I have feeling that loop doesn't work properly somehow.
EDIT: I found out what was the problem about reseting, BUT STILL the proper values doesn't show up
Can you help me out, please?

Why do you suspect the loop() function, when you've already seen it work correctly? You've supplied the code but you already know that works. We need to see the breadboard wiring that you said is failing, since that is the difference between working and non-working systems. Despite triple-checking your wiring, you've apparently found a problem with reset. What was the problem and what was the solution? Could that guide you to other wiring problems? Please post a schematic, or at least a clear and accurate wiring diagram of your breadboard. Without that, we can only guess.

Did you add some (bypass) capacitors on the breadboard, between VCC and GND? Place them as near to the chip as possible. Secondly, try wiggling all the wires in the breadboard. Sometimes their don't make proper connection.

Pretty sure a hardware issue related to the breadboard environment...

Alright, I figured it out myself, thanks. Yeah, there was a hardware problem. A5 pin somehow didn't work properly.. Now it does.


text:
Accelstepper - how to switch from fullstep to halfstep in loop?
I am using Accelstepper library to control a unipolar stepper motor. In my project, I would like to run the stepper in full-step mode when I need speed and in half-step mode when I need precision. As you know, the full-step/half-step selection is done in the very beginning of the sketch...
I found a workaround by creating two instances of Accelstepper for the same stepper. That is:
Accelstepper fast(FULL4WIRE, 2,3,4,5);

Accelstepper slow(HALF4WIRE, 2,3,4,5);

With this, when I call (skipping other details of the code) fast.run() the motor moves fast (full-step) and when I call slow.run() it moves slowly as it is in half step mode.
But;
When it comes to determine to current motor position, this workaround fails, since there are two different values returned by the two functions: fast.currentPosition() and slow.currentPosition(). So this workaroud becomes useless.
My first question is: is there a way in Accelstepper to switch from full-step to half-step and vice versa in the execution(let say in the loop)? If so, the second question can be skipped.
The second: XX.currentPosition() function returns the value of a variable, namely "_currentPos" which is calculated in Accelstepper.cpp file. As I understand, there become, as many _currentPos values as Accelstepper instances. In my case, one for fast and another for slow, and somehow they are kept and calculated individually without any confusion. Is there a way to access (extern?) and set this variable from the sketch, by referencing the specific Accelstepper instence? Briefly, is there a way to copy one motor position to another?
Many thanks.

The documentation notes a setCurrentPosition() function.

void AccelStepper::setCurrentPosition ( long position )

Resets the current position of the motor, so that wherever the motor happens
  to be right now is considered to be the new 0 position. Useful for
  setting a zero position on a stepper after an initial hardware
  positioning move. Has the side effect of setting the current motor
  speed to 0.
Parameters
position The position in steps of wherever the motor happens to be right now.

Use the currentPosition() function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

Jose, thanks for the answer. But it doen't solve the problem. Consider, the motor is at zero, when it moves 100 steps via fast.run() and then it moves 50 steps via slow.run()...In this case, fast.currentPosition() returns 100 and slow.currentPosition() returns 50, but in fact motor is at position 150! Notice, there is only one single motor although declared 2 times. By reseting the position with setCurrentPosition, you lose your starting point. If you mean that I should record the movements and recalculate in my sketch it becomes too complex as the movements are dependent on many sub-functions

Sorry I wasn't more clear. Also use the currentPosition() function. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

I thought that the setCurrentPosition() function is only for setting the current motor position to "0". However, it is possible to set current position to anything. So, with this info, it became possible to copy/add one motor position to the other just by considering the step sizes.


text:
Segmentation fault and huge SRAM need for Serial.println
I have written my own 'assert' since I want to use it for both Windows and Arduino. The class is called from many files (about 10).
AssertUtils.h:
#pragma once

#define assert(expr) AssertUtils::Assert2((expr), (__func__), (__FILE__), (__LINE__));

class AssertUtils
{
public:
    static void Assert2(bool expression, const char* funcName, const char* fileName, int line);
};

AssertUtils.cpp:
#include "AssertUtils.h"
#include "Arduino.h"

/* static */ void AssertUtils::Assert2(bool expression, const char* funcName, const char* fileName, int line)
{
    if (!expression)
    {
        Serial.println(funcName);
        Serial.println(fileName);
        Serial.println(line, DEC);
        Serial.flush();

        // Abort program execution.
        abort();
    }
}

When I compile this, the SRAM usage is 1469 bytes (together with the rest of my sketch and classes).
When I comment the line below, I get a segmentation fault in a random assert call (when I comment out that call, I get it in the next, etc.).
    //Serial.println(funcName);

When I also comment out the second print statement, the compiler reports only 1137 bytes SRAM usage (which I expect since this was about equal until before I added the Assert class).
    //Serial.println(funcName);
    //Serial.println(fileName);

Questions:

How can I get rid of the segmentation fault?
How can it be that about 332 bytes are used for one two additional print statements? (maybe related to the const char* buffering (?)

the  segmentation fault is a bug in compiler in 1.6.22 and 1.6.23. more here https://forum.arduino.cc/index.php?topic=619213.msg4195749#msg4195749

try F(__FILE__) and F(__func__). (change the parameter type to __FlashStringHelper)

@Juraj Somehow it only works for __FILE__ but not for __func__. Anyway using F( __FILE__) was about -90B difference (It's probably full path and it was only used in one file).

so the compiler optimizes the parameters away if hey are not used

Why are you wasting a class on this? Just use the prints directly in the macro.

@juraj Thanks (see answer, but feel free to add your own if you want an upvote from me)

@KIIV Thanks (see answer, but feel free to add your own if you want an upvote from me)

@Majenko Thanks (see answer, but feel free to add your own if you want an upvote from me)

Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.
What I did was:

(Juraj) Changed the compiler version to 6.21
(juraj) Added an F in F(__FILE__)
(KIIV) Removed func; this did not work with the F flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
(Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.
The resulting code is below:
#define assert(expression) \
  if (!(expression)) \
  { \
    Serial.println(F(__FILE__)); \
    Serial.println(__LINE__, DEC); \
    Serial.flush(); \
    abort(); \
  }

About class - in this case it was used as old form of namespaces (as namespaces weren't present in c++ until 1990). However struct was used more likely as it doesn't need public: specifier.


text:
Can I power Arduino with 12V 1.2A adapter
I am new to arduino and i am making a smart energy meter for my home. I want to run the arduino months so, how to power arduino with a adapter, I have a 12V 1.2A adapter is it ok to power arduino with it or not?.
Thanks in advance.
As i said i want to run it long time.

read the documenation pertaining to your version of arduino

I have arduino smd

this one or other? https://store.arduino.cc/arduino-uno-smd-rev3

If it is an Arduino Uno Rev3 SMD, the documentation (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

Operating Voltage     5V
Input Voltage (recommended)   7-12V
Input Voltage (limit)     6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.
Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.

Yes, you can power an Arduino with 12V into the barrel connector. It will then use it's internal voltage regulator to drop that to the 5V it needs internally. However, that is on the high side of it's recommended range, and will make the Arduino's voltage regulator run hot. A 7.5V supply would be better, and you could probably get more total current out of the 5V regulator without overheating if you fed it 6V or 7.5V instead of 12V. (6V is the lower limit. >= 7V is better.)
(A linear voltage regulator like the one in most Arduino boards essentially uses a transistor as a variable resistor to lower the voltage from the input voltage to 5V, which converts the excess voltage to heat. The higher the input voltage, and the more current you draw from the regulator, the more heat it generates.)

The 12V power supply is unlikely getting hot (without loading it near it's full power). But the on board voltage regulator is different story. Also there is no linear power supply on the arduino board, it's just the linear voltage regulator. Just for correcting terminology.

That's what I meant. Good call on the wrong term. I'll fix stat


text:
Float division returns "inf" and 0
I'm new to Arduino and I'm doing an ultrasonic project where I test for the speed of sound. My code is below and for some reason, this is what the serial port returns:
This is the measured speed of sound: inf m/s
This is the measured speed of sound: 0m/s
This is the measured speed of sound: 0m/s
etc...
Here's my code. Any help's massively appreciated:)
int trig = 13;
int echo = 11;
float target_distance = 0.3;
float recieved;
float speed_of_sound;

void setup() {
    Serial.begin(9600);
    pinMode(trig, OUTPUT);
    pinMode(echo, INPUT);
}

void loop() {
    digitalWrite(trig, LOW);
    delayMicroseconds(2000);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);

    recieved=pulseIn(echo, HIGH);
    recieved = recieved*1000000.0;
    speed_of_sound = (2*target_distance)/recieved;
    Serial.print("This is the measured speed of sound: ");
    Serial.print (speed_of_sound);

    Serial.println("m/s");
    delay(3000);
}

What do you expect the division of 0.6 with 1000000  * some value?

Assuming the speed of sound is of the order of 330 m/s, you expect
the round-trip to the target and back to last about 1.8 ms. Then
recieved = pulseIn(echo, HIGH);

should give a value close to 1,800, and
recieved = recieved * 1000000.0;

should make received something like 1.8 × 109.
Then
speed_of_sound = (2*target_distance)/recieved;

gives a speed of sound of 3.3 × 10−10. It is the
correct value if you want that speed in meters per picosecond, but this
is inconsistent with your program printing “m/s” after the value.
The Arduino's Serial.print() is quite dumb with floating point
numbers. It defaults to printing two digits after the decimal point,
irrespective of the order of magnitude of the number. Thus, anything
smaller than 0.005 gets printed as “0”.
I don't quite understand why you got ∞ on the first loop. Looks like
pulseIn() missed the pulse and returned zero, in which case the speed
is computed as 0.6 ÷ 0 = ∞.
The solution is to compute received as
recieved = pulseIn(echo, HIGH) * 1e-6;

This can be remembered by thinking that a quantity (round-trip time) is
a numeric value (pulseIn(echo, HIGH)) multiplied by a unit (1e-6,
which stands for “microseconds”).

nice, thorough answer. (voted)

Ah, a maths error... thats embarrasing. I assumed it was my code. Thanks for taking the time to help though! I just changed the faulty line to: recieved = recieved/1000000 and apart from the first line being  "inf", it works well now.

@ThisUsernameHasBeenTaken: Scanning the available datasheets didn't turn up any anomalies related the first measurement. I would take a practical approach to it by triggering the device once during setup() and ignoring that result.


text:
ESP8266 official library post request returns 400
Every time I try the post request I get a 400 error but the JSON and URL are identical to those that I used on an online API tester and it worked every time there. I am running this program in the official Arduino IDE and most of this code was taken from the ESP8266 official library here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h
if (http.begin(client, host)) {  // HTTP

  http.addHeader("Content-Type", "application/json");
  // Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  // int httpCode = http.GET();
  String request = "{ \"temperature\": 27.0, \"humidity\": 43 }";
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(request);

and the value of host?

client is an instance of the WiFiClient object and host is a variable declared to the url with my private key included.

error code 400 is "Bad request" and it is a HTTP response from the server

Right, but I'm trying to figure out what the inconsistency is between my code and the API tester I used. The JSON and URL are identical.

only other thing you provide is host in sketch

So maybe my JSON is formatted incorrectly? I just want it to show up as {"temperature": 27.0, "humidity": 43}

it would not be 400. 400 is wrong status line or headers. maybe some missing header?

What header would be missing? I'm not very familiar

some invalid characters in url (host) which should be encoded? space or %

I don't think there's any invalid characters. The format is as follows: https://redacted.redacted.net/some/stuff/here/fad34552435jdasfaghh8?private_key=8342yfsadh4jh38fh27df8

https protocol?

Here is the recommended cURL from the documentation: curl -H "Content-Type: application/json" -X POST
-d '{ "timestamp": 1541519720, "value": 76.5 }'
https://myfarm.farmos.net/farm/sensor/listener/xxxxxx?private_key=yyyyyy

Oh it is https:// could that be my problem here?

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino

I changed the URL to http and now it is giving a 301 error moved permanently. I will take a look at the HTTPS example instead, the reason I avoided was because they had an expired fingerprint so I wasn't sure if it would work (honestly don't even know what the fingerprint is for).

I used some online generator for the fingerprint and switched to HTTPS and it is working and the JSON data is showing up on the server. Thanks for your help. Since you solved my question if you'd like to post something as an answer I will mark you as the answer.

400 is a HTTP error "Bad request" sent by the HTTP server. Possible reasons for this error are malformed HTTP request line, malformed HTTP request headers, missing empty line after the last HTTP header and a request to 'secure' port without encryption.
In your case the HttpClient library constructs the HTTP request so there should be no error. Only thing you supply for the request is the URL in your case it is the variable host. As we cleared in comments, your URL started with https. The HttpClient library parsed the url, detected the https protocol and used the secure port 443. But the underlying networking Client object was not SSL so it didn't encrypt the request.

Thank you for your help!

I appreciate the explanation of what went wrong, but how can we make it work?

@jezmck in this case it would be using the WiFiSecureClient as shown in the BasicHttpsClient example


text:
Wemos D1 is not triggering Relay
Update: I realized my relay module was 12V and the current leaving the digitalpin from my Wemos D1R1 is only 3.3V. I bought a 5V relay module that I read in some articles that it could work, but it didn't.
My new question is: is there an easy and simple way to amplify the voltage leaving the D5 pin so it could control the 12V or the 5V relay module? I tried using and logic level converter from 3.3V to 5V but had no success. Ideas?

I am having issues with a simple project using Wemos D1 and a relay board. I followed a tutorial that was supposed to work out fine (https://www.instructables.com/id/Control-a-Lamp-With-ESP8266-and-a-Relay/), but for some reason I still don't know it is not working.
I read that it could be that the D5 pin has not enough energy to trigger the relay and change its state. So I tried using a logic level converter and still it didn't work.
I am attaching the image of my board/connections and also the logic level converter (https://br.banggood.com/3_3V-5V-TTL-Bi-directional-Logic-Level-Converter-For-Arduino-p-949438.html), plus my code below.

void setup() {
  // put your setup code here, to run once:
    Serial.begin(115200);

}

void loop() {
  digitalWrite(5, HIGH);
  Serial.println("HIGH");
  delay(3000);
  digitalWrite(5, LOW);
  Serial.println("LOW");
  delay(3000);
}

Does anyone have any idea of what could be happening? And how to make it work?

I can't quite see the text under the red wire connected to the Wemos D1. Does it say 5V? I'm asking because the relay requires 12VDC to operate.

yep. its 5V. I think I'll try with 12V and get back here if it still doesnt work

D5 is not io 5. use D5 in code

Still no success. Just got a 12V 2A powersource and still it doesnt trigger the delay. Also changed 5 to D5 in the code, and nothing happened.

try connecting the signal pin of the relay right to ground and vcc; do either of them actuate?

No. I tried putting it on the gnd and vcc coming from the 12V power supply and it works. I need to provide also 12V to the pin, apparently.


text:
HTTP and HTTPS server at the same time
I'm trying to set up a HTTP and HTTPS server at the same time on an ESP8266 NodeMCU V3. The compiler however doesn't accept any other name than client otherwise no new clients will be catched. But client cannot be used twice and I cannot get it to switch every loop because of the different data-type; WiFiClient and WiFiClientSecure.
Is what I'm trying to accomplish even possible?
Sketch.ino

// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_HTTPPORT  = 80;
const int   CONFIG_HTTPSPORT = 443;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <ESP8266WiFi.h>

// Create webserver object
WiFiServer HTTPserver(CONFIG_HTTPPORT);
WiFiServerSecure HTTPSserver(CONFIG_HTTPSPORT);
static const uint8_t rsakey[] PROGMEM = {
  #include "key.h"
};
static const uint8_t x509[] PROGMEM = {
  #include "x509.h"
};

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

  // Wait for WiFi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected!");

  // Print WiFi connection information
  Serial.print("  MAC Address: ");
  Serial.println(WiFi.macAddress());
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Gateway: ");
  Serial.println(WiFi.gatewayIP());

  // Start webserver
  Serial.println("Starting webserver...");
  HTTPserver.begin();
  HTTPSserver.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
  HTTPSserver.begin();
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Hostname: ");
  Serial.println(WiFi.hostname());
  Serial.print("  HTTP Port: ");
  Serial.println(CONFIG_HTTPPORT);
  Serial.print("  HTTPS Port: ");
  Serial.println(CONFIG_HTTPSPORT);

}

// Loop instructions
void loop() {

  // Wait for new client
  WiFiClient HTTPclient = HTTPserver.available();
  WiFiClientSecure HTTPSclient = HTTPSserver.available();
  if (HTTPclient || HTTPSclient) {
  }

}

UPDATE (2019-06-05):
I've tried @KIIV's method which works! However it brings a new problem into the equation. HTTPS requests take pretty long te complete, currently about 2 seconds. And it makes the HTTPS request twice for some reason (see log; I made only one request after setup).
Sketch-updated.ino

// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_HTTPPORT  = 80;
const int   CONFIG_HTTPSPORT = 443;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <ESP8266WiFi.h>

// Create webserver object
WiFiServer HTTPserver(CONFIG_HTTPPORT);
WiFiServerSecure HTTPSserver(CONFIG_HTTPSPORT);
static const uint8_t rsakey[] PROGMEM = {
  #include "key.h"
};
static const uint8_t x509[] PROGMEM = {
  #include "x509.h"
};

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

  // Wait for WiFi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected!");

  // Print WiFi connection information
  Serial.print("  MAC Address: ");
  Serial.println(WiFi.macAddress());
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Gateway: ");
  Serial.println(WiFi.gatewayIP());

  // Start webserver
  Serial.println("Starting webserver...");
  HTTPserver.begin();
  HTTPSserver.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
  HTTPSserver.begin();
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Hostname: ");
  Serial.println(WiFi.hostname());
  Serial.print("  HTTP Port: ");
  Serial.println(CONFIG_HTTPPORT);
  Serial.print("  HTTPS Port: ");
  Serial.println(CONFIG_HTTPSPORT);

  // Setup complete
  Serial.println("Setup completed");
  digitalWrite(LED_BUILTIN, 0);
  Serial.println();

}

// Loop instructions
void loop() {

  // New wait for new client
  if (HTTPserver.hasClient()) {

    // Set client to HTTP for this loop
    //auto client = HTTPserver.available();
    WiFiClient client = HTTPserver.available();

    // Response
    Serial.println("This is HTTP");
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/plain");
    client.println("Connection: close");
    client.println();
    client.println("This is HTTP");

  } else if (HTTPSserver.hasClient()) {

    // Set client to HTTP for this loop
    //auto client = HTTPSserver.available();
    WiFiClientSecure client = HTTPSserver.available();

    // Response
    Serial.println("This is HTTP Secure");
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/plain");
    client.println("Connection: close");
    client.println();
    client.println("This is HTTP Secure");

  }

}

Serial Log
15:59:34.121 -> Starting setup
15:59:34.121 -> Connecting to: mywifi
15:59:34.452 -> .............
15:59:38.205 -> WiFi connected!
15:59:38.205 ->   MAC Address: XX:XX:XX:XX:XX:XX
15:59:38.238 ->   SSID: mywifi
15:59:38.238 ->   RSSI: -21 dBm
15:59:38.238 ->   IP Address: 192.168.1.121
15:59:38.238 ->   Gateway: 192.168.1.1
15:59:38.238 -> Starting webserver...
15:59:38.238 -> Webserver started!
15:59:38.238 ->   Hostname: ESP_XXXXXX
15:59:38.238 ->   HTTP Port: 80
15:59:38.238 ->   HTTPS Port: 443
15:59:38.271 -> Setup completed
15:59:38.271 ->
16:00:38.069 -> This is HTTP Secure
16:00:38.833 -> This is HTTP Secure

I'd try if there is client awaiting first: if (HTTPserver.hasClient()) { auto client = HTTPSserver.available(); /* do something; */ } and the same for HTTPS. (and maybe optimistic_yield(1000) as it's used inside of available so it'll be almost the same

@KIIV your method works! It however also causes a problem; HTTPS requests take a really long time to complete. Between 5-10 seconds, which also triggers a timeout function (not present in example code). This long time is not happening when trying a sketch which only uses a HTTPS server.


text:
Whats the maximum external voltage/current i can apply through an Arduino Uno ? + a couple mini questions
i'm just starting out with electronics and Arduino's and was wondering about the extent of an Arduino's ability. Will i eventually be able to program and power very high voltage/current requiring devices such as a full sized fan motor? Also at what point would i not be able to use normal wires, components and breadboards due to a high current/voltage (not sure which one would break them).
I know these are total noob questions but thanks in advance!

Arduino Uno
First, never use too high voltages on GPIO pins of an Arduino. if you want to know, search for 'absolute maximum current' or 'absolute maximum voltage'. Probably any pin of an Arduino is about 5 V (plus some headroom).
External power
So since your fan will use more voltage high likely, you are not lost, in contrary, you should use a separate power source (giving the voltage you need for the fan), and use either a relay, or a transistor or MosFet. Than you can program it with a 5 volts pin and control a much higher voltage device (your fan).
Wires
Do not send high voltages/currents through breadboards and jumper wires neither. Use separate wiring, and you can check tables using AWG (thickness of wires) to see how much current they can support. Note that I say current, not voltage. The voltage will drop depending on the length of the wire and the size, so calculate that you have enough voltage at the end of the wire.
Safety
Also for safety, do not forget a fuse, and remember that the external power source and all wires have the same voltage as the fan, which may kill you if you touch them.

Thanks for the in depth answer! The fan was just an example but could you go into a bit more detail in programming a fan? How would i connect it to the Arduino? i couldnt just attach it to pin 11 or whatever and pretend its a servo motor so how would you go about doing something like this?

I don't know how your fan works, first find out in the datasheet or description what the protocol is (just adding power on it? use a relay), some work with PWM (use a PWM signal and transistor/mosfet), if it is a servo motor, than you might need additional components, like a servo motor driver, check for examples, there are plenty on internet).

arduinos, and microcontrollers in general, handle only very small ammounts of current, and they work at what is called 'logic level' voltage, usually much lower than 'line' voltage or 'mains,' which is your wall outlet. in general an arduino will put out 30-50 mAh per pin, and max of about 200mAh combined. again, the total ouput for the entire board is a max of about 0.2 amps. the idea is that the pins are pulled high or low (+5 or ground) depending on the logic of the programming. these signals trigger logic level components to act, usually mosfets/transistors and relays turn higher loads on/off
basically, you dont want to power even a single led without a current limiting resistor. its just a microcontroller after all


text:
OTA push sketch to NodeMCU
Similar questions regarding Arduinos mention the existence of tools that would enable the pushing of sketch updates to NodeMCU via WiFi / OTA (Over The Air).
Does this proceed?  If so, please indicate the proper tools.

Arduino IDE supports upload to a network port. Network ports are detected with mDns and made available in Tools>Port menu.
The ArduinoOTA library bundled with the esp8266 Arduino boards package supports upload from IDE with 'network port' over WiFi. See the example of the ArduinoOTA library available in Examples menu in IDE.

Yes, there exist methods to update codes through OTA in Wifi-modules/NodeMCU. You will first need to allot an IP address to your device which will later be used as a port to carry out OTA transmission. Look out to this tutorial-https://circuitdigest.com/microcontroller-projects/esp8266-ota-update-programming-using-arduino-ide


text:
LED doesn't turn on as specified on code State Machine
This is the question from the homework I'm doing "Design and implement a state machine with a single button to turn on and off two LEDs The first LED should be turned on and off with a quick press of the button, the second LED should turn on and off with a long press (1 second)."
I have this code
int state_s1 = 0;
int state_s2 = 0;
int state_s3 = 0;
int state_s4 = 0;
int state_prev_s1 =0;
int ledPin2 = 8;
int ledPin = 9;
int boton = 10;
int boton2 = 11;
int val_s1 = 0;
unsigned long t_0_s1 = 0;
unsigned long t_s1 = 0;
unsigned long t_s2 = 0;
unsigned long tiempo = 50;
unsigned long bounce_delay_s1 = 5;
unsigned long bounce_delay_s2 = 1000;
boolean prendido = false;
boolean prendidoP = false;

void setup()
{
  pinMode(boton, INPUT_PULLUP);
  pinMode(boton2, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  SM_s1();

  if(prendido == true)
  {
    led();
  }

  if(prendidoP == true)
  {
    led2();
  }

   Serial.print("state 1 =");
   Serial.println(state_s1);

   Serial.println("************");

}

void led()
{

  switch(state_s1)
  {
    case 0:         //OFF
    digitalWrite(ledPin, LOW);
    t_0_s1 = millis();
    state_s1 = 1;
    break;

    case 1:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
      state_s1 = 2;
    }
    break;

    case 2:         // ON
    digitalWrite(ledPin, HIGH);
    t_0_s1 = millis();
    state_s1 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
     state_s1 = 0;
    }
    break;

  }
}

void led2()
{

  switch(state_s4)
  {
    case 0:         //OFF
    digitalWrite(ledPin2, LOW);
    t_0_s1 = millis();
    state_s4 = 1;
    break;

    case 1:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
      state_s4 = 2;
    }
    break;

    case 2:         // ON
    digitalWrite(ledPin2, HIGH);
    t_0_s1 = millis();
    state_s4 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
     state_s4 = 0;
    }
    break;

  }
}

 void SM_s1()
 {
  switch(state_s2)
  {
    case 0:         //RESET
    state_s2 = 1;
    break;

    case 1:        //START
    val_s1 = digitalRead(boton);
    if(val_s1 == LOW)
     {
      state_s2 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s1 = millis();
    state_s2 = 3;
    break;

    case 3:         //WAIT
   if(val_s1 == HIGH)
     {
      state_s2 = 0;
     }

    t_s1 = millis();

    if(t_s1 - t_0_s1 >= bounce_delay_s1)
    {
      state_s2 = 5;
    }
    break;

    case 5:         //ARMED & WAIT
    t_s2 = millis();
    val_s1 = digitalRead(boton);
    if(val_s1 == HIGH && t_s2-t_s1 < bounce_delay_s2)
     {
      state_s2 = 4;
     }

     if(t_s2-t_s1 >= bounce_delay_s2)
     {
      state_s2= 6;
     }

    break;

    case 4:       //TRIGGERED
    state_s2 = 0;
    prendido = not prendido;
    break;

    case 6:     // ARMED 2
    state_s2 = 0;
    prendidoP = not prendidoP;
    break;

}
}

It will work the first time but then the LEDs won't turn off and sometimes when the button is pressed hard, it will turn both LEDs on, please help me.

please use the {} button to format the code

how do you press a button hard? ... is the button touch sensitive?

case 3 never reads if the button is pressed. It only uses the old value stored in case 1. I think case 3 should start with a val_s1 = digitalRead(boton);

Do you have the state-diagram for us, as the code is hard to understand with all those meaningless variable names.


text:
How to write code to make the LED’s ﬂash in the following sequence?
How to write code like this sequence? What is the meaning of 4 decimal?
For this, we had to add a delay in the code
led_Pin_1 1 0 0 0
led_Pin_2 0 1 0 0
led_Pin_3 0 0 1 0
led_Pin_4 0 0 0 1

my code, It is working. But I need to convert this code to above sequence?
int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  digitalWrite(led_Pin_1, HIGH);
  delay(200);
  digitalWrite(led_Pin_2, HIGH);
  delay(200);
   digitalWrite(led_Pin_3, HIGH);
  delay(200);
   digitalWrite(led_Pin_4, HIGH);
  delay(200);
  digitalWrite(led_Pin_1, LOW);
  delay(300);
   digitalWrite(led_Pin_2, LOW);
  delay(300);
   digitalWrite(led_Pin_3, LOW);
  delay(300);
   digitalWrite(led_Pin_4, LOW);
  delay(300);
}

your third question makes no sense .... also the comment about the delay makes no sense

please help me to write this code

No sir, I asked Is my code correct or not. If incorrect my code help me

what do you see when you run the code?

read the question that you posted .... you did not ask if your code is correct or not

int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

int led_on = 0; // Start with first (led_Pin_1)

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(led_Pin_1, (led_on == 0) ? HIGH : LOW);
  digitalWrite(led_Pin_2, (led_on == 1) ? HIGH : LOW);
  digitalWrite(led_Pin_3, (led_on == 2) ? HIGH : LOW);
  digitalWrite(led_Pin_4, (led_on == 3) ? HIGH : LOW);
  delay(250);

  led_on = (led_on + 1) % 4;
}

led_on will start with 0 (pin 1), switching only that pin on. Some explanation:
(led_on == 0) ? HIGH : LOW

This means: if (led_on == 0), than the value will be HIGH, otherwise LOW. Resulting in only pin 1 going on, if led_on is 0, and in the next loop, only pin 2 oing on, because led_on is 1 etc.
led_on = (led_on + 1) % 4;

This increases the value of led_on, but when it reaches 4, it reverts back to 0.
I don't know about the delay times you need. I guess you want to change all LEDs at once, than wait.
You can make the 4 almost identical digitalWrite lines into a function as small improvement.
If you want to do more with the LEDs, than consider storing the leds into an array and use a for loop to iterate through them.


text:
Help understanding how avrdude works with ArduinoISP and why its not working for me
I am trying to use avrdude with a Mega2560 running ArduinoISP
Note: I have the 10uF cap on the Mega2560 RESET line as described by Ardunio.
Also, I am using avrdude/6.3 on Windows 10.  The Mega2560(ArduinoISP) is connected to the PC using an a USB cable - connection is COM8.
I have a couple of tasks I want to do

Update the firmware on my USBASP
Load Arduino boot on ATTINY85 dev board.

I started with Arduino IDE but moved to avrdude to better understand the problem
For #1:
Wired it per https://www.arduino.cc/en/Tutorial/ArduinoISP
AVR-ISP pin     MEGA-ISP pin
6/10 (name)

1/9 (MISO)      50
2/2 (VCC)       VCC
3/7 (SCK)       52
4/1 (MOSI)      51
5/5 (RESET)     53
6/10 (GND)      GND

I tried using the command:
avrdude -c arduino -p m8 -P COM8

I get the error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xed
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

avrdude done.  Thank you.

--UPDATE-- The error above was caused by not setting the BAUD rate. Now I get:
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

What I really want to know is more of how this process works so I can better understand it and be able to debug the issues.

Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?
What does "stk500" mean?  Is that the programming protocol, the ISP protocol, or something all together different?
Is this all documented somewhere?

baud rate, fuses? use IDE to burn the botloader

I get similar errors when I try to use the IDE (which I believe uses avrdude in the bacground.  That is why I am focused on understanding avrdude.  Note: I normally use the IDE but not with a ISP.

Please add info about the wiring.

Added wiring info

programmer is not responding seems to show the problem is with the programmer, not the target. 2. stk500 is the protocol the Arduino uses to program itself. I don't think this should be the protocol to use when using the Arduino-as-ISP, but it's been a while. 3. Not really. All the info is out there, but not in one place.

I think -c arduino should be -c avrisp -b 19200

@Gerben baud rate appear to have been what was causing the 'not responding'.  It now responds but I get 'Invalid device signature'.

What signature do you get?

the command for Uno as target and "Arduino as ISP" is avrdude -C avrdude.conf -v -patmega328p -cstk500v1 -P/dev/ttyACM0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m as you can see in IDE console when you use "Burn bootloader"

@Juraj That is pretty much the same as what I am using but 1)my target is different, and I am no writing of fuses and  lock

@Gerben 'avrdude: Device signature = 0x000000'

@MikaelPatel I added detail on the wiring to the OP

@Gerben Re:Not really. All the info is out there, but not in one place  I am finding some stuff and collecting it and will add it as a Answer so it can at least be in this one place.

the Arduino as ISP page doesn't show wiring for USBASP or ATiny

@Juraj Arduino ISP page shows the pin numbers on each ISP board type by AVR-ISP signal name.  I just connect those to the same signal name on the target (USPASP/ATTINY).  For one example (USPASP) I added the specific connections.

Device signature = 0x000000' means it can't see/communicate with the target.

You have the use the correct reset pin on the USBasp. You can't use the 'reset' pin on the programming header on the USBasp, as that's is just a GPIO output pin on the ATMega8. It seems that some of the board have a jumper to connect this pin to the reset on the ATMeag8. Not properly resetting the target could give you the incorrect signature error.

The target board was not reset.
The "Arduino as ISP" sketch uses pin 10 to reset the target, not the SS pin. So even on Mega, wire reset of target to pin 10, not to pin 53.

Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?

the first error "not in sync" is a problem with communication with the programmer. it was caused by wrong baud rate. the "invalid signature" is a response from the programmer about target. if the signature could be read avrdude would print the target MCU type. all zeros signature is when the target doesn't answer. so check the wiring.

What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?

yes it is a ISP programming protocol. the "Arduino as ISP" implements only this protocol

Is this all documented somewhere?

this is AVR MCU world, not Arduino. you can google avrdude reference, stk500 reference etc

This got it working.  How did you know it was the reset?

I use "Arduino as ISP" quite often. You could accept the answer to mark the question solved

Just recall that the question was not just to solve the immediate issue; but, to know how to trace the symptoms to the cause.  If you can add how the symptoms pointed you to the RESET connection then that would be a more complete answer.  Also I need to test it with the other test case.

the "check the wiring" rule. I enhanced the answer


text:
Please help me combine the two codes for DHT11 and SW-420 Vibration sensor for arduino in one program
The following is the code used for DHT11 Temperature and Humidity sensor:
#include <LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 0, 1, 2, 3);
byte degree_symbol[8] =
              {
                0b00111,
                0b00101,
                0b00111,
                0b00000,
                0b00000,
                0b00000,
                0b00000,
                0b00000
              };
int gate=11;
volatile unsigned long duration=0;
unsigned char i[5];
unsigned int j[40];
unsigned char value=0;
unsigned answer=0;
int z=0;
int b=1;
void setup()
{

lcd.begin(16, 2);
 lcd.print("Temp = ");
 lcd.setCursor(0,1);
 lcd.print("Humidity = ");
 lcd.createChar(1, degree_symbol);
 lcd.setCursor(9,0);
 lcd.write(1);
 lcd.print("C");
 lcd.setCursor(13,1);
 lcd.print("%");
}

void loop()
{

 delay(1000);
 while(1)
 {
  delay(1000);
  pinMode(gate,OUTPUT);
  digitalWrite(gate,LOW);
  delay(20);
  digitalWrite(gate,HIGH);
  pinMode(gate,INPUT_PULLUP);//by default it will become high due to internal pull up
 // delayMicroseconds(40);

  duration=pulseIn(gate, LOW);
  if(duration <= 84 && duration >= 72)
  {
      while(1)
      {
        duration=pulseIn(gate, HIGH);

        if(duration <= 26 && duration >= 20){
        value=0;}

        else if(duration <= 74 && duration >= 65){
        value=1;}

        else if(z==40){
        break;}

        i[z/8]|=value<<(7- (z%8));
        j[z]=value;
        z++;
      }
    }
answer=i[0]+i[1]+i[2]+i[3];

if(answer==i[4] && answer!=0)
{
lcd.setCursor(7,0);
lcd.print(i[2]);
lcd.setCursor(11,1);
lcd.print(i[0]);
}

z=0;
i[0]=i[1]=i[2]=i[3]=i[4]=0;
 }
}

The following is the code for SW-420 Sensor:
int LED_Pin = 13;
int vibr_Pin =3;

void setup(){
  pinMode(LED_Pin, OUTPUT);
  pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurment
  Serial.begin(9600); //init serial 9600
 // Serial.println("----------------------Vibration demo------------------------");
}
void loop(){
  long measurement =TP_init();
  delay(50);
 // Serial.print("measurment = ");
  Serial.println(measurement);
  if (measurement > 1000){
    digitalWrite(LED_Pin, HIGH);
  }
  else{
    digitalWrite(LED_Pin, LOW);
  }
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

Assuming the DHT11 Pin configuration remains unchanged and you can change the pin configurations for SW-420 vibration sensor, please give me a combined code for the two sensors to display results in one program. Thanks a lot.

Hello and welcome to Arduino! Please take the tour and visit the helpcenter to see how things work here.

Have you already tried combining those sketches? If yes, what's the problem you actually have? If no, try it. We are not supposed to do the job for you but we'll guide you to the solution.

There are multiple threads on how to combine two different sketches. One of the main things you have to do is refactor your code to get rid of calls to delay(). Do a Google search on Arduino blink without delay and read one of the tutorials you find. The idea is to make a call to the millis() function for each thing you want to do on a time intervl, save the current millis count, and then wait until the new value of millis() is greater than the saved value by your desired time interval. By doing that, your code does a very fast series of checks:
"is it time to do <thing 1> again?"
"Is it time to to <thing 2> again?"
"What about <thing 3>"
And repeats.
Then it doesn't freeze the rest of your sketch waiting for time to pass. (That is what delay() does. Everything stops until the delay time has passed, which is bad.)


text:
NodeMCU Modbus interfacing with Pressure Multi-Switch
I've been trying to interface between a NodeMCU and a Dotech DPX200 Pressure Multi-Switch over Modbus RS485 using a MAX485 Module for the past few weeks, going through nearly every Modbus post on this site  with no luck.
As my access to the multi-switch can be limited at times, I've also tried using several simulators like ModScan64, Simply Modbus Master/Slave, Modbus Poll etc. but could get none to work.
I'd like to know if the Modbus device's Slave ID has to be set on the device itself or the NodeMCU? Also to get the "Display of low pressure value" the address given in the manual is 40023. How would I write the NodeMCU code to read that value using either the ModbusRtu, ModbusMaster or any other appropriate library?

I've added the DPX200's Manual link with my NodeMCU script and wiring diagram, and would appreciate any help from you.

#include <ModbusMaster.h>
#define MAX485_TX_ENABLE  12

int myInts[6];
ModbusMaster node;

void preTransmission(){
  digitalWrite(MAX485_TX_ENABLE, 1);
}

void postTransmission(){
  digitalWrite(MAX485_TX_ENABLE, 0);
}

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600, SERIAL_8N1);
  pinMode(MAX485_TX_ENABLE, OUTPUT);
  digitalWrite(MAX485_TX_ENABLE, 0);
}

void loop(){
  uint16_t k = 0,Status;
  node.begin(1, Serial1); //Slave ID = 1?
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
  Serial.println(i);
  Status = node.readHoldingRegisters(0x0023, 5); //Since address is 40023 to 40027
  if ( (Status == node.ku8MBSuccess) ){
     Serial.print("\nIDK: ");
     //Serial.println(node.getResponseBuffer(0));
     for (k = 0; k <= 5; k++ ){
        Status = node.readHoldingRegisters(k, 1);
        Serial.println(node.getResponseBuffer(0));
        delay(0);
     }
  }
}

the slave id is set in slave. the id is in the documentation of the sensor. it is 1 (and can be set in register 40063)

@Juraj Thank you for the info on Slave ID. I'm sorry but could you please explain what you meant in the second comment?

@Juraj Thanks a ton. So is the solution to just change it to Serial? Sorry if it's a silly question but I don't have much experience with this.

Now you have node.begin(1, Serial1), but you can't use Serial1 for RS485 because Serial1 doesn't have RX pin
According to the picture you wired the adapter to RX/TX pin of Serial, but this pins are wired on board to USB for communication with the computer (upload and Serial Monitor). You can't use Serial for RS485 adapter while you are using it for debug prints.
You can use SoftwareSerial fo example on D1/D2 for RS485.
Or if you have an USB-to-TTL-Serial adapter then you can use Serial1 for debug prints and Serial for RS485


text:
LED blinking issue
i made a distance measuring circuit with different led for different distance ranges
#define trigPin 13
#define echoPin 12
#define BPin 7
#define piezoPin 9
#define RPin 4
#define GPin 8

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(RPin, OUTPUT);
  pinMode(GPin, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(1000);
  {
    if (distance <= 25 || distance <= 0) {
      digitalWrite(RPin, HIGH);
    }
    else {
      digitalWrite(RPin, LOW);
    }
  }

  {
    if (distance >= 25 && distance <= 50) {
      digitalWrite(GPin, HIGH);
    }
    else {
      digitalWrite(GPin, LOW);
    }

    {
      if (distance >= 50 && distance <= 75) {
        digitalWrite(GPin, HIGH);
      }
      else {
        digitalWrite(BPin, LOW);
      }

      {
        if (distance >= 75 && distance <= 100) {
          digitalWrite(BPin, HIGH);
        }
        else {
          digitalWrite(GPin, LOW);
          {
            {
              if (distance >= 100 && distance <= 200) {
                digitalWrite(piezoPin, HIGH);
              }
              else {
                digitalWrite(piezoPin, LOW);
              }
            }
          }
        }
      }
    }
  }
}

everything is working fine except Gpin it is blinking please  help me
i am also uploading link to download my .ino file
link; https://www.datafilehost.com/d/e19b35d5

First align your code (put { and } nicely under each other which belong together, also remove unneeded { and } (like around if statements). Also do not indent when it's not needed (e.g. the pin mode settings).

I formatted your code, and your logic is extremely convoluted, and I suspect also incorrect in several places. I counted at least 5 unnecessary brackets, and inconsistent if/else structure. Also if something is lower then 25 it's already lower then 0.

I guess it should be if(distance blabla) digitalWrite(pinX,HIGH); else digitalWrite(pinX,LOW); (you have different pins in if/else case). Also two leds will be on when distance==50, distance==75 or distance==100 which I would consider a mistake.

This is your code without unnecessary brackets:
#define trigPin 13
#define echoPin 12
#define BPin 7
#define piezoPin 9
#define RPin 4
#define GPin 8

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(RPin, OUTPUT);
  pinMode(GPin, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(1000);

  if (distance <= 25 || distance <= 0) {
    digitalWrite(RPin, HIGH);
  }
  else {
    digitalWrite(RPin, LOW);
  }

  if (distance >= 25 && distance <= 50) {
    digitalWrite(GPin, HIGH);
  }
  else {
    digitalWrite(GPin, LOW);
  }

  if (distance >= 50 && distance <= 75) {
    digitalWrite(GPin, HIGH);
  }
  else {
    digitalWrite(BPin, LOW);
  }

  if (distance >= 75 && distance <= 100) {
    digitalWrite(BPin, HIGH);
  }
  else {
    digitalWrite(GPin, LOW);
    if (distance >= 100 && distance <= 200) {
      digitalWrite(piezoPin, HIGH);
    }
    else {
      digitalWrite(piezoPin, LOW);
    }
  }
}

Using the ternary operator you can write some if statements easier:
#define trigPin 13
#define echoPin 12
#define BPin 7
#define piezoPin 9
#define RPin 4
#define GPin 8

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(RPin, OUTPUT);
  pinMode(GPin, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(1000);

  digitalWrite(RPin, (distance <= 25 || distance <= 0) ? HIGH : LOW);
  digitalWrite(GPin, (distance >= 25 && distance <= 50) ? HIGH : LOW);

  if (distance >= 50 && distance <= 75) {
    digitalWrite(GPin, HIGH);
  }
  else {
    digitalWrite(BPin, LOW);
  }

  if (distance >= 75 && distance <= 100) {
    digitalWrite(BPin, HIGH);
  }
  else {
    digitalWrite(GPin, LOW);
    digitalWrite(piezoPin, (distance >= 100 && distance <= 200) ? HIGH : LOW);
  }
}

Some remarks to think about that helps you solve your sketch (and is the reason why your GPin may blink):

The line part (distance <= 25 || distance <= 0) can be rewritten to (distance <= 25) since if a value is less/equal than 0, it automatically is less/equal than 25.
You set based one a condition a pin to HIGH or another pin to LOW, I would expect both pins to change, or the same pin. But I don't know your requirements.
The 'edge' values (e.g. 25, 50, 75) fall in multiple conditions, you probably want to exclude the end edge. It is a sort of guideline to include the start and exclude the end, e.g. if (distance >= 50) && (distance < 75).

In your case you probably are best of checking the distance like this:
if (distance < 0)
{
   ...
}
else if (distance < 25)
{
   // 0 <= distance < 25)
   ...
}
else if (distance < 50)
{
   // 25 <= distance < 50)
}
...

or do it the other way around:
digitalWrite(GPin, 'condition in which GPin should be on' ? HIGH : LOW);
digitalWrite(BPin, 'condition in which BPin should be on' ? HIGH : LOW);

e.g. when you want the GPin to be on when between 0 and 25:
digitalWrite(GPin, ((distance >=0) && (distance < 25) ? HIGH : LOW);

I'm afraid your conclusion of point 1. is not correct. The first line is OK. But if a value is less or equal than 25 it is not automatically less then 0. e.g. the value 25 is less or equal then 25 but greater than 0. But the other direction is correct. I know, I count peas, it's my hobby ;-).

@PeterPaulKiefer I think I'm correct. If the distance is smaller than 0 it is always smaller than 25, thus the sub expression distance < 0 is unnecessary, as the range (-inifinit,0) is within the range of (-infinit, 25). If the operator would be an &&, than you would be correct.

Yes the formula you derived is correct, but you had written "since if a value is less/equal than 25, it automatically is less/equal than 0." And that is not correct.

Sorry perhaps the word "conclusion" irritates you, but I'm not a native English speaker. Perhaps I've misused it.

@PeterPaulKiefer No need to sorry, I just completely missed your point, I was focused on the formula, not the text. And you were right, so I fixed the answer. You didn't  irritate me at all, I just misinterpreted your text (I'm also not a native speaker). Thanks for your improvement, and I adapted my answer accordingly.


text:
Getting maximum value from HX711 and use it in the code further
i am using HX711 module to get value from load cell.my projects is a tensile strength testing machine,which will increase the load gradually and break at its maximum capacity.therefore i need the maximum value at which the specimen breaks.and use that value in the code to calcuate the tensile strengh of the specimen using the formula(tensile strength=load/cross section area of specimen).
Please help me with this and if possible ,i will be very gratefull if anyone can help me with the code too.
Thank you

Please show us the code, that you already have. What is your problem with reaching the goal? Everytime, that the load increases, you measure with the load cell and save the result in a variable, but only, if it's greater, that the previous value. Sense the breaking of the specimen by checking for a large load decrease in your load cell. The saved value at this time is the absolute maximum, that was reached.

Thank you, i do not have any code for the project, i am new to arduino programming.i just know the basics.can you please help me with the code.?

Thank you, The code should take the maximinum value from the load cell at which the specimen broke and use that value to calculate the tensile strengh using the formula given above i.e (maximum load÷cross section area) where cross section area is calculated by formula-((pi÷4)*(r^2)) and 'r' is entered by user which is the radius of the specimen.

We won't write the code for you, since we are not a free coding service, but I will try to give you some hints, how you can do it.

Timing of measurements: The measurements themselves can be done with one of the HX711 libraries, that are available on the web, but you may want to time them to get more regular measurements. This can be done in a non-blocking coding style like in the BlinkWithoutDelay example, that comes with the Arduino IDE. It involves the millis() function to measure the time since the last measurement and act accordingly. This is explained many times troughout the web and on this site.
Saving the data and finding the maximum: This depends on what else you want to do with the data.

Saving all data for later processing: You might want to save all data (the load curve) for later use. In this case you have to define an array of appropriate length (the length depends on the duration and frequency of the measurement). Also define a position variable or pointer, that marks the current position in this array. Everytime when you do a measurement, you save the result to the array element at the saved position and increment the position variable after that. After the end of the measurement, you declare a value variable with the value of the first array element. Then you loop through all the following elements (for(int i=1;i<array_length;i++)). Inside the loop you calculate and save the maximum of 2 numbers: The value of the current array element and the saved variable. This can be done with saved_value = max(saved_value, array[i]);. When the loop is finished, you will have the maximum value in the saved_value variable.
No saving of data: You can also calculate a flying maximum without saving all data. Declare a variable (max_value), that will hold the maximum value, and set it to zero. Then, everytime when you do a measurement, you execute max_value = max(current_value, max_value); which calculates the maximum of the two numbers (current measurement and the previously calculated maximum). At the end of the measurement you will have the absolute maximum in the max_value variable.

Sensing the end of measurement: You need to sense the end of the measurement (when the specimen breaks) (though this can be done manually if you like). For this I would suggest to calculate the speed in which the load changes. During the measurement the load will increase slowly. In the moment of breaking the load will decrease very fast. The speed between two load measurments is calculated by (value(x) - value(x-1))/measurement_interval. You can define a threshold of negative speed, so that every speed below it (faster negative decrease of load) will be sensed as breaking of specimen. You can check this on every measurement with a simple if statement, or you can calculate the speed over more than 2 consecutive measurements. That depends on the actual speed of load change and the frequency of load measurements.
Calculating the tensile strength: This is just writing your formula into the code using the variable names, that you used in the previous code. Be sure to use the correct variable type for your needs. Most likely you would want to use float.
Getting input from user: This depends largely on your planned means of interaction with the user. Is the Arduino connected to a PC and you use a serial terminal program? Then you can use this for user input (You might want to look at the SerialEvent example of the Arduino IDE, which shows how to work with messages and delimiter characters). Do you want to add a keypad and a LCD display? There are library available for these too, so it should not be very difficult to learn how to use then to get user input.

Thank you so much for the help.


text:
Arduino Uno Wifi R2 Mesh Network
I currently have a project that uses a few Xbee S1 modules to report temperature measurements to a computer. I'm thinking about reworking the project to use the newer Arduino Uno WiFi R2 boards.
Is there an existing library that will allow me to create a mesh network for a number of Wifi R2's (about 20+)? I know there's a Mesh Library for the ESP8266 I'd be curious if I could either use this library or if one exits for the native board

why do you want to use Uno WiFi for this? two MCU? IMU? crypto chip? not compatible sensor libraries?

I was thinking about using the Uno WiFi for the simplicity of having most functionality on one board. I also want some level of security (like that provided by the crypto chip)

ok. don't buy 20. try one first

Fair point, I'll get 2-3 to verify 1st. I want to make sure the solution is able to do 20+ish

first test if it works with your sensors. it is ATMega4809. it has a different  architecture then the classic Uno 328p

It will, the sensors are run through an I2C ADC.

the crypto-chip and IMU are already on I2C. the Nina esp32 is wired to I2C too (not used yet). and there is no mesh support yet in WiFiNina firmware and library. why not use esp8266?


text:
Writing Data through Pin at certain frequency
I have an Arduino UNO which is connected to an KLZ25 board, the Arduino sends an 1MHz Clock at Pin 9 and now I should write the PDM-Data with 1 Mhz at pin 8. But i don't know how to write with such a speed, because if I write in the Loop:
loop{
digitalWrite(1);
digitalWrite(0);
}

I get only a frequency of 36Khz, I know it depends on the count of commands in the loop, but I don't know how to write with a certain frequency in my case 1Mhz.
I get the PDM-Data (pulse density modulation) in form of 1 and 0 from a python script on a Host-PC and now I want to stream the Data with 1MHz to an other developer board which makes further calculation with the PDM-Data. I store the PDM-Data in queues because I have not enough memory to store the whole Data.
Does anybody know how to write PDM-Data with a 1MHz frequency to an output pin ?

What does the acronym PDM mean?  It would help to state it in your question.

Use one of the timers on the UNO. Those are the ones that are used for PWM. Set the prescaler to /8. Set the mode to fast-pwm. Set the output pin to no-inverting mode. Set OCxA/OCxB to 2 (since the timer runs at 2Mhz). Then change the TOP value based on the PDM value you want to send.

PDM means pulse density modulation, basically I write 1 or 0 with 1Mhz frequency. @Gerben What do you mean by TOP value ? Does the change of the timer changes also the loop speed because I don't get how to write in 1Mhz if the loop is slower.

DigitalWrite itself is super slow. It takes a lot of cycles. loop itself also takes a few cycle to get called. You could use direct port manipulation instead, which is a lot faster. But to run at 1Mhz, you only have 16 cycles to toggle the pin and run the loop, leaving you with nearly no time left to do anything else.  Also other interrupts could occur and slow your loop at "random" intervals, giving you a unstable 1Mhz signal. That's why I'm suggesting using timers, as they run in parallel.

The timer is for example used to PWM an LED. This timer runs parallel to your code. The timer has a counter that it increments every clock cycle. You can select a TOP value, so that, when it reaches this value, it reset the counter to zero. It also has a compare registers. You can instruct the timer that, once the counter reaches the value in the compare register it should set one of the output pins LOW. You can also instruct it to set the output pin HIGH when it's set back to zero. So by combining this the output will be HIGH for 1µs, followed by a number of µs LOW, depending on value of TOP.

You might also be able to emulate the desired behaviour with one of the atmegas interfaces (e.g. SPI master). The essence of what Gerben mentioned is that you should use the available hardware because as you already found out handling this stuff in loop() won't work at 1 MHz.

16 CPU cycles is a very short time. You won't be able to do much other than the delta-sigma algorithm for generating the PDM output. Some time ago I wrote a program that does almost what you are asking for. It reads data in a “shift register” fashion and outputs it as PDM at 615 kHz with a CPU running at 8 MHz. That's 13 CPU cycles per PDM cycle. It's intended to run on an ATtiny13A and should be easy to adapt to an Uno. It's based on a carefully timed assembly loop, with no interrupts. Tell me if you are interested in me publishing it.

Ah ok I understand, thanks for the answers! @EdgarBonet that would be nice if you would publish it. I don't know if the SPI solution would work with the frdm-klz25 board but I will try to use the timer interrupt solution and if this don't fit I give it a try, thanks! And I don't must do the sigma delta modulation, I have done it on python on the Host-PC and I use the Arduino to send the Data to a KLZ25, basically the Arduino and the Host-PC together simulates a Microphone and on the KLZ25 I will do an MFCC calcuation after I streamed the PDM-Data from the PC to the Arduino.

If I understand correctly, you want to output a synchronous serial bit
stream at 1 MHz. Something like this:
        ___     ___     ___
clk  __/   \___/   \___/   \___⋅⋅⋅
     ______ _______ _______ ___
dat  __D0__X___D1__X___D2__X___⋅⋅⋅

where the data bits come from the PC.
If you want this to be a continuous bit stream, it will not be easy to
generate on an Arduino Uno.
Receiving the data
Since the data comes from the PC, it comes presumably through the serial
link. You have to account for the fact that this link adds a start bit
and a stop bit to every byte. Thus, you have 10 bits on the wire
for every 8 bits of actual data. Since you have to sustain
1 Mb/s average of actual data, this means that you must configure
the serial port for at least 1.25 Mb/s. However, the only baud rate
higher that 1 Mb/s supported by the Arduino Uno is 2 Mb/s.
Does your PC support this baud rate? Is the communication reliable at
this speed?
If the speed is too high, I would suggest you try to have the PC send
the data as PCM at a lower speed, and have the Arduino handle the
PCM → PDM conversion.
Transmitting the data
This data format is very similar to an SPI transmission. Then, the SPI
hardware port seems like the easiest way to generate it. However, the
SPI transmitter on the Uno is not double-buffered. This means that you
have to wait for the current byte transmission to be finished before
providing the next byte to the SPI hardware. This in turn means that you
will inevitably have small delays between consecutive bytes, and one out
of every 8 clock cycles will be stretched beyond the expected
1 µs. If this unsteadiness is acceptable for your application, then
do use the SPI transmitter. If not, you will have to find another
solution.
The serial port on the Uno has a special mode of operation where it
behaves like a master SPI port. Unlike the actual SPI port, this port is
double-buffered, which makes it possible to send a continuous bit stream
with a steady clock. The problem is, you cannot use this mode for
transmission and at the same time use the serial port receiver in its
regular asynchronous mode. Thus you will not be able to receive the data
from the PC when using this mode. If you can manage to route the
PC → Arduino communication through SPI, this mode of operation
of the serial port may be a good choice.
If none of the options above works for you I suggest, as last resort, to
generate the bitstream entirely by software. The timings are tight, as
each level of the clock has to be held for only 8 CPU cycles. But
it is likely doable in hand-written assembly, provided that interrupts
are disabled. Here is roughly how I may try to do that:
    in output, _SFR_IO_ADDR(PORT_OUT)   ; save a copy of the port reg.

loop:
    lds data, _SFR_MEM_ADDR(UDR0)       ; load data from USART

    ; output bit 0
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 0                         ; save data[0]
    bld output, 0                       ; load it into output[0]
    ; no delay needed here
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6                             ; assumed to be a macro
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; output bit 1
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 1                         ; save data[1]
    bld output, 0                       ; load it into output[0]
    delay 4
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; etc...

    rjmp loop

The code above assumes the UART is synchronized with the output stream,
which will likely not be the case in reality. Your real application may
then be more complex, and you will have to make that extra complexity
fit within the delay slots above.
Note that if you handle the PCM → PDM conversion on the
Arduino the resulting code may end up being simpler, as you will be able
to read the UART at every loop iteration without worrying about
synchronization. I have written a program that does something very
similar a while ago, and I just pushed it to GitHub for you to take a
look: avr-dac: Turn an AVR into a 1-bit D/A converter. Note
that this program is meant to be usable on AVRs without a hardware UART.
It expects the PCM data to be fed in the fashion of a shift register.
Using the UART would make the program simpler.


text:
RTC 1307 when connected to a relay via Arduino Nano
I was posting a question but to be completely sure i did some more tweaking in the code and solved at least functionally my problem.
I decided to post it anyway to have suggestions for a better solution and / or help whoever has the same problem.
The project is a flowers watering application.
I set up an RTC connected with Arduino Nano using LEDs to simulate the operations, it works really well, no mistakes when RTC.readTime requests.
Once satisfied I replaced the LED with a relay to be connected to the pump, and then the problem appeared:
Randomly the reading is not correct, something like (YYYY/MM/DD H:M:S) represented as 165/0/165 0:165:0.
The combinations of 165 and 0s are completely random but only 165 and 0s are present.
My solution was to check after each reading if there was any 165s into the returned data, and if yes, read the time again. This was the medicine.
This mistake appears only and always when i replace the LED with a relay, with or without connected charge.
Circuitry is very simple as well as is the code.
  RTC.readTime();
  if (RTC.h == 165 ||
      RTC.m == 165 ||
      RTC.s == 165 ||
      RTC.dd == 165 ||
      RTC.mm == 165 ||
      RTC.yyyy == 165 ) {
        RTC.readTime();
        Serial.print("Mistake found in step N. ");
        Serial.println(countCycles);
  }

  countCycles ++;

From the printout I can confirm that the mistake is absolutely random but never immediately subsequent to another mistake.
Any clues?
Thank you for any comments

Did you use a relay or a all-in-one relay module/breakout? A relay itself requires some additional components to connect it to an Arduino. They also require quite a bit of current, which can cause a short voltage drop, which some components don't like. Turning a relay off can cause some back EMF, which some components don't like. Adding a large capacitor might be enough to fix these issues.

Hi Gerben, thank you for your answer.

Answer to your question first: I used a Relay module from Elegoo that as said does not need any other components to be connected with Arduino, nevertheless i believe that a condenser will not do any harm. Which capacity do you think suitable? and where to fit it? my electronic skill is quite low 'cause i am more a SW guy beginning to play with Arduino for fun while retired. I dont know where to put a picture here, otherwise i may have posted a picture of the module. Ciao

Just forgot to say that i powered the circuit with a proper source with load of current available.

I'd try a 10-100 uF (electrolytic) capacitor near the module. It might be that your power-supply can't handle the very sudden increase in current fast enough. I too came from a SW background. When things start to act weird, it's mostly a power issue, I've learned.

Do you mean between + and - on the power supply?  An update on the mistakes is that they appear in sequence as well so i had to set a do - while loop.

Yeah, sorry. I should have mentioned that. Between + and - (Vcc and GND).


text:
Python Arduino Serial Communication Speed
Background : Im controlling serial manipulator using Arduino Uno with Servo Shield. Servo work at 20 ms, so i would like to send command atleast every 2.5ms. Command sent from PC.
I send 8 bytes of data from my python code on PC at 250k Baudrate. If i send it every 25 ms, my robot could respond and everything works fine. But if i send every 2.5 ms, my system wont work.
Here my arduino code,
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
int x,temp;

int sudutT0(long int p)
{
  int u = 3600+((405*p)/180);
  return u;
}

void setup() {
  Serial.begin(250000);
  Serial.println("Joint 2 Test!");
  pwm.begin();
  pwm.setPWMFreq(50);

  Wire.setClock(1000);
  for (uint8_t pin=0; pin<16; pin++)
  {
  pwm.setPWM(pin, sudutT0(90),4095);
  }
  pwm.setPWM(3, sudutT0(150), 4095);
}

void loop() {
    if(Serial.available() == 8){
      if(Serial.read() == 0xF5)
      {
        //Joint 1
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(0,x,4095);
      // Joint 2 Servo
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(1,x,4095);
      x = sudutT0(180-temp); //810 - theta
      pwm.setPWM(2,x,4095);
      //Joint 3 - 6, Gripper
      for(uint8_t u = 3; u<8; u++)
      {
        temp = Serial.read();
        x = sudutT0(temp);
        pwm.setPWM(u,x,4095);
      }
      //delay(100);
      }
    }
}

Is there anything that i miss, that make my system could not respond if i send signal every 2.5 ms?

Is there a reason you need to update it 400 times a second? All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data.  I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms.

@ChadG Actually i wanna apply control theory about multirate sampling time, and i just realize i made a mistake.. i didnt need to make it 2.5ms now. And thank you for explaining why my robot couldn't respond.. could u put ur answer at answer section, because u explain why my robot not responding. Thx

All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data. I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms


text:
I2C between two arduinos
I have 4 gyro sensors that communicate to arduino uno using I2C and then arduino uno sends the data to arduino mega.
I was wondering if I could use i2c for this purpose or if I should look for other methods.
gyro sensor used in the project:
https://www.pololu.com/product/2129/resources

Sure, the Mega can be an I2C slave, too. Is there a reason, why you are using a Mega and an Uno, instead of just the Mega?

ok so the arduino uno can be both a slave and a master. thanks
yes, I will be adding a bunch of analog sensors to the project later and I don't have enough unused I/O pins on the Mega to connect them to, so I'm using 2 boards.

Both master and slave is not adviserable. The I2C protocol has multi master support,  but the Wire library does not implement this. If the gyro sensors use I2C and you already considered to use I2C between the Uno and Mega, why don't you connect the gyro sensors to the Mega? They will only use the 2 I2C pins, that you already planned in, since they are all I2C sensors.

thats better thank you!


text:
Is there an Arduino motor shield library?
I have an old motor shield but can see the revision 3 is still being sold: https://store.arduino.cc/arduino-motor-shield-rev3
When I follow the link for "Getting Started section" the page lists a lot of shields but not the motor shield.  I must be missing something really obviously but I can't find a library for the motor board.
I'm trying to drive 2 DC motors.

Have you googled this, before asking here? I googled "Arduino motor shield rev3 library" and directly found this library on github. Have you tried it or any other library?

Yes for the last 90 minutes: https://www.ecosia.org/search?q=arduino+motor+shield+library&addon=opensearch https://www.ecosia.org/search?q=arduino+motor+shield+library+-adafruit https://www.google.com/search?q=site%3Ahttps%3A%2F%2Fwww.arduino.cc%2Fen%2FGuide%2F+motor+shield&addon=opensearch https://www.google.com/search?q=arduino+motor+shield+library+example Granted that for me: https://www.google.com/search?q=arduino+motor+shield+library shows your link as the fifth result down for but then it's followed by Adafruit Motor Shield again... their SEO is too good.

Ok so using Ecosia is part of the "problem", along with Adafruit's SEO... but I just realised Ecosia is powered by bing.com  and the extreme irony is that this question is already indexed as result number 7 but the library you helpfully provided is not! https://www.bing.com/search?q=arduino+motor+shield+library  LOL

Often it is helpful to add the term github to your search, since almost every Arduino library is hosted there.

Thanks @chrisl something seriously weird is going on with all my filter bubbles because your result now isn't shown in my google search after being shown in it minutes before... * so confused *.  Adding github just shows the Adafruit barrage, at least on page 1.

From Chrisl's comment: https://github.com/gallingern/arduino-motor-shield-r3
You don't really need a library though as the code is simple enough:
void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

}

void loop(){

  //forward @ full speed
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A
}

From here.


text:
Is there something I can add to my ESP8266 script to track how much data it uses on WiFi?
I want to set it up on a mobile hotspot but I'd like to get an idea of how much data my sketch uses first.

keep a running tally of the length of data being sent ... you could keep track of received data also

But I don't know the size of the data I am sending, it's just two JSON objects.


text:
Trouble with i2c on ESP8266
I have used with partial success I2C with the ESP8266.  When it works, it works well, with many devices on the bus.  I've examined the signals on a 'scope to assure Vlo, Vhi, Tr, and Tf.
However, often it works not at all.  No I2C devices (even if there is only one connected) are detected.  This condition is determined by some unknown factor, and it stays in this condition for some time (days?) before it starts working again.  Power cycle, reset-by-button, and reset-by-reflashing do not restore operation until it works again.
This has occurred with at least three ESP8266 modules from two different manufacturers with different pinouts.  It affects all connected I2C devices.  They are all slaves to the ESP8266.
What should I try next?

next time it fails, load and run a minimal sketch that uses I2C

The signals had looked good, but I did not examine them closely enough.  When I removed extra pullup resistors I had added on SCL and SDA, I2C worked.

It's OK to accept your own answer as the solution to the problem.


text:
How can I control a slave ESP8266 from a local server and also from another ESP8266?
I have a power strip with a ESP8266 which is supposed to turn it on upon command from a OpenHAB server, or to stay on for a predefined time upon command from another ESP8266 (serverless).
The reason is that OpenHAB is used to directly control the strip, while the other master ESP8266 is powered on and off intermittently and periodically sends "refresh" commands to the slave, that will turn off when no more messages are received.
How should I handle the control of the ESP8266? I have never worked with master/slave and I'm confused by the number of available options. For example, MQTT seems a good choice when the server sends the control command, but it requires a software listening and relaying MQTT messages, therefore is not suitable as only control technique because the communication between ESP8266 must not rely on any further network device.
I also thought about simply controlling the slave ESP8266 via webpage and POST/GET commands, since OpenHAB can be set up to use this method as well and that would work also as direct control between ESP8266.
What are my options, their complexity and pros/cons?

let the esp8266 be a client for OpenHAB and start server for commands from the other esp8266

@Juraj do you mean using MQTT? I don't understand to which protocol you refer.

I don't know OpenHAB. Do what it requires. And for the other esp8266 start a server


text:
How to create a Arduino socket server to receive messages
From linux I can send a socket message using netcat
echo "Hello" | nc 88.109.110.161 100

But I don't know how to setup the socket server for listening incoming messages using the ethernet shield.
What I have so far is one from a lot of examples I tried but still not showing anything
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetServer server(1000);

void setup() {
  Ethernet.begin(mac);
  Serial.begin(9600);
// Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
 EthernetClient client = server.available();
 if (client) {
   Serial.println("Client");
   // an http request ends with a blank line
   boolean currentLineIsBlank = true;
   while (client.connected()) {
     while(client.available()) {
       char c = client.read();
       // if you've gotten to the end of the line (received a newline
       // character) and the line is blank, the http request has ended,
       // so you can send a reply
       if (c == '\n' && currentLineIsBlank) {

// Here is where the POST data is.
         while(client.available())
         {
            Serial.write(client.read());
            //Serial.println(c);
         }
         Serial.println();

         Serial.println("Sending response");
         // send a standard http response header
         //client.println("HTTP/1.0 200 OK");
         //client.println("Content-Type: text/html");
         //client.println();
         client.println("OK");
         client.stop();
       }
       else if (c == '\n') {
         // you're starting a new line
         currentLineIsBlank = true;
       }
       else if (c != '\r') {
         // you've gotten a character on the current line
         currentLineIsBlank = false;
       }
     }
   }
   Serial.println("Disconnected");
 }
}

have you confirmed that your ethernet shield is functional?

see the ChatServer example

Where is your Ethernet.begin? Surely you still need one of those. have a look at the setup() in the docs here: EthernetServer Example

the shield is fully functional, I'm able to receive http post requests, that's how I figure it out, but I still needing the socket server, just to receive raw messaages

I updated the code, that's how actually receives http requests

What do you mean by "needing the socket server" and "to get the raw request"?
I would have thought that your are already doing that. After all, your loop is reading the incoming socket data character by character and assembling it into a string. You are dealing with the low level http protocol (in the example above) by checking the new lines. How much lower do you "need" to go?

Maybe a typo but you send your message to Port 100 and the Arduino is listening to Port 1000 ;)

I am learning to use the arduino library about sockets and I spent an hour detecting why your example was not working for me, I ended up noticing that you have one line wrong
if (c = '\n' && currentLineIsBlank) {

should be:
{ if (c != '\n' && !currentLineIsBlank) {

And you still have an error you are missing a return character because you are not printing it in the second loop.
Anyway thanks for your contributions.

there is == and that is right