text:
ESP8266-01 Resetting when DC motor runs
DC motor: 3-6v
Servo sg90: 3-7.2v
Esp 8266 01: 3.3v

I have 2 Arduino Uno both has their own ac-dc power adapter.
Lets say, 1st Arduino is Ard1 and 2nd is Ard2.
The Ard1 communicates to a web server (BLYNK) with Esp 01.
Using I2C, Ard1 sends command to Ard2 to power/move the DC motor/Servo.
So far, it has no problem operating with Servo. But,
Whenever the Ard1 commands the Ard2 to power the DC motor.
Right when the DC motor runs(using digitalWrite(motor,HIGH)) the Esp 01 resets.

Tried using analogWrite(motor, 102) though it won't reset instantly, prolong usage randomly resets it anytime.
I also tried to test operating Servo and DC motor simultaneously in Ard2 using Serial commands, without I2C/Esp01. There was no problem at all, both works flawlessly.

Below is the diagram of the wiring.

That‘s an electronic issue. You should post a circuit diagram or move this question to electronics SE

You should check the current rating for motor. It may be the case that your supply is not able to provide it.

How is the ESP-01 powered/?

I've just included a diagram for further understanding. Please pardon me, I have zero knowledge on electronics/electrical.

Despite the fact that you don‘t have pull-ups connected to the I2C lines your circuit looks fine. How do you know that the esp resets, what did you observe?

Using blynk app, as simple as on/off for any of the motor. Once I 'on' the DC motor and it runs, the connection between the esp and server will be cut. Which also means I can't 'off' the DC motor from the Blynk app unless the connection between the server and esp resumes/restarted. I suppose the problem would be the wiring of I2C/GND(ard1 - ard2), as It's the only way these two is linked.

The connection between the Arduinos probably has nothing to do with the esp resetting. From the information you provided I‘m not convinced that the esp really performs a reset, maybe the esp simply doesn’t send anything. Have you added the pull-ups?

Try removing the second arduino and uploading a program to the one connected to the motor that turns the motor on and off, to see if you still have the problem. Try powering the motor from a separate 5 v supply so it is only connected to the arduino by pin 3

Can you clear one thing that you are giving power to dc motor from 5v pin given on Arduino board or from your ac to dc power supply. If you are giving power to the motor from 5v pin of Arduino Uno then there is a high possibility that the motor is not getting sufficient current because 5v supply on Arduino comes from onboard lm1117 5v voltage regulator and cheap clon Arduino has a cheap regulator with less than 1amp capacity.

It was indeed. I then resorted to a 9v battery supply for dc however problem still exist but not that severe, it still cuts the connection. Finally, my latest solution was attaching a 10ko resistor between esp's ch_d to 3.3v of arduino and 1k between gnd and esp's rx and another 1k between esp's rx to arduino's. So far everything went well.

@Kolokoy what are These resistors supposed to do?! Note that a 9V battery is also a bad choose as I can‘t provide much current as well. You better use a proper PSU or e.g a Li-Ion battery

Someone I knew said rx/tx might uses a TTL logic level of 5v instead of 3.3v which the esp 01 can only take. I also found a tutorial on YouTube on the wiring of esp01 to arduino and followed it. The battery was just to test if problem would still exist when the dc motor has different power supply, I will not use it in the final outcome.


text:
Determining which raw IR code to use for AC
I'm new on this so go easy on me.
I'm trying to make an IR blaster to control my TV and ACs. I realized that when I capture the IR code, power button/temp up and down/mode send raw codes that are almost similar to each other.
I've searched the net(maybe missed some answers) and came through this. The raw IR code provided on the blog did turned on my AC but I wasn't able to turn it off. So I think that the code isn't the power button. That's because I remember leaving the AC off at 23°C and when I send that code, my AC started at 20°C.
So, how do I know which code to use for off, temp up etc? The codes I captured seems not to work when I send the codes to the AC. Nothing happened. No beep or anything. I'm using a GREE AC by the way.
Here's an example of the raw code that turned on my AC:
uint16_t irACon1[139] = {9050, 4500, 800, 1600, 750, 550, 700, 550, 700, 1600, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 1600, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 550, 700, 1600, 750, 550, 700, 550, 700, 1600, 750, 550, 700, 19950, 750, 500, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 550, 700, 550, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1550, 800, 550, 750, 500, 700, 1600, 750};

And few other codes that I had captured:
Raw: (139) 9068, -4404, 708, -1580, 712, -488, 712, -484, 712, -1580, 712, -1580, 708, -1580, 712, -488, 708, -488, 708, -1584, 708, -1584, 708, -1580, 708, -492, 708, -488, 704, -496, 704, -492, 708, -492, 708, -492, 704, -492, 708, -492, 708, -488, 712, -488, 712, -1580, 708, -1580, 712, -488, 712, -484, 712, -488, 712, -488, 712, -484, 712, -1580, 712, -484, 712, -1580, 712, -484, 716, -484, 712, -1580, 712, -484, 712, -19848, 684, -512, 704, -496, 708, -492, 708, -488, 708, -492, 708, -488, 712, -488, 712, -488, 708, -488, 712, -488, 712, -484, 712, -488, 712, -488, 708, -1580, 712, -488, 712, -484, 712, -488, 708, -488, 712, -488, 712, -488, 708, -488, 712, -488, 708, -488, 712, -488, 712, -488, 708, -488, 712, -488, 708, -492, 708, -488, 708, -492, 708, -1584, 704, -1584, 708,

Raw: (139) 8988, -4540, 556, -1736, 564, -688, 520, -676, 524, -652, 548, -1688, 600, -1688, 604, -648, 548, -652, 548, -1688, 604, -1684, 604, -1688, 604, -648, 548, -652, 548, -648, 548, -652, 548, -652, 548, -648, 548, -652, 548, -652, 548, -648, 548, -676, 524, -1688, 600, -1688, 604, -676, 520, -676, 524, -676, 524, -672, 524, -676, 524, -1712, 576, -680, 520, -1688, 604, -756, 440, -788, 412, -1688, 600, -816, 384, -20092, 468, -840, 348, -848, 352, -848, 352, -820, 384, -812, 388, -788, 412, -784, 412, -784, 416, -760, 440, -760, 436, -760, 440, -756, 444, -756, 440, -1824, 468, -780, 416, -760, 440, -756, 444, -728, 468, -732, 468, -728, 472, -700, 496, -704, 496, -700, 496, -676, 524, -676, 520, -652, 548, -648, 552, -624, 572, -624, 576, -620, 580, -1740, 548, -620, 580,

PS: Sorry for my bad English. And I somehow feel that the title isn't specific so let me know if there's a better title I should put.
UDPATE: Now the off and temp up is working but the temp is somewhat like an on button. It instantly put my AC on 23°C and won't increase when pressed multiple time. I understand that AC's remote fires the whole setup string when a button is pressed so which means different temps has different codes?

It appears from the data you've posted, the remote is holding the presets for what the A/C unit needs to be doing when after every button is pressed.  This will keep the remote with LCD disply? in Sync with the A/C master.
Ie.  The remote is sending an entire setup string EVERY time ANY button is pressed.
Can you post a capture of an ON and OFF Raw's only?  Do not press any other buttons after pressing ON, or before pressing OFF.

I see. But surely there's a way to know which raw code control what, isn't it? And here's the on and off raw code: https://pastebin.com/sKVWecLh

You are on the right track, but I think you need an expert for a better answer.

source: Stack Exchange

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

sort: votes


text:
Char Array Buffers String UINT8
So, I have an ATTiny85 sending data, awesome.
I would like to have it send a message that consists of a few concatenated parts.
I have been reading about strings, buffers, chars, toCharArray and more for about 6 hours now and am completely puzzled by this.
Below, the variable deze will no transmit, but msg will.
So I tried to do something like char *deze = "hello" + "world"; but that also fails.
What would be the best way to construct a piece of data that will be send by my 433MHz transmitter. I need to combine INT, String and float before sending it as uint8_t (bytes?).
#include <RH_ASK.h>

#define R_PIN PB4
#define T_PIN PB1
#define L_PIN PB3

RH_ASK driver(2000, R_PIN, T_PIN);

void setup()
{
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
}

void loop()
{
  char deze[5];
  char *msg = "gewonechar";

  String thijs = "thijs";
  thijs.toCharArray(deze, sizeof(deze)-1);

  driver.send((uint8_t *)deze, strlen(msg));
  driver.waitPacketSent();
  delay(200);
}

[edit]
This is the working code on the receiver side.
struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    server.handleClient();
    yield;
}

And the transmitter
#include <RH_ASK.h>

#define BAUD 2000
#define RX 11
#define TX 12

RH_ASK driver(BAUD, RX, TX);

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void setup() {
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    struct data myData;

    myData.id = 1001;
    myData.pin = 4;
    myData.value1 = analogRead(4);
    myData.value2 = analogRead(5);

    driver.send((uint8_t *)&myData, sizeof(myData));
    driver.waitPacketSent();
    delay(2000);
}

Library used: http://www.airspayce.com/mikem/arduino/RadioHead/

First off you never want to use String - especially on a chip with a mere 512 bytes of SRAM.
You should really be learning about struct for sending of data in the most efficient way.  A struct is a complex data type that combines multiple bits of data into one single variable - a bit like a record in a database.
You should avoid sending text as it is generally wasteful. The odd character, yes, but not whole strings of text.
For instance, you might want to send temperature, humidity and pressure:
struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
};

void sendData() {
    struct data myPacket;

    myPacket.temperature = 23;
    myPacket.humidity = 72;
    myPacket.pressure = 1016;

    driver.send((uint8_t *)&myPacket, sizeof(myPacket));
    driver.waitPacketSent();
}

With a struct, if you want to send text, you need to allocate enough space in the struct for your text. For instance, enough room for 9 characters plus NULL:
struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
    char weather[10];
};

Then, to get data into it, you (for example):
strcpy_P(myData.weather, (PGM_P)F("fog"));

is myPacket an 'instance' of the data 'class' here?

An "instance" of the data "struct", yes.

and how would I handle this at the receiver, what I now have is (char*)buf)

The same way. Create a struct exactly the same, then an instance of it, and use the pointer to that instance.

So I am receiving: driver.recv(buf, &buflen) and I created the struct, and an instance of it. But can I address the buf as a struct? It's not clear how the receiver understand the type so I can save the buff.temperature in the mypacket.temperature

driver.recv((uint8_t *)&buf, &buflen); where buf is struct data buf;

Let us continue this discussion in chat.

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


text:
Programming addressable LED
I have TM1812 addressable LED strip (1meter long 96 LED). I am looking a way to program it and i found this http://www.deskontrol.net/blog/arduino-based-artnet-node-for-led-pixels/
and its mentioned in article that it doens't work with current version of Arduino IDE.
Is there some other lib/api available to program it or another method?
UPDATE
As mentioned by @dlu FastLED support wide variety of LEDs. I contacted developers of FastLED on google + and they have updated there documentation for support of TM1812 its similar to TM1809

There is a very nice library called FastLED, it is also on GitHub as FastLED/FastLED. It is quite flexible and supports a huge range of addressable LEDs. I'm currently using it with 1.6.6.
The code that you linked to was developed with an older version of the Arduino IDE, so you might want to see if you can find an older version and try building with that.

I checked there reference sheet. its not mentioned anywhere they support TM1812. https://github.com/FastLED/FastLED/wiki/Chipset-reference

Ack, I'm sorry I was writing from memory and TM1812 is close to the WS2812 that the NeoPixel uses. I'll fix it…

Can i use WS812 library to program TM1812 or any other libs?

I need to go look at them. Do you have a data sheet you could link to? Looking at the GitHub page (https://github.com/FastLED/FastLED/wiki/Overview) I see that they are planning to support the TM1812, but don't have support yet. It might be worth contacting the authors and asking about the status of TM1812 support. Also since they support similar chips (by number) it would be worth comparing the data sheets to see how hard it would be support the newer chips.

How can i program them without using any library.

All TM chip Family is supported by Fastled Libs if you use a TM1811 just put TM1809.
It should work, I have tried and it succeeded.

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


text:
Arduino and WS2812 RGB LED Strip "freezing"
I have been working on a project as a gift for my girlfriend for Christmas which involves some a bunch of standard "white" LEDs controlled by shift registers and darlington arrays, and also some RGB LED strips (WS2812B strip, 29 LEDs on strip). Everything is going fine with the white LEDs, but not so much with the RGB ones.
If I leave the RGB leds running for a while all of the LEDs on the strip turn red, except for the first one, which continues to change color. I am not sure how long "a while" is because in "short term" testing, approximately running continuously for an hour, it works fine and all of the LEDs change appropriately, but if I leave it running overnight I wake up with the issue of all red and one single RGB "working". I then have to reset to get it working again. These RGB LEDSs need to be run for long periods (24 hours) of time without "freezing". The rest of the program (with the normal LEDs) continues to work fine despite the RGB ones not.
Let me explain how I am controlling them. V_rgb is 5V (5V - 8A power supply), which it is also grounded to. Then the data line, C, is connected to an Arduino Uno, on pin 12, which is a PWM pin.
In software, I am using a Adafruit Neopixel Library to control the RGB LEDs and write their respective colors, based off the examples given in their git repo and the tutorial here.
I have pasted my code below in case that may help, but honestly I am not sure if it is software or hardware related. (unrelated code has been removed)
#include <Adafruit_NeoPixel.h>
#define rgbPin 11
#define numRGBleds 29

Adafruit_NeoPixel strip = Adafruit_NeoPixel(numRGBleds, rgbPin, NEO_GRB + NEO_KHZ800);
int colorStep = 0;
int rgbIndex = 0;

void shiftColor() {
  int i = 0;
  for (i = 0; i < numRGBleds; i++) {
    int idx = (rgbIndex + i) % numRGBleds;
    int colorVal = round(i * colorStep);
    strip.setPixelColor(idx, Wheel(colorVal & 255));
  }
  strip.show();
  rgbIndex++;
}

uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  } if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

void setup()
{
  strip.begin();
  strip.show();
  rgbIndex = 0;
  colorStep = 255 / (numRGBleds - 1);
}

void loop()
{
  shiftColor();
  delay(1000); // Redo every second
}

My thoughts of what it could be are the following, let me know if any make any sense or are known issues:

Having issues with micros() value rollover
Overheating
Noisy power supply
Defective LED strip
black magic?

Thanks in advance for any help.
UPDATE
My current solution to the problem is to just reset the board using the watchdog functionality. It reboots in a few milliseconds and sometimes flashes in the process, but I would like to figure out the real problem.
UPDATE #2
So with the reset solution, I left it running overnight and it did not freeze which leads me to think it is definitely a software, not hardware, issue. I have changed some of the wiring and coding to make sure the watchdog reset is not noticeable. It resets every half hour or so. This will make sure all of the memory is cleaned, except stuff I store in the EEPROM (which I do use to make the reset less noticeable). This reset delays processing by a few milliseconds, but time is not critical, so it is not a big deal.
I still however, would like to know a more elegant way of doing this. The software reset is a bit "hacky"

Do the Arduino and LED strip share a common ground? You'd expect to connect more than just the signal line to the Arduino.

@TomvanderZanden They do. Everything is connected to the same ground line through the power supply.

Is everything connected to the same power supply? Chances are the power supply is galvanically isolated so nothing is connected to anything through it.

@TomvanderZanden yes, all is wired through one 5V - 8A power supply. The arduino is powered through the 5V pin, which is wired in parallel to LED strip. Note that a reset does fix the problem, without disconnecting power.This is my power supply

Try changing delay(1000) to delay(1). That way the problem might pop up a lot faster. Also, try changing rgbIndex++; to rgbIndex=(rgbIndex+1)%numRGBleds;. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.

@Gerben That is actually a fantastic point, I was not considering the rollover of rgbIndex. and since it is an int, it will flip to a negative on rollover, which is an invalid address on the LED strip. I was also under the impression until now that ints were 32-bit. Such a naive assumption, clearly I don't program for Arduino frequently

@Gerben That seemed to fix the problem. I will still let it run overnight, but it has been running now for over 3 hours , with the update rate being 5 times as fast as it was previously (it is now delay(200)) and it is has not frozen yet, so that would be equivalent to 15 hours previously, which definitely would have seen it freeze. Thanks for the help, if you want, post the same thing in an answer and I will accept it.

Try changing rgbIndex++; to rgbIndex=(rgbIndex+1)%numRGBleds;. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.
Also try changing delay(1000) to delay(1). That way the problem might pop up a lot faster.

Thanks a lot for your help! I left it overnight and it is working perfectly now. Sometimes you can stare at your code for hours on end, and then someone else looks at it for 2 minutes and immediately sees the problem.

Well, to be honest, there was nothing wrong with you code, except for the fact that computers only allocate a limited number of bit to represent a number. Anyways, glad to be of help.

valid point, if only arduino int was 32 bit, it would not have been an issue for 68 years, which is well beyond what I expect to actually get out of the project. And that is assuming it never loses power, which if for sure will at some point.


text:
Sketch does not work without delay() or other complex functions like digitalWrite()
I have a simple sketch here that should just blink a led once a second or so (approximately):
boolean onOff=true;
int count=0;

void setup() {
  pinMode(13, OUTPUT);
 }

void loop() {
    count++;
    delay(1);

    if (count == 316) {
    onOff=!onOff;
    digitalWrite(13, onOff);
    count=0;
    }
}

So, if count is 316 it changes the state of led. It works right now, but it does not without delay() function or some other complex ones like digitalWrite() being in the loop() too. If i am deleting delay(), than led is just always on. I can feel it is smth about interrupts, but i am not sure.

What am i trying to do here is to make an alternative to delay() and millis() for my other project. One of the most needed thing for me is to make ASAP (as soon as possible) "timer", so that some code could run every 2(3-4...) iterations of loop(). delay() is bad always, and millis() uses long variable (which is bad for cpu time and ram), and while having problems with ram and cpu time in my project, i want smth lighter for ASAP and other not very precise timing.  So, the questions are:

Why does my sketch works only with delay(), but does not work
without it?
Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
Am i a bad person for trying to make smth like an ASAP timer?:)  Is saved ram and cpu time worth of it?  Any other possible problems?
Can this sketch be workable without delay() or other complex or ram and cpu costly functions?

Thank you.
So, the sketch up there works indeed, but here is the version that you can can observe with your eyes:
boolean onOff=1;
unsigned int counter=0;
unsigned long time=0;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(57600);
}

void loop() {
   if (counter==0)  time=micros();
    counter++;
    if (counter == 0) {
        onOff= !onOff;
    digitalWrite(13, onOff);
    Serial.println(micros()-time);
    }
}

With Serial i was checking delay between blinks, and it is 140164 mcs = 140 ms = 0.14s. But to be honest it feels slower, so please correct me if i can benchmark it in a better way.

Without delay() it is doing exactly what you tell it. It is blinking the LED - just far too fast for you to see. Try using values in the hundreds of millions instead of just a few hundred for your counter.

The typical design pattern used to perform a delay without delay() is described here: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

“millis() uses long variable (which is bad for cpu time and ram)” If you never need to compare timestamps more than 65 seconds apart, then you can do the timekeeping with 16-bit unsigned integers.

@Edgar Bonet , i was thinking about it, but what happens, when previous millis() value is 60000, and than it overflowed and current millis() is 3000? 3000-60000=-57000, and who knows what will arduino do next... Or did i miss smth? Tell me please if so, that would a nice solution.

@ Dirk Grappendorf , thank you for that, but it also uses millis(), and it is too costly in my current project.

@Majenko , indeed it is!) Thank you!

With unsigned ints, 3000 − 60000 = 8536. Unsigned numbers follow the rules of modular arithmetic, which make the overflow irrelevant as long as you compare durations instead of timestamps.

As majenko answered in the comments, the blinking rate will be so fast you can not see it.
Also it is possible that without the delay the optimizer removes the whole counting. So increasing the number as proposed by majenko may not even work due to compiler optimisations.
Using a method based on counters is a very unreliable way to use timings.
Look at the blinkwithout delay example as proposed by Dirk.
It boils down to using millis() for timing. millis tells you how many millis the arduino is running.
void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

There is absolutely no reason for the optimizer to remove the counting. If it did that sort of thing then nothing would ever work. The compiler has no clue what delay() does.

You are right when delay is there. I mean when delay is gone.

Why do you think that removing a function that has no relationship at all with the counting would affect how the compiler optimizes the counting?

because loop() is actually in a while(true) loop. So without the delay you get while(true){count++;if(count==316){[something]}}. Which can get optimized to while(true){[something]}. I have had that happen to me.

What makes you think the optimizer would ever do something as idiotic as that? (By the way: try it for your self. Compile the code without delay() and look at the assembly output. You'll see the count never gets optimized out). The only time the optimizer would remove the counting is if the result of the counting does nothing (i.e., if the if is empty).

As I said, It happened to me. I never stated it would happen. As Arduino now is plenty of toolchains and cores I think it is save to say: I could happen. Maybe you should reread  my answer.

As long as the result of the count is used somewhere (and that "somewhere" doesn't get optimized out) the count will never be optimized, under any circumstances. Such behaviour would break massive amounts of code all over the place. I reiterate: it cannot happen. Ever. Full stop. I suspect your "it happened to me" was something completely different. You may have seen it optimized out as a casualty of something else being optimised out (such as an empty if that gets optimized out) but as long as there is something using the count it CANNOT be optimized out. Counting is perfectly reliable.

This sketch blinks an LED on D10 (on a Uno) at one second intervals. It does not use delay, micros, millis or any unsigned long variables (apart from a constant).
const int STROBE_FREQ = 1000;     // sets the period in milliseconds
const unsigned long countTo = ((float) F_CPU / 1024.0) / (1000.0 / STROBE_FREQ);

void setup ()
  {
  // D10 to output
  bitSet (DDRB, 2);

  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11); // fast PWM
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS12) | bit (CS10);   // fast PWM, prescaler of 1024
  OCR1A = countTo - 1;                 // zero relative
  OCR1B = (countTo / 2) - 1;           // 50% duty cycle
  bitSet (TCCR1A, COM1B1);   // clear OC1B on compare
  }  // end of setup

 void loop ()
   {
    // do something useful
   }

It frees up the main loop to do something useful without worrying about time taken to do the blinking.
For more details see my page about timers.

Wow, thank you for that! But that is so much more than i know for know, i do not really understand that sketch. Can you please provide some more info or some links, so that i could learn what is going on there?  Do i understand correctly that some hardware timer is used here? Also i have no clue how to make a second timer for another pin in that sketch, would love extended example.  Thank you again!

See amended reply. Yes, it uses a hardware timer.


text:
How to read analog sensor data with different timers in arduino
I have three analog sensors like voltage, temperature and pressure. I need to measure the voltage and temperature every 10 ms and I need to measure the pressure alone every 30 ms by using the timers in an Arduino.
How can I do this?

see the BlinkWithoutDelay example in Arduino IDE Examples menu

Have you seen this library? https://www.avdweb.nl/arduino/timing/virtualdelay

please add your code to your post

You only need one timer for this, which triggers every 10ms. Then read pressure only every third time. Or you can just use millis() or micros() depending on the rest of your code. Please share that code and explain what it should do

start with BlinkWithoutDelay as @Juraj mentioned ... do not delete any part of the code ... add a counter variable and set it to zero... go to the part of the program where the LED is updated ... add a function to measure voltage and temperature ... if the counter = 0, then measure pressure ... increment counter ... if the counter = 3, then set counter to zero ... when everything works  then change the delay variable from 500 to 10

". . . by using the timers in Arduino." You have multiple options depending on how deep you need to go for this exercise, listed here in order of increasing complexity. (1) The simple recording of the start time of an event and testing to see if its time slot has expired as in the already mentioned "blink without delay" sketch. (2) Using ready made timer libraries which can call user specified functions at defined intervals etc. and (3) direct configuration of hardware timers to trigger interrupt service routines, directly manipulate gpio pins etc.

May this help as starting point! Not tested
void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
}

unsigned long previousMillis1;
unsigned long previousMillis2;

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis1 >= 10) {
    int val1 = analogRead(A0);
    int val2 = analogRead(A1);
    Serial.print("Values from A0 and A1: ");
    Serial.print(val1);
    Serial.print(" ");
    Serial.println(val2);
    previousMillis1 = currentMillis;
  }

  if (currentMillis - previousMillis2 >= 30) {
    int val3 = analogRead(A2);
    Serial.print("Value from A2: ");
    Serial.println(val3);
    previousMillis2 = currentMillis;
  }
}

Thank you for your kind help Mr. Carlos Costa, but i am in need to use timer 1 or 2. without using millis i have to read the sensor data

Presumably it is a school project. Are you allowed to use ready made libraries or do you have to use direct configuration of the timer's hardware registers? Which Arduino are you using? In any case, the datasheet for the microcontroller is a good (but heavy going) start.

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


text:
SPI with DMA in a Arduino Due
I have a project where I need to store data (~16 Mo) on a memory and be able to fetch the data fast (<36000 bits/s) with DMA because I have other signals to take care of.
Currently I use an SD card with the SD library, but it doesn't seems to use DMA because of the delay between sending.
Many people told me it shouldn't be that hard and I suppose so. My guess is that I can't configure the DMA and/or the SPI correctly.
I tried this a long time ago.
Can someone show me an example of SPI with DMA, or tips on how to configure both?

#include <dmac.h>
#include <SPI.h>
#include <Arduino.h>
#include <sam.h>

uint8_t sourceBuffer[256];

void setup() {
  SPI.begin();
  SPI.setClockDivider(21);  // 4MHz clock (assuming 84MHz system clock)
  setupDMA();
}

void loop() {

  for(int i = 0; i < sizeof(sourceBuffer); i++) {
    sourceBuffer[i] = i;
  }
  startDMATransfer();
  delay(1000);
}

void setupDMA() {
  // Enable the DMA controller
  PMC->PMC_PCER1 |= PMC_PCER1_PID34;  // DMA ID for the Due is 34

  // Disable SPI DMA TX and RX
  SPI0->SPI_PTCR = SPI_PTCR_RXTDIS | SPI_PTCR_TXTDIS;

  // Setup a DMA channel for the transfer (channel 1 for this example)
  DmacChannel* channel = &(DMAC->DMAC_CH_NUM[1]);

  // Disable the DMA channel
  channel->DMAC_CHDR = DMAC_CHDR_DIS;

  // Clear any flags and reset the status
  channel->DMAC_CHDR = DMAC_CHDR_RES;

  // Set up source and destination pointers
  channel->DMAC_SADDR = (uint32_t) sourceBuffer;
  channel->DMAC_DADDR = (uint32_t) &(SPI0->SPI_TDR);

  // Configure source and destination pointers: source increments, destination does not
  channel->DMAC_CTRLA = DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_DST_WIDTH_BYTE;

  // Set source and destination handshake (related to the SPI0 Tx)
  channel->DMAC_CTRLB = DMAC_CTRLB_SRC_DSCR_FETCH_DISABLE | DMAC_CTRLB_DST_DSCR_FETCH_DISABLE |
                        DMAC_CTRLB_FC_MEM2PER_DMA_FC | DMAC_CTRLB_SRC_INCR_INCREMENTING |
                        DMAC_CTRLB_DST_INCR_FIXED;

  channel->DMAC_CFG = DMAC_CFG_SRC_PER(1) | DMAC_CFG_DST_PER(1) | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ALAP_CFG;
}

void startDMATransfer() {
  // Assuming channel 1 is used
  DmacChannel* channel = &(DMAC->DMAC_CH_NUM[1]);

  // Set up the buffer size
  channel->DMAC_CUBC = sizeof(sourceBuffer);

  // Enable SPI DMA for TX
  SPI0->SPI_PTCR = SPI_PTCR_TXTEN;

  // Enable the DMA channel to start the transfer
  channel->DMAC_CHER = DMAC_CHER_ENA;
}

When you want to send data via SPI using DMA, you can fill the sourceBuffer and call startDMATransfer().
Remember to always refer to the Atmel SAM3X8E datasheet and the Arduino Due's schematic when you are working at this level, as it provides in-depth details on how the hardware functions. I am unable to run the code or test it. But I believe that the code logic is proper. Error handling is up to you.


text:
Compressing grayscale image with ESP32-S3-WROOM Freenove
I have a ESP32-S3-WROOM module by Freenove which has a camera and a micro SD card module. I can take a snapshot as a PIXELFORMAT_JPEG photo.
However, when I change the pixelformat to "PIXELFORMAT_GRAYSCALE", the module captures the raw data (1 byte for each pixel) which is 480 kB constant for SVGA (600x800).
How can I compress this raw data to jpg? I also tried the way of saving the photo to a ".jpg" file, however, it did not work.
This is my capturing code for it:
/**********************************************************************
  Filename    : Camera and SDcard
  Description : Use the onboard buttons to take photo and save them to an SD card.
  Auther      : www.freenove.com
  Modification: 2022/11/02
**********************************************************************/
#include "esp_camera.h"
#define CAMERA_MODEL_ESP32S3_EYE
#include "camera_pins.h"
#include "ws2812.h"
#include "sd_read_write.h"

#define BUTTON_PIN  0

void setup() {
  Serial.begin(500000);
  Serial.setDebugOutput(false);
  Serial.println();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  ws2812Init();
  sdmmcInit();
  //removeDir(SD_MMC, "/camera");
  createDir(SD_MMC, "/camera");
  listDir(SD_MMC, "/camera", 0);
  if(cameraSetup()==1){
    ws2812SetColor(2);
  }
  else{
    ws2812SetColor(1);
    return;
  }
}

void loop() {
  if (digitalRead(BUTTON_PIN)==LOW) {
    delay(20);
    if (digitalRead(BUTTON_PIN)==LOW) {
      ws2812SetColor(3);
      while (digitalRead(BUTTON_PIN)==LOW);
      camera_fb_t * fb = NULL;
      fb = esp_camera_fb_get();
      if (fb != NULL) {
        int photo_index = readFileNum(SD_MMC, "/camera");
        if (photo_index!=-1) {
          String path = "/camera/" + String(photo_index) +".jpg";
          Serial.println(fb->len);
          writejpg(SD_MMC, path.c_str(), fb->buf, fb->len);
        }
        esp_camera_fb_return(fb);
      }
      else {
        Serial.println("Camera capture failed.");
      }
      ws2812SetColor(2);
    }
  }
}

int cameraSetup(void) {
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.frame_size = FRAMESIZE_SVGA;
  config.pixel_format = PIXFORMAT_GRAYSCALE; // for streaming
  config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
  config.fb_location = CAMERA_FB_IN_PSRAM;
  config.jpeg_quality = 20;
  config.fb_count = 1;

  // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
  // for larger pre-allocated frame buffer.
  if (psramFound()) {
    config.jpeg_quality = 10;
    config.fb_count = 2;
    config.grab_mode = CAMERA_GRAB_LATEST;
  } else {
    // Limit the frame size when PSRAM is not available
    config.frame_size = FRAMESIZE_SVGA;
    config.fb_location = CAMERA_FB_IN_DRAM;
  }

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return 0;
  }

  sensor_t * s = esp_camera_sensor_get();
  // initial sensors are flipped vertically and colors are a bit saturated
  s->set_vflip(s, 1); // flip it back
  s->set_brightness(s, 1); // up the brightness just a bit
  s->set_saturation(s, 0); // lower the saturation

  Serial.println("Camera configuration complete!");
  return 1;
}

This is the writejpg() function that the code snippet used:
void writejpg(fs::FS &fs, const char * path, const uint8_t *buf, size_t size){
    File file = fs.open(path, FILE_WRITE);
    if (!file) {
        Serial.println("Failed to open file for writing");
        ws2812SetColor(1);
        delay(100);
        return;
    }
    file.write(buf, size);

    // Define the chunk size
    const size_t chunkSize = 2048;

    // Write to serial in chunks
    for (size_t i = 0; i < size; i += chunkSize) {
        // Calculate the size of the current chunk
        size_t currentChunkSize = ((i + chunkSize) <= size) ? chunkSize : (size - i);

        // Write the current chunk in hex format to serial
        for (size_t j = 0; j < currentChunkSize; ++j) {
            Serial.printf("%02X ", buf[i + j]);
//            if ((j + 1) % 128 == 0) { // Print a new line every 16 bytes for better readability
//                Serial.println();
//            }
        }
    }
    Serial.println();
    Serial.printf("Saved file to path: %s\r\n", path);
}

This function also prints out the hexadecimal values of the image for debugging.
So, do you guys have any ideas for compressing this image into a jpg file?

I just managed to solve this problem with using frame2jpg() function.
Hope it helps!

Perhaps you would like to expand this answer to include a little more detail?

Of course! There is a code that to_jpg() which located in esp32 github repo. You can find the "frame2jpg()" function in it. Also the usage will be like "frame2jpg(fb, quality, &jpg_buf, &jpg_buf_len)" it will return a boolean value which indicating the success situation. If you dont understand, I'm here to help!


text:
LED button alarm with DS3231 RTC problems
I am a PHP web programmer, but I am a beginner studying Arduino. I would like to inquire about a problem with the following function that I am creating while looking for various references. (This article was written through Google Translator.)
I would appreciate it if you could see what the problem is and give me some advice.
I also posted this question on the arduino forum.
▶ Program function: To save battery, in sleep mode, when the button is low, it wakes up with a button interrupt and pressing and holding the button sets the alarm. After setting the alarm, it goes back into sleep mode and when the time comes, the LED blinks through an interrupt via RTC. When the button is set low, the alarm is disabled and you must press and hold it to reset the alarm.
▶ Problem: The first run goes well, but if you turn off the alarm and set the alarm again, the next alarm does not run. (When the alarm time comes, you have to turn it off and then set the alarm again after a certain time.)
▶ Hardware used: Arduino Nano (CH340), DS3231 RTC, Ywrobot LED button switch module
▶ Program source:
#include "RTClib.h"  // DS3231 library
#include <avr/sleep.h>

const int alarmPin = 2;  // The number of the pin for monitoring alarm status on DS3231
const int btnPin = 3; // button interrupt
const int ledPin = 4;

int countBlink;
unsigned long buttonPressTime;
bool buttonState;
bool ledState;
long current_millis;
unsigned long previousMillis = 0;
bool alarmActive = false;
const int check_interval = 1000;

RTC_DS3231 rtc;
DateTime alarmTime;

void setup() {
  Serial.begin(9600);               // Start serial port for monitoring
  pinMode(alarmPin, INPUT_PULLUP);  // Set alarm pin as pullup
  pinMode(btnPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }
  if (rtc.lostPower()) {
    // this will adjust to the date and time at compilation
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  rtc.disableAlarm(1);
  rtc.clearAlarm(1);

  rtc.writeSqwPinMode(DS3231_OFF);  // Place SQW pin into alarm interrupt mode
  DateTime now = rtc.now();
  char buff1[] = "Now: YYYY MM DD hh:mm:ss";
  Serial.println(now.toString(buff1));
  delay(1000);
}

void loop() {
  current_millis = millis();
  buttonState = digitalRead(btnPin);
  if (buttonState == LOW) {
    alarmActive = false;
    buttonPressTime = millis();
    while (digitalRead(btnPin) == LOW)
      ;
    if (millis() - buttonPressTime > 1500) {
      Serial.println("Long press detected");
      settingAlarm();
    }
  }

  if (alarmActive) {
    blink_led();
  }
  if (!alarmActive) {
    digitalWrite(ledPin, LOW);
    Serial.println("...Zzz....");
    Serial.println("====================");
    enterSleep();
  }

  //delay(check_interval);
}

void blink_led() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= 1000) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }
    digitalWrite(ledPin, ledState);
  }
}

void sleeping_led() {
  for (countBlink = 0; countBlink < 5; countBlink++) {
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
    delay(200);
  }
}

void settingAlarm() {
  DateTime now = rtc.now();  // Get current time
  alarmTime = now + TimeSpan(0, 0, 0, 20);
  rtc.setAlarm1(alarmTime, DS3231_A1_Second);  // In 20 seconds
  char buff4[] = " YYYY  MM DD hh:mm:ss";
  Serial.println(alarmTime.toString(buff4));
  Serial.println("===================");
  sleeping_led();
}

void enterSleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);  // Setting the sleep mode, in this case full sleep
  noInterrupts();                       // Disable interrupts
  sleep_enable();                       // Enabling sleep mode
  attachInterrupt(digitalPinToInterrupt(alarmPin), wakeUp, FALLING);
  attachInterrupt(digitalPinToInterrupt(btnPin), checkUp, FALLING);
  Serial.flush();  // Ensure all characters are sent to the serial monitor
  interrupts();    // Allow interrupts again
  sleep_cpu();     // Enter sleep mode
  rtc.disableAlarm(1);
  rtc.clearAlarm(1);
}

void wakeUp() {
  sleep_disable();                                   // Disable sleep mode
  detachInterrupt(digitalPinToInterrupt(alarmPin));  // Detach the interrupt to stop it firing
  detachInterrupt(digitalPinToInterrupt(btnPin));    // Detach the interrupt to stop it firing
  alarmActive = true;
}

void checkUp() {
  sleep_disable();                                   // Disable sleep mode
  detachInterrupt(digitalPinToInterrupt(alarmPin));  // Detach the interrupt to stop it firing
  detachInterrupt(digitalPinToInterrupt(btnPin));    // Detach the interrupt to stop it firing
}

we'll wait to see what results you get at the arduino forum

You can use the "uRTCLib.h" library instead. Here is a detailed tutorial:
https://lastminuteengineers.com/ds3231-rtc-arduino-tutorial/
Here is also an Arduino-based project using DS3231: https://www.pcbway.com/project/shareproject/Arduino_based_weather_station_with_the_atmega328p.html I hope these tutorials will help you.


text:
Incremental Rotary Encoder sends data when shaft is untouched
I'm trying to build an Arduino project that counts pulses sent by an encoder.
I've bought an Omron E6B2-CWZ5B-2 2000P/R and face the issue of it sending pulses non-stop, even when I'm not touching it. The code I use is from this video.
I thought that the encoder itself was the problem and bought two encoders like in the video above (LPD3806-400BM-G5-24C), but I faced the exact same problem.
When I connect the encoder to the Arduino 5 V and GND ports, the encoder doesn't seem to work at all (in the video it does without any resistors, etc.). I had to use a different power source, which was a laboratory power supply, which I set to around 6 V.
I connected the A output to digital pin 2 and the B output to digital pin 3 of my Arduino Uno. The problem is - the values just start going up and down at an insane speed without me touching the encoder. If I only connect output A, they go like I'm spinning it hard left, if I connect only the B output, they go like I'm spinning it hard right. If I connect both of them, it's just a massacre of data, like I'm spinning it left and right insanely fast.
The other thing I noticed - if I power up my Laboratory power supply to 12 V and more it seems that the encoder sends even more data per sec.
I only managed to get it working properly once and can not repeat it now. I did the following:
I powered the LPD3806 with 5.5 V externally (lab power supply), took the ground shield of encoder and held it really tight to Arduino Uno USB port. Data spam stopped and the encoder worked properly when I'm twisting the shaft. But I can't repeat this thing now.
It's clear the problem is with grounding, but I wonder how I can fix it to use it in an okay way. And I still wonder how the author of the video above got results with no use of the ground shield at all.
So the question is - how do I fix it and where did I go wrong?
Here are some schematics. I don't know how to do them properly, so I did them with Wokwi. So to read it keep in mind that:

I marked A and B output cables of my LPD3806 encoder as CLK and DT on the rotary encoder from wokwi.com

The VCC and GND symbols at the very top of some schemas here are + and - of my laboratory power supply

I marked my ground shield as SW on the third schema to show where I held it to get it working.

Here's how I tried to power it from the Arduino itself. It just didn't start. No signal; nothing.

So I powered it from the lab power supply. Now the encoder started, but it was just spamming numbers. When I increased the voltage, the number-spamming got faster.

And here's how I got it working once by pulling the ground shield tight to the Arduino USB port (keep in mind in my schema I marked ground shield as SW on the encoder).

Here's the code I use:
volatile unsigned int temp, counter = 0; // This variable will increase or decrease depending on the rotation of encoder

void setup() {
  Serial.begin (9600);
  pinMode(2, INPUT_PULLUP); // internal pullup input pin 2
  pinMode(3, INPUT_PULLUP); // internal pullup input pin 3
  // Setting up interrupt
  //A rising pulse from encoder activates ai0(). AttachInterrupt 0 is digital pin nr 2 on most Arduinos.

  attachInterrupt(0, ai0, RISING);

  // B rising pulse from encoder activates ai1(). AttachInterrupt 1 is digital pin nr 3 on most Arduinos.

  attachInterrupt(1, ai1, RISING);
}

void loop() {
  // Send the value of counter
  if (counter != temp) {
    Serial.println (counter);
    temp = counter;
  }
}

void ai0() {
  // ai0 is activated if digital pin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if (digitalRead(3)==LOW) {
    counter++;
  } else {
    counter--;
  }
}

void ai1() {
  // ai0 is activated if digital pin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if (digitalRead(2)==LOW) {
    counter--;
  } else {
   counter++;
  }
}

Looking forward for your answers and thanks in advance!

please add the wiring diagram

From the description that sounds like a floating pin, though you already have the internal pullups activated. You wrote, that you use an external power supply for the encoder. Did you connect the grounds of that supply and the Arduino? Have you tried adding stronger external pullup resistors (like 1 to 4.7kOhm)? The seller site, that I found with this encoder claims, that you can connect it directly to Arduino 5V pin. Though it might, that your voltage is right at the lower end of the valid power voltage range of the encoder (4.8V). USB voltage can easily get as low as 4.5V

@chrisl I did try it with external pull-up resistors - no help. But I moved forward a little bit! I did everything like before - I powered LPD3806 with 5.5v externally and got it working properly once.
How I did it - I took the ground shield of encoder and held it really tight to Arduino Uno USB port. Data stopped and encoder only worked properly when I'm twisting the shaft. But I can't repeat this thing now. It's clear the problem is with grounding, but I wonder how can I fix it to use it in an okay way. And I still wonder how the author of the video got results without ground shield at all.

You absolutely need to connect all grounds. Your wiring diagram is missing the connection between external power supply ground and Arduino ground

From the datasheet: the E6B2-CWZ5B 2000P/R 0.5M encoder has an output circuit which is described as PNP open collector. That is, the output swings from whatever voltage you are running the encoder at (12 V to 24 V) to high impedance:

You probably want to wire it to your (5 V?) Arduino in this manner. The resistor divider is balanced for ~12 V:

Your loop() could be better structured to avoid non-atomic reads because it appears that you are using an 8-bit Arduino and an int is 16-bit. There is, therefore, a risk that an ISR will corrupt the variable counter while you are attempting to read it in the loop():
void loop() {
  // Send the value of counter
  noInterrupts() ;
  int counter_copy = counter ;
  interrupts() ;
  if (counter_copy != temp) {
    Serial.println (counter_copy);
    temp = counter_copy;
  }
}

Thanks for your answer! But the thing is - I tried it with Omron before, powering it with 12v adapter. Now I'm trying it with LPD3806-400BM-G5-24C, which is 5-24V. As the video above shows, it can be powered with Arduino but it doesn't seem to work that way.
What I did now - I powered it with 5.5v externally and got it working properly once. How I did it - I took the ground shield and held it really tight to Arduino Uno USB port. Data stopped and only worked when I'm twisting the shaft. But I can't repeat this thing now. It's clear the problem is with grounding, but I wonder how can I fix it.

@DoICare . OK. The second device you have LPD3806-400BM-G5-24C has apparently an open collector (NPN) output so that is wired in a different way to the first so connecting it to an Arduino pin (per phase) and using the internal pullup is correct. The encoder can be driven still at a higher voltage that the the Arduino. However, it is also important that there is a common ground between the Arduino and the encoder. Anyway, show your wiring diagram. This is the nearest I have found to a data sheet with a quick search: domoticx.com/sensor-lpd3806-optical-rotary-encoder

I've just looked at the video. The red wire from the encoder can only be connected to the Arduino if you are powering the encoder at 5v from the Arduino only. Otherwise the encoder red wire should go to an external power supply and again all grounds should be common.

Thanks for your answer once again! I've updated my question with some schemas, would be great if you check it out. I'm pretty new to electronics and I struggle understanding how to set common ground. Again - when I tried to do this with ground shield held tight to Uno USB port, it did work but only for a while

Even when you use a lab power supply, all the grounds must be connected together. That is, the power supply ground, the arduino ground and the encoder ground (and 0v and shield if the encoder has these). So your last 2 pictures of the Uno setup are clearly wrong because there is no shared ground. Can you find a better data sheet for that LPD3806-400BM-G5-24C encoder?


text:
Can I wire LEDs without resistor with an Arduino like this?

There are four red LEDs and an Arduino in the picture. Each LED has a forward voltage of 2 V. My friend says that just digitalWrite(9,HIGH) will make the LEDs light without resistor and they won't be burnt. Is this true?

The LEDs will be fine. The Arduino won't be happy though.

It doesn't hurt to add a cheap resistor, at least it will prolong the life of your LEDs and Arduino

That can work, if you don't set pin 9 to OUTPUT (using pinMode). Calling digitalWrite on an INPUT pin will enable the internal pull-up resistor (around 30kOhm). So in that case there is still a resistor limiting the current. The leds won't be very bright due to the high value of the resistor.

Another option would be to have 3 leds in series, instead of only 2. That way the combined forward voltage will be 6V. Supplying 5V will result in less current going through the leds. Though it may not be enough for the leds to light up, or at least not light up very brightly.

if you want the pro answer, you'll need the datasheet for the LEDs. Look for the v/i curve and see how much current 2.5v causes. If it's more than half the UNO's max pin current, you're out of spec and bad things may or may not happen. It's like hanging 60kgs on a rope rated for 50kg; it might work, maybe even probably will work...

I am assuming you only have 5VDC available. Your friend is almost correct, it will work for a while however in the long run it will probably fail unless you are one of the lucky ones. What is the Vf (forward voltage drop) range of the LEDS (you state 2V), and are they matched by pairs, if not they will not illuminate evenly. You are forcing the arduino to output its maximum on port D9. I believe the current will not be within the microprocessor specifications. You are assuming a LED is a voltage device, it is not it is a current device. A resistor or constant current source is normally used to drive LEDs.  The LED driving circuit must provide sufficient current to light the LED at the required brightness, but must limit the current to prevent damaging the LED and driver. Typically, the forward voltage (Vf) of an LED is between 1.8 and 3.3 volts. It varies by the color of the LED. A red LED typically drops around 1.7 to 2.0 volts, but since both voltage drop and light frequency increase with band gap, a blue LED may drop around 3 to 3.3 volts. across an LED is approximately constant over a wide range but can vary from LED to LED.
LEDs are diodes and have a

Depending on the LEDs, it might or it might not, who knows?
You'll be both safe and in control by adding a small resistor in series (either with each individual LED or, if the LED pairs are balanced, with the whole LED circuit). The resistor value depends on the LEDs and the Arduino's supply voltage.


text:
Correct syntax for setCACert ESP8266
I am trying to use a cert with an ESP8266. The identical code works fine on ab ESP32, but in the ESP8266 I am getting errors.
I set the cert as follows:
const char *ROOT_CERT PROGMEM = R"EOF(= "-----BEGIN CERTIFICATE-----
MIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
...
-----END CERTIFICATE--------)EOF";

For the ESP32 I use:
wifiClient.setCACert(ROOT_CERT)

This works fine, but on the 8266 I get:
no matching function for call to 'BearSSL::WiFiClientSecure::setCACert(const char*&)'

I have done some research and there are some suggestions the length is required, so I tried that also:
 wifiClient.setCACert(ROOT_CERT, sizeof(ROOT_CERT)-1);

But that produces the following error:
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

I am using the 2.7.4 8266 board library as I have heard the 3.X has similar issues.
I have tried V 3.X but I get the following:
class BearSSL::WiFiClientSecure' has no member named 'setCACert'

i could not use setCACert with 8266.  you need to do it differently and i had to do some web hunting.
But finally i did get my telegram test working from esp32 to 8266,
here is what i did and hope that you can adapt it
you need :
#include <ESP8266WiFi.h>

after your defines add:
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtokenValue,client);

in setup i had to add BOTH of these lines (i initially didnt think i needed the 1st line, but apparently you do) :
configTime(0, 0, "pool.ntp.org");   // get UTC time via NTP
client.setTrustAnchors(&cert);      // Add root certificate for api.telegram.org

this got my ESP32 code converted from ESP32 to 8266

PS- replace WiFi.h  with the ESP8266WiFi.h


text:
loop() either stops working, or lcd stops working | buttons don't work
I'm using a Let's Start Coding Ultimate Kit 1 (it was a christmas present, don't ask) and I'm trying to use this as a typing sort of thing. I haven't implemented the actual letters though.
#include <MakerScreenXVI.h>;

MakerScreenXVI lcd;

int currentNumber = 1;
int ms = 0;
int totalMS = 0;
bool first = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, INPUT);
  pinMode(A3, INPUT);

  lcd.begin();
  lcd.print("Success");
  lcd.setCursor(0,1);
  lcd.print(currentNumber);

}

void loop() {
  delay(200);
  changeNumber();
  delay(200);
}

void clearLCDLine(int line) {
        lcd.setCursor(0,line);
        for(int n = 0; n < 16; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
        {
                lcd.print(" ");
        }
}

void changeNumber() {
  if (digitalRead(A0) == LOW) {
    if (first == false) {
      clearLCDLine(1);
      first = true;
    } else {
      first = false;
    }
    currentNumber++;
    if (currentNumber == 27) {currentNumber = 1;}

    lcd.print(currentNumber);
  } else if (digitalRead(A3) == LOW) {
    currentNumber = currentNumber - 1;
    if (currentNumber == 0) {currentNumber = 26;}
    //clearLCDLine(1);
    lcd.print(currentNumber);
  }
}

For some reason, after it deletes the 1, it stops. Nothing is printed onto the screen, and nothing is cleared from it. How can I fix this?
Also, the buttons always return the LOW value. How can I fix this?

I don't know the LSCU-Kit, but are there any pull-up resistors at the inputs? If not, can you set the pins with internal pull-ups and try that?

The buttons will send a LOW signal when pressed if they are set with pinMode INPUT_PULLUP.
The issue with currentNumber not displaying is that after you clear the screen with the 'for' loop, you need to reset the cursor to position 0,1 with lcd.setCursor(0,1); . Otherwise, the numbers are printing out of view.
If I add lcd.setCursor(0,1); just above each line with lcd.print(currentNumber); , I think the code has the behavior you're looking for.
Edit from the person who asked the question:
 You also have to add a delay of around 150-200, or else one push will count as many.

For some reason, I did something (I think with the button and the sockets on the board) and both buttons go down into negatives. I followed your instructions. Before that, you would have to press the down button first (A3) for the other button to work, and then it would show the single digit numbers and a zero. How can I fix this?

If I understand correctly, you've made some changes to the code, so it's hard to provide direct advice without seeing it. The code you posted above provides "bounds" for the currentNumber variable with the "if" statements. I recommend sending us an email at info@letsstartcoding.com with the code and we may be able to help.


text:
WiFi.begin doesn't work with ArduinoJson's const char* output
I'm using ArduinoJson to parse a file full of JSON strings that contain the SSID and password for the registered networks. I have a little web interface that runs in soft AP mode so you can scan for networks and add them to the file. Adding networks to the file works fine, but reading them back and using them as input for WiFi.begin doesn't work. It moves to status code 1, which means it failed to find a network with that SSID.
I have compared the value of the result of const char* ssid = networks[network]["ssid"]; with const char* _ssid = "MySSID"; using strcmp and it returns 0, so I can't figure out why it's not working. It works if I replace networks[network]["ssid] with my SSID (though I need to replace the password with the string literal as well, otherwise it stays on status code 6, disconnected).
I can't figure out what it is about ArduinoJson, but it seems that the result of grabbing a string doesn't return a string that is formatted correctly for WiFi.begin, but it satisfies strcmp?
Edit:
I modified the code quite a bit in an effort to get it to work. I am no longer passing the ArduinoJson object, I'm now passing a struct with the data, and it still doesn't work. Is this the work of some advanced c++ constants/pointers stuff that I don't seem to understand?
main.cpp:
#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>
#include <SPIFFS.h>
#include <vector>
#include <elapsedMillis.h>

#include "config.h"
#include "restserver.h"
#include "scanwifiserver.h"

AsyncWebServer *Server = new AsyncWebServer(80);

ScanWifiServer *scanWifi;
RestServer *restServer;

struct Network {
    const char* ssid;
    const char* password;
};

std::vector<Network> readAP(fs::FS &fs) {
    //fs.remove("/ap.txt");
    File file = fs.open("/ap.txt");
    std::vector<Network> networks;
    if (!file) {
#ifdef DEBUG
        Serial.println("Failed to open file for reading");
#endif
        return networks;
    }

    while (file.available()) {
        DynamicJsonDocument n(JSON_CAPACITY);
        auto s = file.readStringUntil('\n');
        deserializeJson(n, s);
        struct Network network = {n["ssid"], n["password"]};
        networks.push_back(network);
        Serial.println(networks.back().ssid);
    }

    file.close();
    return networks;
}

void setup() {
#ifdef DEBUG
    Serial.begin(BAUDRATE);
    delay(2000);
#endif

    SPIFFS.begin();
    auto networks = readAP(SPIFFS);
    if (networks.size() > 0) {
        Serial.println("Networks:");
        int network = 0;
        Serial.println(networks.size());
        while (WiFi.status() != WL_CONNECTED && network < networks.size()) {
            const char* ssid = networks[network].ssid;
            const char* password = networks[network].password;
            Serial.printf("%s, %s\n", ssid, password);

            WiFi.begin(ssid, password);

            while (WiFi.status() != WL_CONNECTED) {
                if (WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_NO_SSID_AVAIL)
                    break;
                delay(500);
                Serial.print(WiFi.status());
            }
            Serial.println("");
            network++;
        }
        if (WiFi.status() == WL_CONNECTED) Serial.println("Connected");
        else networks.clear();
    }
    if (networks.size() == 0) {
        Serial.println("Starting ScanWifiServer");
        WiFi.mode(WIFI_AP);

        scanWifi = new ScanWifiServer(Server);

        Server->begin();

        MDNS.begin("grow");
        MDNS.addService("http", "tcp", 80);
    }
}

void loop() {}

add WiFi.persistent(false); and WiFi.setAutoConnect(false)

I found the solution myself. I switched from using struct Network network = {n["ssid"], n["password"]}; to declare the struct and const char pointers to using char arrays and strcpy
struct Network network;
strcpy(network.ssid, n["ssid"]);
strcpy(network.password, n["password"]);

Seems like the pointers were getting freed or something right at the same time that I tried to use the value to connect to the network?

std::vector<JsonDocument> doesn't store a copy of the complete document, but just a copy of the internal pointers of JsonDocument. Therefore, at the time you use the value, it points to an invalid location.
This is clearly a bug, that's why I removed the copy constructor of JsonDocument, but the change hasn't been published yet.
You can fix your program by replacing the std::vector<JsonDocument> with std::vector<DynamicJsonDocument>.

Thanks for the response, though I modified my code a bunch and it still doesn't work. Do you know what's going on?


text:
Replacing large lookup table with switch statement
My arduino needs to take a 14-bit number and convert it to a 10-bit number. Can't use a formula for it since the data is quite random. So I created a lookup table with 2^14 elements, each containing a 10-bit value. But it's too big to fit on the arduino. So I thought of using a switch statement instead. Would this result in a significant speed decrease?
Say, for example, that the input value is 16383. How much longer would it take for the arduino to iterate through the 16384 cases compared to accessing index #16383 of an array?
EDIT: This code compiles fine and reports a program memory usage of 1000 bytes.
int xval;
int yval;

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  xval = random(0,16383);
  switch (xval) {
  case 0:
  yval = 0;
  break;
  case 1:
  yval = 4;
  break;
  case 2:
  yval = 4;
  break;
  case 3:
  yval = -60;
  ...
  case 16383:
  yval = 1023;
  break;
}
}

However, I haven't tried if it really works so maybe the compiler is optimizing away too much.
EDIT 2: Added the line Serial.println(yval); so that I'm actually doing something with yval as Majenko commented. And now it doesn't compile :'( :'( :'(
So, I'll tackle my problem in some other way.

If you don't have room for an array, what makes you think you'll be able to store the same (or more) data in the same space?

So, if you don't have some kind of formula or algorithm, did you really written 16384 numbers by hand? Normally there is some kind of algorithm, that can also be implemented in the Arduino

Haha no I didn't write them by hand but I've collected the data through an automated process.

You say you cannot use a formular. So that means random in and random out? Ok no that case you simply could short the size. If not, you should be able to use a formular. Otherwise it does not make any sense at all. Could you explain more what exactly to try to achieve? What are those 14-bit numbers and how do they relate to the 10-bit output?

You could store this table in some form of external storage. Something like EEPROM or an SD card.

214 is 16384 entries. Each entry takes 2 bytes. That's 32768 bytes. That's all the flash the ATMega328P has.
The most efficient storage will be an array in flash, and that will take 100% of it. Using a switch will take more space.
So in short: no. Just no. It won't work whatever you try. You need to come up with a radically different storage solution (external flash memory?) or use a larger chip.

As a side note, with "bit packing" you could reduce the storage to 20480 bytes, but doing a lookup of the data within that packed data (4 10-bit entries taking 5 bytes) will be slow to do since you have to work out exactly what combination of bits and bytes you need to reconstruct your 10-bit value.

I might be able to compress the array in some way. There's a lot of duplicates in the array so the amount of unique values is a lot less than 16384.

What is it you're doing that needs such a huge lookup table?

In short, an adapter that reverses some value conversion that takes place in a software.

How come Arduino compiles the code fine? I tested with the long switch statement of 16384 cases and it says it uses only 1000 bytes. I'll edit my question to include this.

If you're not actually doing anything with yval the compiler will optimise all that code out.

Dammit, you're absolutely right! :'(

Could always change to a 1284P based board, with 128K flash, will easily hold a large lookup table in PROGMEM.

Almost certainly not
Compilers often optimise switch statements using jump tables. However the entries in the jump table basically make up a lookup table with 214 entries! So you don't gain anything.
Some ideas for compression

You can use bit packing

If your numbers aren't 8 bits in size, you can pack them together. For example, if you have managed to code things in 6 byte chunks, you can squash 4 of these chunks into 3 bytes, to shrink a table by 25% (at the expense of some bit shifts when retrieving entries.)

Take advantage of frequency of duplicates

You say you have duplicates. But how many "very common" duplicates are there?
If, say, 90% of your values come from a group of 15 possible values, then you can pack 2 entries per byte, each one represented by a value from 0-14. If one of the entries is 15, then that that value is an "exception" and is looked up by binary search in a second table.
This would result in a table of size 8KB plus the size of the other table (say 4KB when you pack the 14 bit index and 10 bit value into 3 bytes.)
If you instead have a set of 254 possible "common" values, then your main table would be more like 16KB. That might be doable.

Is there any relation between input and output?

Maybe there is no formula, but there might be properties of the input that affect the properties of the output. (For example, maybe most input values 0-1024 have an output that is similar plus or minus 30.)

Write a program to find patterns in your data

Don't just use your eyes. Write a script (Python?) to count the frequency of each output value, or compare inputs to outputs, or evaluate your suspicions about the data. Graph input vs output.


text:
Sending and receiving custom messages with Ardulink
I am sending custom code to Arduino with this ardulink command:
{        ArduinoControl.link.sendCustomMessage("oled");
}

Code from standard Ardulink sketch CustomMessagesChipKit.ino:
{
  if (stringComplete) {
    if(inputString.startsWith("alp://")) {
    // OK is a message I know (this is general code you can reuse)
      boolean msgRecognized = true;
      if(inputString.substring(6,10) == "cust") { // Custom Message
        // here you can write your own code.
        int separatorPosition = inputString.indexOf('/', 11 );
        int messageIdPosition = inputString.indexOf('?', 11 );
        String customId = inputString.substring(11,separatorPosition);
        String value = inputString.substring(separatorPosition + 1, messageIdPosition);
        if(customId == "oled") {
            //Clear the virtual buffer
            lcd.noBacklight();
            analogWrite(9,100);
            digitalWrite(13, HIGH);
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("jkhgvjgv");
        } else {
          msgRecognized = false;
          // this sketch doesn't know other messages in this case command is ko (not ok)
        }
      } else {
        msgRecognized = false;
        // this sketch doesn't know other messages in this case command is ko (not ok)
      }
      // Prepare reply message if caller supply a message id (this is general code you can reuse)
      int idPosition = inputString.indexOf("?id=");
      if(idPosition != -1) {
        String id = inputString.substring(idPosition + 4);
        // print the reply
        Serial.print("alp://rply/");
        if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
          Serial.print("ok?id=");
        } else {
          Serial.print("ko?id=");
        }
        Serial.print(id);
        Serial.write(255); // End of Message
        Serial.flush();
      }
    }
    // clear the string:
    inputString = "";
    stringComplete = false;
  }}

As a result the LED on pin 13 is turning on after message from java program. But that is all. LCD or or LED on PWM 9 pin are not reacting at all.
Also I could not understand how to send an answer back from Arduino to Ardulink. Can you please show me an example? I would love to send and print data in Java program from  DHT11 sensor in response. I know about RawDataListener and I read the whole Ardulink site, but I did not understand that. I a newbie in programming.
When i replace
{String customId = inputString.substring(11,separatorPosition);}

with
{String customId = inputString.substring(11,15);}

than everything works. What can it be?

you can read a complete (real project) example about how to receive messages from Arduino with Ardulink from here: https://github.com/openQCM
In general you can use a listener (digital, analog, and raw) to receive messages from Arduino. A raw listener receive all messages received from Arduino, so you need to implement code to filter the messages you are interested in. Digital and Analog listeners receive events from digital and analog PINs.
The sketch in your question isn't the original sketch you can find in Ardulink distribution. That sketch was written to manage the OLED on the ChipKit shield I have. You have modified the sketch to manage your LCD.
Actually you can send successfully messages from an Ardulink based application (as Ardulink Console) to Arduino since LED on PIN 13 is turned on. So the problem maybe just on your sketch.
To FIX analogWrite on PIN 9 try to set the PIN as OUTPUT with this statement:
pinMode(9, OUTPUT);
I cannot help you with lcd library that I don't know.
If you need for some help don't hesitate to write to me.

PIN 9 is set as OUTPUT, but it still does not work. I thought it was smth with library too, but i guess it is not.

It looks like you're trying to send a custom message to arduino and have it respond. As a small add on to your code try serialCommand. It pulls in whatever you send over the command line and executes it as a command and returns whatever you need to whatever interface you gave such as softwareSerial.
https://github.com/scogswell/ArduinoSerialCommand/tree/master/examples
I offer that you could use the two together to get the results you want.
Let serialCommand listen for commands and execute them and then set up a listener in Java for any serial communication back from the unit.
That's more or less what I end up doing when it comes to bluetooth, rf24, and wifi anyway, so why not serial as well.


text:
XBee + Arduino Problem
I've been doing some XBee experiments with Arduino Pro Mini 5V. I knew that XBee S2 is 3.3V only, so I've connected its Vcc to 3.3V from external supply, but I had also connected XBee RXTX to arduino TXRX, in this order, and since that i can't use my XBee Explorer to communicate with XCTU on my notebook. The connections with an 5V Arduino RXTX can cause damages to the XBee, even if the XBee was powered with 3.3V?

Try to add a voltage divider on Arduino's TX to shift it to 3.3v logic. This might solve your problem.

The thing is, I can't even communicate with the XBee with a XBee Explorer to my computer, since I did that. Its problaby bricked or damage. What I wanna know if it can get damaged from the RXTX pins.

Did you try the opposite wiring? TX --TX and RX -- RX ?

I've tryed it eventualy as some guides for bricked XBee sugested, but nothing happend.

Is this the first time you tried to work with this xbee? Was it working before this time? Please tell me how do you connect it to your computer?

I just started working with XBee this week. Yes, I could do some thing before it "bricked". I've connected it to my computer with an XBee Explorer from Parallax. http://www.hobbytronics.co.uk/wireless/zigbee/xbee-usb-adapter

Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, http://knowledge.digi.com/articles/Knowledge_Base_Article/Recovery-procedure-for-ZigBee-XBees. I really think that the XBee is gone. :/

Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, knowledge.digi.com/articles/Knowledge_Base_Article/…. I really think that the XBee is gone. One way to avoid this problem is to get one of this regulated breakout board. http://www.hobbytronics.co.uk/xbee-explorer-reg. As it says in the description, it regulates ALL pins to 3.3V, making me believe that I needed to take care of that before making such a mistake. Hopefully this prevent someone from doing this mistake in the future. So, bye-bye XBee.

Based on the information found here: https://www.faludi.com/bwsn/xbee-level-shifting/ . It seems that xbee isn't that sensitive and maybe you can apply 5v logic to RX pin.


text:
How to program ESP8266 with Arduino Uno pins 0 and 1?
I know that I can connect an ESP8266 with an Arduino Uno at pins 0 and 1, which is Rx and Tx, and enter commands manually in the serial monitor the commands to test it.
I had tried to use software serial and altserial to connect an ESP8266 to other pins, but it was error prone at sometimes.
My question is that how to use an automated program to control an ESP8266 when I connect the ESP8266 with an Arduino Uno at pins 0 and 1.
Sample code would be helpful.
Edit: I have added a simple program to blink led when it get response but it is not working. could you look at it too?
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  delay(3000);
  pinMode(12,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(12,LOW);
  delay(2000);
  Serial.println("AT");
  if(Serial.available())
  {
    digitalWrite(12,HIGH);

    while(Serial.available())
    {
      char c=Serial.read();
    }

    delay(2000);
  }

}

What are you trying to achieve here using esp8266 and arduino? You said connecting using software serial was error prone. What do you mean? Were you getting junk values in the serial monitor? or something else.. please be specific. There could be a lot of issues related to power supplied or the buad rate or even loose connections...

Remember that the TX pin on the arduino puts out 5v logic levels, while the ESP8266 require 3.3v logic level. You can create a buffer using a simple diode (cathode on the Arduino TX pin, anode on the ESP RX pin)

The problem with using pins 0 and 1 is that they are also used to communicate with the PC for both serial monitoring and programming.
If you attach an ESP8266 to pins 0 and 1 chances are you will fail when uploading a new sketch - you will have to disconnect the ESP8266 every time you need to upload a new sketch - that is why most people use SoftwareSerial.
Also if you are using pins 0 and 1 for the ESP8266 you cannot then also use the serial monitor to see what is going on with your program and thus be able to debug it when it's not working.
If you're OK with both those caveats then by all means go ahead and use pins 0 and 1.  You use it in exactly the same way as using SoftwareSerial but you don't need to define an object first - you just use the pre-defined Serial object.
One important thing to remember with the ESP8266 is that the default firmware's AT command interface is ropey as hell.  It's most likely that which is tripping you up not your SoftwareSerial.  You have to get the timing right with it from what I remember - always impose a 1 second delay after sending each command - it's the delay that terminates the command, not a carriage return (although I think a CR is also needed). Maybe later versions have been improved since, but that's one really good reason to directly program the ESP8266 and implement your own protocol for communicating.  My ICSC library is a good candidate for communicating between the two - it runs on both the ESP8266 and the Arduino.

I tried a simple program to send AT commands via serial which is connected to esp8266. I added an led to blink when i got the response so that i could know it is working. But the led is not blinking.

i have added it in the question.

@abdulrahuman You're program is expecting a response from the ESP module before the serial command has had a change to get there and be processed. Your whole serial reading methodology is flawed.

could you please be specific about where in the program should I change. I am beginner. A sample code could help better.

@abdulrahuman http://hacking.majenko.co.uk/reading-serial-on-the-arduino

Nice article majenko. Now I think i got what I am missing. I will try it and give you results. Thank you so much.

I tried your program. But it didn't work. It gave the same results as before

You need to use Arduino IDE serial Monitor Window for ESP8266 setup instead of using TTL or Serial Converters. I successfully Setup My ESP8266 Module by using just Arduino Nano and Arduino IDE Serial Monitor.
    #include <SoftwareSerial.h>
SoftwareSerial softSerial(3, 2); // RX, TX

void setup()
{
  uint32_t baud = 9600;
  Serial.begin(baud);
  softSerial.begin(baud);
  Serial.print("SETUP!! @");
  Serial.println(baud);
}

void loop()
{
    while(softSerial.available() > 0)
    {
      char a = softSerial.read();
      if(a == '\0')
        continue;
      if(a != '\r' && a != '\n' && (a < 32))
        continue;
      Serial.print(a);
    }

    while(Serial.available() > 0)
    {
      char a = Serial.read();
      Serial.write(a);
      softSerial.write(a);
    }
}

Necessary AT Commands


text:
Cannot read from DS3231
I'm having issues with a DS3231 RTC connected to an ESP8266. I can write to it to set the time (Wire.write returns 1), but anytime I try to read from it, Wire.requestFrom always returns 0.
I've tested my circuit with another DS3231 and it works correctly. So I guess it's faulty hardware and I can throw it to the bin. Or is there something I can do with it?
Update:
In fact, endTransmission returns 2, which if I understand well means the address is not found, so this is not a read issue. I guess that means it's dead.

Wire.write() only places data in the TX buffer. Please check the return value od Wire.endTransmission(), which is doing the actual communication. Have you checked with the I2C Scanner sketch, if the Arduino sees the DS on the Wire bus

@chrisl I hadn't thought of that, thx. See my edits.

Have you tried the I2C scanner sketch? Are you using pullup resistors on the lines?

Yes, I tried it and it finds nothing. I'm using the integrated pullups on the esp8266 (huzzah board). Also, the circuit works correctly if just drop another one in place.


text:
a mega 2650 power supply mystery
Something happened to my mega2650 as I was experimenting the other day.  It no longer turned on when powering from the 2.1mm jack or from Vin, regardless of the voltage applied.  A plastic bubble had formed on the 5V regulator, I assumed I had shorted something and fried it.  If I applied 5V to the 5V pin everything worked fine.  It also works fine when powered from USB.  So I replaced the 5V regulator with a NCP1117 version.  But I have the same situation.  If I apply voltage directly to the 5V regulator input pin I get 5V on the output pin and everything is fine.  I tested up to 12V and it is dead on at 5V.  I also checked the PNP switching transistor, and found it was working correctly.  As far as I can tell, the only thing remaining is that the trace is severed somewhere between just after the Vin pin and the 5V regulator, maybe the regulator input is not soldered well to the trace?  But this was one of the better solder joints I made, so I thought.  Any other ideas as to the root cause?
Thanks

How about D1? The M7 diode. Try testing before and after that with power applied to the power jack.

I wonder if I should do a forensic nuking of my Mega2560? Connect it to a nice meaty PSU and short the 5V, see exactly what does happen besides the Magic Smoke™ escaping from the 1117...

@NickGammon I know of one very popular board designed by an associate of mine that uses a 500mA diode on both the USB and main power inputs leading to the Vin of an 800mA 3.3V regulator.  Short out the 3.3V power and the diode feeding the power at the time literally blows itself clean off the board.

What I did was power the mega by 12v to Vin.  But, I also powered a LED constant current boost driver from the same 12v terminals.  I had the usb plugged in for programming.  When I switched off the 12v battery, then the usb was now powering the mega and the boost driver via Vin header pin instead of receiving power from it.  There was 5v reverse voltage across the 5v reg.

You obviously have some form of DMM or volt meter at your disposal, since you know the voltages around the regulator.
Some places you should, therefore, probe for voltages, and what voltages you should expect.  With the barrel jack connected and powered up, and assuming a 12V supply, you should expect:

At the rear of the socket: 12V
At the socket side of the M7 diode: 12V
At the header side of the M7 diode: 11.4V
At the right-hand (VIN) pin of the regulator: 11.4V
On the tab of the regulator: 5V

If you find any of those are wrong then the component that comes before it may well be faulty.

Ok, I checked and found these:  11.14 at battery;  11.14V at Vin header pin;  11.14V at D1 +; 11.14V at D1 - ;  0V at 5V header pin;  0V at 3.3V header pin;  0V at IC1 (5V reg) at all 3 pins; 0V at IC5B (comparator) at all 6 pins; 0V at T2 (5V switch) at a 3 pins; 0V at IC6 (3.3V regulator) at all 5 pins.  If I look close it appears the 3.3V reg also has some visible heat damage but slight.  So in this case it seems to me a power supply smoothing capacitor is at fault.

I got EagleCAD - wow that is extremely helpful.  The trace between the PC1 smoothing cap and the 5V reg. must be open because the cap terminal is at Vin, probably a bad solder job on the 5V reg.  Thanks.

Well the answer is ... I fried the rest of the board when I was trying to troubleshoot it further :(  I think 12V went to the 328p, it got hot.  Oh well, thanks everyone!


text:
Voltage sensor Calibration
We had used a voltage sensor unit to measure the voltage of the odroid board using an Arduino Uno. wWhen I uploaded the sketch and got the output, the value which was being displayed was around 4.7 to 4.9V, but when I measured the top of the voltage sensor module using a multimeter, it had a stable voltage of 5.08V. Is their any particular reason why this is happening?
Voltage sensor module
int analogInput = A0;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
int value = 0;
void setup() {
pinMode(analogInput, INPUT);
  Serial.begin(9600);
  Serial.print("DC VOLTMETER");
}
void loop() {
  // read the value at analog input
value = analogRead(analogInput);
vout = (value * 5.0) / 1024.0;
vin = vout / (R2 / (R1 + R2));
Serial.print("INPUT V= ");
Serial.println(vin, 2);
delay(500);
}

Please, post complete arduino code.

http://www.skillbank.co.uk/arduino/measure.htm

Multimeters are designed to provide a stable response. It would be averaging the readings.
As far as the difference in voltage reading, if you are using the Arduino board as is the default is to assume a reference voltage for the A/D as being 5.0 volts.(for your calculations) That may not be the case. Also there may be a tolerance issue on the measurement board, but I think the reference for the A/D on the Arduino is the bigger issue.


text:
How to put Arduino Nano in low power sleep mode (<0.05mA)
I'm trying to put an Arduino Nano in low-power mode using this guide: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery.
The article suggests 3 things: use the Low-Power library from Rocketscream, cut the power to the power LED, and remove the voltage regulator.
So far I've only done the first two and reduced the clock speed to 8 MHz.
The important part of the source code that puts the Arduino in deep sleep looks like this:
void setup() {
  CLKPR = 0x80; // (1000 0000) enable change in clock frequency
  CLKPR = 0x01; // (0000 0001) use clock division factor 2 to reduce the frequency from 16 MHz to 8
}

void loop() {
  // Go to sleep until the next scheduled wake up
  int32_t waitSeconds = 60;
  while (waitSeconds > 0) {
    period_t waitFor = SelectWaitTime(waitSeconds);
    LowPower.powerDown(waitFor, ADC_OFF, BOD_OFF);
    waitSeconds -= PeriodToSeconds(waitFor);
  }
}

period_t SelectWaitTime(int32_t secondsToWait) {
  if (secondsToWait >= 8)
    return SLEEP_8S;
  else if (secondsToWait >= 4)
    return SLEEP_4S;
  else if (secondsToWait >= 2)
    return SLEEP_2S;
  else if (secondsToWait >= 1)
    return SLEEP_1S;
}

In essence, sleep for up to 8 seconds, remove the seconds from the counter, then sleep again.
So far I've only scratched off the trace to the power LED and haven't removed the voltage regulator. According to the article above, this should reduce the power consumption to around 0.05 mA but I get around 1.7 mA, which is over 30 times more!
Electrically, I only have a MOSFET as a power switch connected to one of the analog pins (I use it as a digital output) and another controller, connected to the I2C pins (the Arduino acts as Slave). The other controller is turned off through the MOSFET when I take the measurements. Physically removing the connections doesn't change the consumption, so I don't think any of that is related.
Is there something I did wrong? What can I do to achieve power consumption similar to the one in the article?

Turns out the voltage regulator was AMS1117 - not MIC5205-KB50/KB33/KBAA like the one in the article. Ripping it off gave me the 0.026 mA idle current which is even better than what I was hoping for.


text:
LCD display interfaced with Arduino Uno not displaying values
I am a beginner on Arduino. I have a project that I will only be using: a heart rate sensor whose values I am displaying on an LCD display. The code compiles and uploads once I set my project up, but the value doesn't appear on my LCD screen.
#include<LiquidCrystal.h>
#include <TimerOne.h>

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
int HBSensor = 4;
int HBCount = 0;
int HBCheck = 0;
int TimeinSec = 0;
int HBperMin = 0;
int HBStart = 2;
int HBStartCheck = 0;

void setup() {
  lcd.begin(20, 4);
  pinMode(HBSensor, INPUT);//heartbeat sensor
  pinMode(HBStart, INPUT_PULLUP);
  Timer1.initialize(800000);
  Timer1.attachInterrupt(timerIsr);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Current HB: ");
  lcd.setCursor(0, 1);
  lcd.print("Time in Sec :");
  lcd.setCursor(0, 2);
  lcd.print("HB per Min :0.0");
}

void loop() {
  if (digitalRead(HBStart) == LOW) {
    lcd.setCursor(0, 3);
    lcd.print("HB Counting ..");
    HBStartCheck = 1;
  }
  if (HBStartCheck == 1) {
    if ((digitalRead(HBSensor) == HIGH) && (HBCheck == 0)) {
      HBCount = HBCount + 1;
      HBCheck=1;
      lcd.setCursor(14, 0);
      lcd.print(HBCount);
      lcd.print(" ");
    }
    if ((digitalRead(HBSensor) == LOW) && (HBCheck == 1)) {
      HBCheck=0;
    }
    if (TimeinSec == 10) {
      HBperMin=HBCount * 6;
      HBStartCheck=0;
      lcd.setCursor(14, 2);
      lcd.print(HBperMin);
      lcd.print(" ");
      lcd.setCursor(0, 3);
      lcd.print("Press Button again.");
      HBCount = 0;
      TimeinSec = 0;
    }
  }
}

void timerIsr() {
  if (HBStartCheck == 1) {
    TimeinSec = TimeinSec + 1;
    lcd.setCursor(14, 1);
    lcd.print(TimeinSec);
    lcd.print("");
  }
}

Please don't use capslock. Thats the equivalent of shouting at us and makes the text difficult to read.

Is this still only in the proteus simulation, or do you now use real hardware? And have you tried following the advice from the comments of your other question? Like declaring variables, that are used inside an ISR, as volatile?

No i only using proteus simulation, this code is for hardware i tried the use it in proteus , ( Like declaring variables, that are used inside an ISR, as volatile? ) No sir i am a very beginner can you show me how please??and thank you

You're doing too much inside the ISR so it takes too much time. Also, the HBStartCheck and TimeinSec variables are changed inside the ISR but not declared volatile so the rest of your code might not see any changes to these variables. change the int HBStartCheck = 0; and int TimeinSec = 0 at the start of your code into volatile int HBStartCheck; and volatile int TimeinSec;. Also move the lcd.setCursor() and lcd.print() out of the ISR and do this inside of loop ().

i remove  TimeinSec=TimeinSec+1;     lcd.setCursor(14,1);     lcd.print(TimeinSec);     lcd.print(""); in the loop and add volatile in TimeinSec = 0 and HBStartCheck = 0 but still doesn't work

does the oscilloscope show a signal on channel B?

Did you configure the sensor with a heartbeat signal (from a hex file)? I ask because in the first question, you provide osci printouts and they were flat. So your sensor has no output.

I think that you may be not paying attention to details ... in your previous question, you connected a battery backward ... in this question, you connected to one pin and configured the sketch for another pin


text:
WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized'
I'm using Ubuntu 14.04 with arduino Galileo and the newest arduino IDE from arduino.cc and every time I compile I got this warnings with any library in place of EEPROM, SD, Wire, Wifi and a lot of others.
When I check the boards manager I got the following:
Invalid library found in /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire: /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire
Anyone knows how to solve this?

As sated above you need to "Edit or add library.properties to that folder so that you specify a valid category."
This link has some good info on the structure of the file: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification
From that link:
library.properties file format
The library.properties file is a key=value properties list. Every field in this file is UTF-8 encoded. The available fields are:
**name** - the name of the library
version - version of the library. Version should be semver compliant. 1.2.0 is correct; 1.2 is accepted; r5, 003, 1.1c are invalid
**author** - name/nickname of the authors and their email addresses (not mandatory) separated by comma ","
**maintainer** - name and email of the maintainer
**sentence** - a sentence explaining the purpose of the library
**paragraph** - a longer description of the library. The value of sentence always will be prepended, so you should start by writing the second sentence here
**category** - if present, one of these: "Display", "Communication", "Signal Input/Output", "Sensors", "Device Control", "Timing", "Data Storage", "Data Processing", "Other"
**url** - the URL of the library project, for a person to visit. Can be a github or similar page as well
architectures - a comma separated list of architectures supported by the library. If the library doesn’t contain architecture specific code use “*” to match all architectures
**dot_a_linkage** - (available from IDE 1.6.0 / arduino-builder 1.0.0-beta13) when set to true, the library will be compiled using a .a (archive) file. First, all source files are compiled into .o files as normal. Then instead of including all .o files in the linker command directly, all .o files are saved into a .a file, which is then included in the linker command.
**includes** - (available from IDE 1.6.10) a comma separated list of files to be added to the sketch as #include <...> lines. This property is used with the "Include library" command in the IDE. If the property is undefined all the headers files (.h) on the root source folder are included.

If you get this error for the FlexIO library installed with Teensyduino, this is because the author has entered a category "Utility" which is not accepted. I changed the category to "Timing" and the error is gone.

Edit or add library.properties to that folder so that you specify a valid category.
Example of library.properties:
name=WebServer
version=1.0
author=Cristian Maglie <c.maglie@example.com>, Pippo Pluto <pippo@example.com>
maintainer=Cristian Maglie <c.maglie@example.com>
sentence=A library that makes coding a Webserver a breeze.
paragraph=Supports HTTP1.1 and you can do GET and POST.
category=Communication
url=http://example.com/
architectures=avr

From: https://www.bountysource.com/issues/29336127-one-wire-library-still-in-v2-3-0-causes-useless-warning

The Arduino library manager still defaults to v2.3.0, which causes the
  IDE to raise the following warning on compile :
WARNING: Category '' in library OneWire is not valid. Setting to
  'Uncategorized'

Solution (In 1.6.12):

Sketch -> Include Library -> Manage Libraries
In the upper-right "Filter Your Search" box enter (without the quotes): "OneWire"
Click the "OneWire by Jim Studt, Tom P..."
Select version 2.3.1 (or newer)
Click "Install"

authors: שם טוב בן גיאת


text:
Problem Uploading to arduino uno board
I have an arduino uno. Whenever I try to upload code to the arduino I get this error.
avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL01EI7I": Device not configured

ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

What OS are you on? Do you have the necessary drivers installed?

The error message is telling you that avrdude failed to open the device and read the modem status (basically the information about whether a device is present and ready on a serial line). The most likely causes of this are:

Using the wrong serial port (Tools > Port in the Arduino IDE).
The IDE not recognizing the board.
Using a power only USB cable.

The Arduino IDE seems to remember the device that your board was last connected through, but on some Unix flavored OSes the device name depends, in part, on method of connection – which port, hub or no hub, etc. So if you change the board or the port you plug it into, the name changes.
So, the very first thing to do is to look under  Tools > Port in the Arduino IDE to see if there is another device present. Also confirm that you're using a USB cable with data wires. There are "power only" USB cables…
Failing that, check to see if the OS sees the board. On OS X you would go to the Apple menu and choose About this Mac and then look at at the System Report to see what devices have been detected on your USB busses. I'd be surprised if there wasn't something similar on Linux (and Windows too for that matter). If you're comfortable on the command line you could look in /dev for devices with similar names.
If the board is present, but not seen by the Arduino IDE, try restarting the IDE and/or plugging and unplugging the USB cable. Sometimes it helps to plug the cable into a different port.