text:
5V 10A 4 channel relay to 2 lights15W light in series in 220V AC supply
I am trying to setup my first relay module with live environment. I have attached the relay module image below.

Which I am using to control 4 devices in my switch board as follows:

Fan (working fine),
6w celling LED panel (2 connected in series) (Working fine)
15w celling LED panel (2 connected in series) (Sometimes work sometimes don't)
Spotlights 3 lights in series and some LED strips connected to it (Sometimes works sometimes don't.).

I have cut one wire which is connected to main normal mechanical switch WHICH IS NOT A HOT WIRE its just the another wire connected to the button.
But I am not sure why its not working? Do I need to connect neutral to the another end of the relay. As I have only 2 wires connected to the relay for each of the switches. Here is a screenshot of specifications 15watt LED panel which is connected to my house, if this can help to understand better.

If I connect Neutral on the first pin of relay and when I close the relay switch, do the current will go into the neutral wire as well?
If I keep my 3w spotlights ON or more then 3-4 hours and try to close the relay on connected to it. The relay LED light for that connected relay goes OFF but the light don't. Seems like the mechanical relay is not getting enough power to move the mechanical relay off.
I want to know why this is happening? And how can I solve this issue? Attaching a neutral (earth) wire will help to reduce this? But if connect neutral to first (off side of relay) pin, then will get the current?
Any suggestions will be helpful. Also I added 3.3v from NodeMCU to VCC (instead of jumper) pin. But that is also not helpful.

NodeMCU don't have 5V pin. I have only 3.3v pins. do I have to connect to any buck converter? @Juraj

How are you powering the nodemcu? The relay needs 5V minimum (72mA current per relay, by the way, so that's 288mA you'll need just for the relays) I mean, the clue is in the name ... they are 5V relays

@JaromandaX I am powering it with mobile charge which is 5v

But as much as I understand nodemcu step down the voltage to each upto esp8266 as esp8266 need 3v.

the Vin pin will be 5V

This "question" is vague and confused - I would STRONGLY ADVISE that you you do not attempt to connect to mains power - there is a danger of electrocution. No electrician would even consider connecting neutral to a relay (or any kind of switch).

2 connected in series; I hope you mean parallel here. You can't really put mains devices in series.

so my revised comment based on schematics in MatsK's answer. remove the VCC/JD-VCC jumper and wire JD-VCC to 5 V (Vin) pin of NodeMcu. it will power the coils with 5 V from USB and work with 3.3 V io pin wired to InX

@Gerben yes the two lights turn ON and OFF together.

@Milliways yes I thought so too. As I am not from electronics background. So I am not much aware to these things. Thats why I am not taking any risk and asking for help here. :)

@JaromandaX I thought VIN pin is used for voltage input, not for output. I may be wrong. I will clarify it once again to brush up the basic concepts.

about Vin on NodeMcu https://arduino.stackexchange.com/questions/51873/nodemcu-vin-pin-as-5v-output

@Juraj Amazing help! It helped to understand the basic concept.

You need to connect Vin from NodeMCU (Raw 5V from USB) to Vcc on the relay board.
And as stated in the comments, the relay need 5V for operating reliable.
In has the same problem, two LEDs and a resistor. To enhance it would be to replace the indicator LED (DS1-4) with a wire.
2 x LEDS á ~1.8V and a resistor á ~1.4V = 5 Volt.
1 x LED á ~1.8V and a resistor á ~1.4V = 3.2 Volt.

but if the JD-VCC is not connected with VCC and JD-VCC is 5 V and VCC is 3.3 V then it will work wit 3.3 V io pin without modification? I am a programmer and not good in electronics, but it is how I read this circuit.

One of the purpose with JD-VCC is to be able to have a optical isolation between "In" and the relay circuit and another is that you can have one PSU that feed the relays.

So do you think any step up (3.3v to 5v) buck converter can solve the problem?

Yes as long as it can supply ~300mA . The relay spec say that a 5V relay consume ~70mA . Ref datasheet https://www.mycomkits.com/reference/Songle_SRD(T73)_Relay.pdf

@user3201500, you can take 5 V from Vin https://arduino.stackexchange.com/questions/51873/nodemcu-vin-pin-as-5v-output

@MatsK I hope this will help me. I am not trying this right away. As I have to open my switch board screws. But I am sure this will be a great help. And most probably this will solve the problem too.

@MatsK, why do you recommend to remove the indicator LED?

If you remove or shorten the LED then you can drive the in with a 1.8 volt lower voltage, 5V - 1.8 volt = 3.2 volt.

but if VCC is 3.3 V and signal level is 3.3 V it would work as it is?

Please read the answer.

again. with this relay board the coils can get 5 V over JD-VCC. now we talk about the left part of the schema. if VCC is 3.3 V and logic level HIGH of In is 3.3 V. will it acrivate the optocoupler as it is? I think yes and there is no need to bridge the indicator LED


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.

source: Stack Exchange

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

sort: votes


text:
Question on how "f" value is calculated in converting Morse Code to laser audio from this tutorial
I am working on this tutorial,
https://www.hackster.io/SURYATEJA/morse-code-communication-using-laser-module-both-ea1b01
and the author created a "Send" and "Receive" code for encoding and decoding Morse code. He created the "Send" code with the entire alphabet A-Z, but his receive code only has 9 letters.
I thought I could easily add in the missing characters, and even add in numbers, but I am stuck.
His code has 2 values to decode the morse - "a" and "f"
In his receive code he has a value "f" that is supposed to be calculated by the number of spaces, but I cannot see how he comes up with his result.
For example, this is his sending code for "a"
    case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;

Then this is the receive code;
if(a==4 && f==10) {   Serial.print("a");

I understand the value of 4 for "a", but I cannot understand the value of 10 for "f"
"a" is calculated by assigning a value of 1 for a dot and 3 for a dash and adding the values (in this case one dot and one dash, 1+3 = 4)
He explains how to calculate "f" here in his tutorial, but I still don't understand.

When the LASER falls on the LDR, the value goes beyond 1000, and then it will enter into a loop.
Now quantize the values i.e. if the value goes beyond 1000, then assign it as '1', otherwise assign it as '0'.
Inside a loop, calculate the number of '1's and '0's. Set the counters 'a' and 'f'. Count the number of '1's and store it in 'a' and similarly count the number of '0's and store it in 'f' respectively.
Now check the specific values of 'a' and 'f' respectively. Each character will have different set of 'a' and 'f'. The matching value will be displayed.

That seems to indicate;
Laser on = Over 1000 = 1
Laser off = Under 1000 = 0
So for the letter a, I only see 2 times the laser goes off, not 10.Minof formatting changes

the person that wrote the code did not bother to make the code easily readable by indenting code blocks correctly .... for instance the case 'a':  block that you included in your question .... the case 'a': should  not be indented and the next four lines should be indented ..... all the other case statement blocks should be formatted the same way ...................... the LightsOff(elemPause); should not be called inside the case blocks .... it should be called at the end of MorseDot() and MorseDash() functions ..... that would reduce the length of the program significantly

This is not a good tutorial. The receiver works by assuming 14 dotLen time periods for each character. There is a loop that runs 14 times, with a 200ms delay between each iteration. If the laser is detected, then a is incremented, otherwise f is incremented. This means that the sum of a and f is always 14, and the case where a==0 means nothing was transmitted. The incomplete receiver code shows only 10 options for received characters and leaves out a==5 (which would be R or U), but does define 1 through 10 otherwise.
The receiver code does not differentiate between dots and dashes, it only counts the number of dotLen transitions where light is detected. This is not Morse Code.
The receiver code cannot distinguish between S (dot-dot-dot) and T (dash) because they both have 3 dotLen value. Same for A (dot-dash) vs. N (dash-dot).
If you want to understand decoding morse code, this is not a good tutorial to follow. It does not decode morse code, and I cannot see how it would work even with it's companion transmitter program.

Thanks very much! So assuming I understand it is fake Morse code, and I'm more interested in sending and receiving text data via the laser, would I be able to create a full alpha-numeric set of characters by some method (maybe increasing the amount of dotLen time periods)?

No. I would suggest to abandon this base code for any project. Find something else that already works and learn from that. Do not try to learn from a broken project. It won’t even work on its own.

I agree, Morse code has variable length characters and no carrier detect which makes it challenging to decode.  (Is it "on" or was that noise?  Is it "off" or did I just lose signal?)  I agree with jose, go with a machine-oriented code (such as Baudot or ASCII) and decode that instead.

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


text:
Serial.write printing blank values
I've got an Adafruit Bluefruit NRF52 hooked up to the Adafruit BNO055 9-axis orientation sensor, but when I use Serial.write to send the data, serial monitor displays blank values only. The scroll bar drops so something I definitely appearing, it just seems to be empty.
Serial.print works fine, but I cannot use this for my application, as it uses too much memory.
I'm gathering 3 axis of absolute orientation plus 3 axis of acceleration (6 floats in total) plus a three digit number representing the calibration of each sensor.
Each line should look something like
303 68.69   4.19    -2.19   -0.12   0.14    -0.40

My code:
void displayCalStatus(void)
{

  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;
  bno.getCalibration(&system, &gyro, &accel, &mag);

  /* Display the individual values */
  Serial.write(gyro);
  Serial.write(accel);
  Serial.write(mag);
  Serial.write("\t");
}

void loop()
{
  imu::Vector<3> accel = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);

  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  displayCalStatus();

  /* Display the floating point data */
  Serial.write(event.orientation.x);
  Serial.write("\t");
  Serial.write(event.orientation.y);
  Serial.write("\t");
  Serial.write(event.orientation.z);
  Serial.write("\t");

    /* Display the floating point data for Linear Acceleration */
  Serial.write(accel.x());
  Serial.write("\t");
  Serial.write(accel.y());
  Serial.write("\t");
  Serial.write(accel.z());
  Serial.write("\n");
}

write transfers a byte, you want print text. replace all write with print

As mentioned, I cannot use print because it uses too much memory. I'm using Serial for debug but am sending over bleuart in prototype. I'm recording high speed, high fidelity movement and so I need the ble connection interval down to 20ms minimum, which means getting the transfer size down. Do you know if there are workable alternatives to print?

This is not good coding: system = gyro = accel = mag = 0; Instead, explicitly set each one to zero.

but you want see the number as text or not? if you write(5) you send a  nonprintable byte. if you print(5) it will print "5". imu::Vector takes much more space then C array

system = gyro = accel = mag = 0; is from the example provided by Adafruit, not my own. Either way that doesn't solve the problem of printing blank values.

I don't need text, just the float, but whole number would do

you print tabs and new line. that is text. if you want to see a number in Serial Monitor you must print it as text with print

Ok thanks for the clarification. Since I will be sending over bleuart ultimately, do you know if there is an alternative for me to send the values alone, without tabs and new line text?

The float values you want to send are 4-bytes long. Serial.write sends 1 byte. To send the raw value, you must send each byte individually, usually by bit-shifting. You would probably do well to send some kind of "end of packet" value to indicate to the receiver that you have now sent all values (in case one gets lost or skipped, the receiver can reset to expect the first value, etc.)

even then you need delimiters, but then you don't know what is a value and what a delimiter so you need a delimiter byte and escaping of the delimiter byte by repeating it twice in data

If all values are 4 byte and the number of values sent each round is the same, there is no need for delimiters, though it could improve robustness.

I see. I am unsure how to do this. Are you able to provide an example which I may be able to use?

Problem 1:
You wish to send/display on the Serial Monitor the int and float values generated by your sensor, but Serial.print() uses too much memory.
Solution 1:
Optimize your sketch to use less memory.

Problem 2:
Serial.write() doesn't cause the values to show up on Serial Monitor, but something is getting sent, because I see scrolling activity.
Solution 2:
Serial.write() sends raw bytes, whereas Serial.print() converts a variable to a string (or series of ASCII bytes) and sends that string. For example, Serial.write(65) sends A to the Serial Monitor because the ASCII value of A is 65; Serial.print(65) sends 65 to the Serial Monitor because it converts the numeric value 65 into a string containing the character 6 and the character 5, and sends that string to Serial Monitor.
The Serial Monitor expects only ASCII data. You are using Serial Monitor for development/debugging, but your final application does not require ASCII, only to transmit the numbers.
Serial.write() comes in a few forms. One is Serial.write(val) which sends a single byte (named val, of type byte or compatible). Another is Serial.write(buf, len) which sends a series of len bytes, starting at the address of memory pointed by by buf. (This is often when buf is an array of bytes, so buf points to the first element of the array.)
If you wanted to send the 4 bytes of a float using Serial.write(), you could call:
Serial.write(&(event.orientation.x), sizeof(event.orientation.x);

As an alternative, you can use bit shifting to send one byte at a time of the 4-byte float:
Serial.write((byte)((event.orientation.x & 0xFF000000) >> 24);
Serial.write((byte)((event.orientation.x & 0x00FF0000) >> 16);
Serial.write((byte)((event.orientation.x & 0x0000FF00) >>  8);
Serial.write((byte)((event.orientation.x & 0x000000FF)      );

On the receiving end, you need to reconstruct your float by doing the reverse.
But you have multiple 4-byte values to send, in rapid repeating loop, so what happens if your receiver and transmitter get out of sync? Then you might want to put in a "flag" value to indicate the start of a sequence of data and a different flag for the stop of a sequence of data. What happens if your start or stop "flag" value actually shows up as one of the bytes you send as part of a real data byte? Then you need to find some way to modify the "real" data so that it's not to be construed as a flag.
This looks to be getting complicated now? Fortunately, these problems have existed and been solved for decades. Unfortunately, there is no consensus on the best or right way.
I did a quick search and found this arduino library that facilitates packet-based serial communication:
https://github.com/bakercp/PacketSerial
Perhaps that can help you take a bundle of numbers and send them reliably to some other system. I don't know that library in particular, and there are probably others that do something similar. This one claims to be compatible with the PySerial, COBS, and SLIP modules for dealing with packetized serial data communications.


text:
Uploading my code gets an error : permission denied on Ubuntu 16.04
I have faced this problem for few years ago and I solved it on Ubuntu 14.04 but I don't know why my solution doesn't work right now on Ubuntu 16.04
The Error :

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

I'm using the same solution from The guide
Here what I've done :

ls -l /dev/ttyACM*
   from the result : The owner is "root" and the group with access is " dialout
  Then I applied

  sudo usermod -a -G dialout UserName
  sudo chmod a+rw /dev/ttyACM0  Finally logged out and logged in .

After all should be worked but  I still have the same Error , it doesn't work at all , I removed the software and re-installed it didn't work as well

sudo apt-get remove modemmanager

Are you sure with ttyACM0? My Arduinos always show up as ttyUSB0

@chrisl Yes I'm sure . Any help ?

@Majenko still ! , didn't solve it

@chrisl Real Arduinos with an ATMega for the USB use CDC/ACM, so appear as ttyACMx. Clones that use other chips, or ancient Arduinos with an FT232 appear as ttyUSBx.

Did you install the snap app of the Arduino IDE? This is known to not work properly in many cases.

@oh.dae.su No I have never installed it !

Re-check the permissions on the device node now you have logged out etc. Some useful commands: stat /dev/ttyACM0 - check the first "Access:" line.  sudo fuser /dev/ttyACM0 - list processes that are using the device node.

@Majenko When I try to see " sudo fuser ... " that shows " Specified filename /dev/ttyACM0 does not exist. " What does it mean ?

Is the board plugged in at the time you run the command?

@Majenko Yes it is, I unplugged it and plugged back again to try then run the command but the command show nothing actually just press Enter then I got nothing " no result " , and the error still on Arduino software

If it returns nothing then nothing is locking the device. That's good. How about the first Access: line from the stat command?

@Majenko That return " (0660/crw-rw----)  Uid: ( 1001/     moh)   Gid: ( 1001/     moh) "
Note : moh is the user , and it's already member of dialout "the group with access" , what do you think ?

How about if you type echo foo > /dev/ttyACM0 - does that return anything?

Finally ! I got it , it works now ! Thank you so much , appreciate your help

What did you do to make it work?


text:
Deep Sleep NodeMCU with Door Sensor
I have a very simple code of door sensor (magnetic) which gives results in 1 & 0 format. But I want to run the NodeMCU only when a door is open or close. Rest of time I want to keep it in deep sleep mode. Here is my code looks like :
int doorClosed = 1;

#define REED_SWITCH D5

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

  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  pinMode(REED_SWITCH, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly

   Serial.println(digitalRead(REED_SWITCH));

    if ((digitalRead(REED_SWITCH) == HIGH) && (doorClosed == 1))
    {
      Serial.println("DOOR OPEN!!");
      doorClosed = 0;
      digitalWrite(BUILTIN_LED, LOW);
      ESP.deepSleep(0);
    }
    else if ((digitalRead(REED_SWITCH) == LOW) && (doorClosed == 0))
    {
      Serial.println("DOOR CLOSED!!");
      doorClosed = 1;
      digitalWrite(BUILTIN_LED, HIGH);
      ESP.deepSleep(0);
    }
    delay(500);
}

Here I am able to put the NodeMCU in deep sleep. But it never wakes up. How can I wake up my chip. After attaching the D0 with RST, I don't event get Serial Logs. I am not sure what kind of behaviour is this. If someone can help me to fix this code will be great!
Thank you!

According to this guide (https://randomnerdtutorials.com/esp8266-deep-sleep-with-arduino-ide/) the pin to be connected to RST is D0 and not A0.

I am sorry it was a typo mistake. I just fixed it.

After going in sleep mode, check D0 voltage value with a multimeter. Should be approximately to 0V.

If D0 is not 0V, connect RST to GND and check if microcontroller wakes up.

I just check the D0 voltage, but seems like its not going to 0V its showing me 3.25V. Which means its not going to deep sleep?
in multimeter I am touching D0 and GND pin to check the voltage.

Before investigating why D0 is high, try to connect GND to RST pin e check if arduino wakes up. ESP8266 documentation says that is sufficient a low value on RST pin to wakes up.

@leoc7 yes it was waking it up. But i am not able to see any details in serial monitor, so not sure how can i do that.

You can’t see any details on serial monitor because esp8266 restarts program and you have to re-open serial monitor. Use a led instead print on serial.

According to this guide:

The RST pin of the ESP8266 is always HIGH while the ESP8266 is
  running. However, when the RST pin receives a LOW signal, it restarts
  the microcontroller.
If you set a Deep Sleep timer with the ESP8266, once the timer ends,
  GPIO 16 sends a LOW signal. That means that GPIO 16 when connected to
  RST pin can wake up the ESP8266 every time the timer ends.

The only way to wakes up ESP8266 from deep sleep mode without timer is set a LOW signal on RST pin.
Example without timer:
ESP.deepSleep(0);

Connect D0 (GPIO 16) to RST is available only when ESP8266 is in sleep mode with timer.
Example with 30sec timer:
ESP.deepSleep(30e6);

In your case, you can use deep sleep with timer and connect Door sensor to D0 and will act as switch between the RST and D0.

can i do that programmatically?

also if its in deep sleep mode. Then how can i send a signal to it? i am using door sensor, will it be able to read its value in deep sleep?

You can’t do it programmatically! During deep sleep esp8266 is switched off and can’t do any operation. An approach can be to set a deep sleep mode with timer (e.g. 30sec) and connect D0 to RST. Every 30sec esp8266 wakes up, restart program and check door sensor.

interrupt will also not work in this case?

No, if you use Deep Sleep, ESP8266 is off and the only way to wake up it is trigger physically RST pin. Consider to use other type of sleep mode (for example light-sleep)
Take a look to this guide: https://www.losant.com/blog/making-the-esp8266-low-powered-with-deep-sleep

OK if I use door sensor then? Because door sensor can work externally on door open and close. As I want to connect with door sensor.

I got it working! Door sensor can be connected to D0 and will act as switch between the RST and D0. With this try. I am able to get it fixed. If you want you can post it under answer I will mark it right. :)

I modified the answer :) If you want you can mark as resolved.

i got it resolved upto a certain limit. The thing is i am able to restart it by setting the value high, but on closing door i don't get it restarted, so there is some challenge now

My response is late but herewith my experience that may be of help to others.
NodeMcu in deep sleep will wake-up from external source on receiving a pulse from high to low on the RST pin.
An ADXL345 accelerometer raises an interrupt HIGH on sensing motion and remains high until (I2C) READ to prevent multiple devices from interfering with each other
The following post was instrumental in my finding a solution
https://electronics.stackexchange.com/questions/158015/how-to-turn-continuous-signal-into-a-short-pulse-using-logic-gates


text:
Lines not pulsed fast enough (?))
Should this code pulse the PB3 and PB4 pins (MOSI and MISO of an Arduino Uno) at 2ms interval ?
#include <avr/io.h>

int main(void)
{

//  for (byte i = 0; i < 32; i++)
//    pinMode(i, INPUT);

  DDRB |= (1 << PB4);
  DDRB |= (1 << PB3);
//  pinMode(PB4, OUTPUT);
  while (1)
  {
    PORTB &= ~(1 << PB4);
    PORTB &= ~(1 << PB3);
  //  digitalWrite(PB4, LOW);
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//    delayMicroseconds(10000);
    delay(1);
    PORTB |= (1 << PB4);
    PORTB |= (1 << PB3);
  //  digitalWrite(PB4, LOW);
//    delayMicroseconds(10000);
    delay(1);

  }
}

If used for SPI MOSI can do 1 MHz just fine - so my logic analyzer says. MISO would not behave when used by SPI. MISO works in other non-SPI scenario: I am able to use the Arduino for in-system programming other AVR boards.
But the code above pulses neither MISO nor MOSI, as pointed out by the same logic analyzer in the same setup. Should it?
update
There has been some issue with the board. Changed it and all works fine now, regardless of using int main() alone or also calling init() as per @Majenko 's answer

Code is looking ok. Are you sure that ports are not shorted by something, or driven from somewhere outside?

@smajli that was probably it. Feel free to turn the comment into an answer

The code content works fine while compiled as an Arduino program - that is, using the proper setup() and loop() structure:
void setup() {
    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
}

void loop() {
}

However the same code will not work when using it in main(). This is simply because delay() will never work. Normally main() calls init() which then configures TIMER0 to generate the millis() and micros() count used for the delay() functions.
So either use setup() and loop() instead of main(), or make your program call init() before anything else:
int main() {

    init();

    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
    return 0;
}

Makes sense. But, it didn't make a difference. Tried both calling init() and switching to setup().  As a sidenote, when I go lower with the delays, into tens / hundreds of microseconds, glithces start showing up on the MISO line. Going for even lower delays causes some (fewer) gltiches to also show up on MOSI .

Then your board is probably broken, or something, because that code does work. I tested it. It worked.

Yes... something like that. I wonder why the lines are doing fine when used as ISP at 19200 baudrate but not when pulsed at similar rates by hand. I am off to more investigations.


text:
Serial.read() keeps returning the same value over and over
This code keeps on returning 'S' with the Serial.read().
#include <Servo.h>
#define trig 10
#define echo 9
int pinMotorRN=3;
int pinMotorRP=4;
int pinMotorLN=5;
int pinMotorLP=6;
long distance;
long duration;
Servo myservo;
void setup() {
  pinMode(pinMotorRP, OUTPUT);
  pinMode(pinMotorRN, OUTPUT);
  pinMode(pinMotorLP, OUTPUT);
  pinMode(pinMotorLN, OUTPUT);
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  myservo.attach(8);
}
void loop() {
  Lid();
  while(Serial.available() == 0);
  char val = Serial.read() ;//reads the signal
  delay(1);
  Serial.println(val);
  if(val == 'F'){
    Forward();
  }
  else if(val == 'B'){
    Backward();
  }
  else if(val == 'R'){
    Left();
  }
  else if(val == 'L'){
     Right();
  }
  else
    Stop();
}
void Stop()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, HIGH);
}
void Backward()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Right()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Left()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Forward()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Lid(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration*0.034/2;
  distance = 11;
  if(distance <= 10){
    myservo.write(180);
    delay(2000);
  }
  else
    myservo.write(0);
}

Note that the app im using is Arduino RC bluetooth car controller

Does it print 'S' over and over or keep executing the stop sequence? Because your terminal is probably sending "<some_letter>", so you'd see stop (the default) get executed 1 or 2 times per keystroke (depending on whether the terminal ends a line with , ,  or both), plus one more if you actually typed an 'S'. In any case, this code shouldn't be delivering a long stream of anything when you aren't typing.

If you are trying to read a character on the serial port shouldn’t “while(Serial.available() == 0);” be “while(Serial.available() > 0);

@MrFixIt87: The semicolon following the while-expression is an empty statement. So the whole loop translates to: "While there are zero characters in the serial buffer, do nothing".


text:
Assign and control Digital pin from String
Here is modified version of Blink example
#define D8  13

String p = "D8";

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(D8, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  byte pin[2];
  p.getBytes(pin, sizeof(pin));

  digitalWrite(D8, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(D8, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

D8 defined above is a byte of length 2. So LED turns on/off if I mention D8 on digitalWrite(D8, HIGH). Similarly I am getting the same byte D8 from String p = "D8", and converting it into byte of length 2, but assigning pin to digitalWrite(pin, HIGH/LOW) doesn't works. Has anyone tried something similar before ? any help would be appreciated :)

digitalWrite(pin, value) is expecting an unsigned 8 bit integer for the pin parameter ......... it is actually unclear what you are trying to do ....... also,  doesn't works does not describe what actually happens .... if you got an error, then why did you not say anything about it?

C and C++ programs get compiled in multiple passes through various programs/steps. One of the first is the C Preprocessor, which handles the #define preprocessor directive.
It's basically a big find/replace function. After the preprocessor is done, anywhere you had D8 outside of a string literal, would have the value 13. It's not a variable or a string -- it's simply the number 13.
But the String p, which has content "D8" doesn't get replaced by the #define directive because it's part of a string, and the preprocessor doesn't modify strings in that way.
Also, p converted to a byte array of length 2 does not have anything like 13 as the value. It has 0x44 and 0x38 (or, in decimal, 68 (ASCII 'D') and 56 (ASCII '8')). Disregarding that digitalWrite() and pinMode() do not accept byte arrays, only bytes, you are passing in a byte that doesn't represent pin 13.
If you want to assign the pin via a string, then you would need to use programming to examine the string and pick the right byte value, and each possible value would have to be explicitly enumerated and checked for.


text:
ESP12F module not working as an access point
I have an ESP12F WiFi module and I need it to work in access point mode. I burned the example code to it using Arduino IDE and it worked at first. I could connect to the WiFi provided by it using my laptop. But when I removed it from power and connected it again it was not working. I couldn't even see its hotspot in my laptop WiFi. What happened to it? Can you please help trouble shoot it?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#ifndef APSSID
#define APSSID "ESPap"
#define APPSK  "thereisnospoon"
#endif
const char *ssid = "ESPap";
const char *password = "thereisnospoon";

ESP8266WebServer server(80);

void handleRoot() {
server.send(200, "text/html", "
You are connected
");
}

void setup() {
delay(1000);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");

WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
}

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

it broke and you've got all the pieces ... try adding some debugging Serial.print statements in your code ... see if/where it breaks

Post your code.

i tried. I got connected to it and again I lost connection. this happened two or three times. its getting connected, then it loses connection and again it gets connected.

wrong RF parameters. let it on so it can calibrate. if it doesn't help, clear the flash with esptool and then upload some simple STA sketch and let it for some minutes to calibrate RF

Can you please explain what are RF parameters?

RF - radio frequency


text:
How do you remove dependencies from a library?
I'm writing a library for a project i created, but it depends on the Neopixel library from adafruit. I want to remove this dependency and have my library be a stand-alone library.
Is there a way to run a ws2811 chip without the neopixel or similar library?

Yes. Copy the code from the Neopixel library into yours.

Why is it important to remove the dependency? Of course there is a way to run the WS2811 chip, but you would have to implement the documented protocol yourself, which has already been done several times by several library authors.

I understand. but i want to just run the chip - its not running rgb leds.

The Adafruit Neopixel library is licensed under GPL v3. You can fork a copy of this library into your own code and modify it to suit your own requirements, but if you distribute your code, your compiled project, or a product containing the library or any portion of it, you must ensure you follow the rules of the license by which the library is governed. Those terms of license may include release of the source code if you use any portion of the licensed library in a product. Opinions differ on the exact meaning of GPL v3 with libraries.
You should be able to copy the library into your own codebase and strip out the color-specific routines, put in your own application-specific data-setting routines, but use the same underlying protocol implementation.


text:
Did not find fingerprint sensor :( Arduino Mega 2560 Adafruit Fingerprint Sensor
I'm getting the following error when I try to enroll fingerprints using the Arduino Mega 2560 microcontroller along with a Fingerprint Scanner:

Did not find fingerprint sensor :(

The exact devices I'm using are as shown in the links below:
https://www.gearbest.com/development-boards/pp_70487.html?lkid=11637831
https://www.gearbest.com/boards-shields/pp_009769796663.html?wid=1433363
My circuit connection is:

(Green) TX    =>  Pin 0 [PWM]
(White) RX    =>  Pin 1 [PWM]

//It doesn't respond when connected to 5V, it only heats up

(Red) VCC     =>  3.3v
(Black) GND   =>  GND

The connection is illustrated below:

The code is shown below:
#include <Adafruit_Fingerprint.h>

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
 #define mySerial Serial1

// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// comment these two lines if using hardware serial
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(10, 11);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

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

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

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()                     // run over and over again
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
  id = readnumber();
  if (id == 0) {// ID #0 not allowed, try again!
     return;
  }
  Serial.print("Enrolling ID #");
  Serial.println(id);

  while (!  getFingerprintEnroll() );
}

uint8_t getFingerprintEnroll() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

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

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

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

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

I used the Adafruit Fingerprint library found here:
https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library
I also soldered the wires from the sensor onto Male Pin Headers for greater connection stability.
All I get is the fingerprint sensor blinking continuously which makes me think it's not faulty but when I try to run the enroll code I get the error message highlighted above.
I also tried connecting using the Software Serial approach like below but that wasn't the solution either:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

What could be the problem? Is my connection and code okay? Anyone have an idea on how to fix this?
The heat occurs on the encircled area below:

Before anything, watch this video https://www.youtube.com/watch?v=nxjLx5RdaSQ&t=183s . I  would say it's damaged goods if it heats up when connected to 5v. That sensor board is supposed to be able to run off that voltage, per the specs listed and educ8ts great video. It's also from gearbest, and gearbest does not have the best track record. Can you pinpoint where the heat is coming from? You may be able to swap a damaged component (if you're lucky).

It just so happens I had watched it :-) Thanks. I have edited my question to show where the overheating is occurring. Do you know which part is causing this from the snapshot? Or am I overreacting, maybe these heat levels are normal?!

Could it be the male jumper wires that connect the breadboard to the micro-controller? Because those dance around a bit as you handle the device. There should be a way to secure those, no?

Mega has 4 hardware Serials. why do you use the first which is used by USB or why SoftwareSerial? and why a breadboard in the middle?

@Juraj Now that I've established my sensor is in working order and have used it with both SFG Demo and Arduino IDE, I'll try out the hardware serials some more. I had tried them unsuccessfully before if you check out my question above where I used PINs 0 and 1 which work with SFG Demo but not Arduino IDE. I suspect the issue might be with the Adafruit Library since when you attempt to upload the edited code to work with the Hardware Serials, the upload is unsuccessful, unless I'm using the wrong PINs altogether. Suggestions? Either way I'll post my findings here in a couple of days.

Serial on pins 0, 1 is used by USB. use Serial1 on pin 18 and 19

Thanks! I'll try this out first. I've confirmed that's the case here: https://www.arduino.cc/reference/en/language/functions/communication/serial/ There's a lot to these tiny computers.

@Juraj Tested and working. I've updated my answer accordingly. Thanks for your input! Regarding my use of the breadboard, I soldered my fingerprint scanner wiring onto 4 joined male pin-headers so that's why I need the breadboard for now albeit as a temporary solution as I prototype my design.

Thanks for your responses @HavocRC and @Juraj
I've successfully come to the following working parameters that I have tested and have given positive results:

When using Arduino Mega 2560 with the SFG Demo, we use:
(Green) TX    =>  Pin 1
(White) RX    =>  Pin 0
(Red) VCC     =>  5V
(Black) GND   =>  GND
When using Arduino Mega 2560 with the Adafruit Library, we use:
Using Hardware Serial Port (Serial1) [Recommended]
(Green) TX    =>  Pin 19
(White) RX    =>  Pin 18
(Red) VCC     =>  5V
(Black) GND   =>  GND
//Note that you'll comment out the Software Serial initialization
//as directed by the code in the Adafruit Library
#define mySerial Serial1

When using Arduino Mega 2560 with the Adafruit Library, we use:
Using Software Serial
(Green) TX    =>  Pin 10
(White) RX    =>  Pin 11
(Red) VCC     =>  5V
(Black) GND   =>  GND
//The order of the PINs in the code is
SoftwareSerial mySerial(10, 11);

In the process of testing I also used an older version of Arduino IDE, version 1.0.5 which may have helped to get the sensor working (just a hunch). It turns out the sensor only works with 5V although it heats up a bit (not to fiery levels at a go but I wouldn't leave it turned on if I was away from my laptop for a while).
By the way, for the SFG Demo to work, upload the 'blank' example first, close Arduino and then run SFG Demo. If it works then your fingerprint scanner is in working order.
For the hardware Serial options you can also use alternative PINs as follows:

Serial2 on pins 17 (RX) and 16 (TX)
Serial3 on pins 15 (RX) and 14(TX)

Links
http://www.adafruit.com/datasheets/SFGDemoV2.0.rar
https://www.arduino.cc/en/main/OldSoftwareReleases
https://www.arduino.cc/reference/en/language/functions/communication/serial/


text:
Can Arduino Uno R3 board remove chip on the board
First off, got my Elegoo Uno board as Christmas gift, so this is all new to me.
Here is my problem, I built an motor project and the chip has been programmed. Can I remove the chip from the Uno board?
Or can I placing a new chip onto the Uno board?
Best regards.

Unless you messed with the fuses you can reprogram the chip again with a new program.

The question is not clear, please edit.  What do you mean by "remove"?  I can imagine, for example, that your Uno board is one of the older versions where the atmega328 is DIP packaged.  If this is the case, then yes, you can remove the chip after programming and place on another board.

I you want to place a new chip, you have to burn the Arduino bootloader to it first. Some stores sell ATMega328Ps with bootloader already on it.

why do you want to remove the chip?

It depends, if the chip has not been soldered, but placed in an IC (DIP) socket, than you can remove the programmed chip, and use it in another circuit and place another (same) IC in the IC socket of the Uno to be reprogrammed.
You also could desolder it, but I would not advice that; also most of the Uno's having a soldered IC use SMD instead of DIP.
Also, to replace the IC, you need to install a bootloader on the IC to be placed in the new Arduino (thanks for the addition Roberto Lo Giacco).
Below is a version with DIP that easily can be replaced, hence the big IC and the socket:

Below is a version with SMD that cannot easily be replaced, hence the small IC without a socket:

This is to me the right answer, but I would also add a note regarding the required bootloader for the new Atmega328P.

@RobertoLoGiacco Thanks, I added your comment (giving you the credits).

Yes, you can pull the DIP chip off the board, and use it elsewhere. It will require a 16 MHz crystal and two 22pF caps (or a 16MHz resonator), at least three 0.1uF (aka 100nF) caps (connect one each from VCC, AVCC, AREF to gnd - do not connect Aref to VCC), a 10K resistor from Reset to Vcc.
If you have a  hot air rework station and decide to pull off the SMD part, that chip has two VCC pins, so another 0.1uF cap is needed.


text:
Arduino Leonardo board - not running or appearing a USB on external power
I've got an Leonardo board, it seems to be official, in that it has the Arduino branding and Made In Italy on the bottom.
However I cannot get anything to run with external power supply. Everything when powered via the USB from the computer runs fine. As soon as I use any sort of external power, and I've tried both the barrel jack with 4x AA batteries, 6x AA batteries, 9v square battery and a Shield with 2x 3.7v lithium batteries - it turns on but doesn't do anything - the USB device doesn't even appear to the computer at all unless I pull the external power out again.
Is this a faulty board? Do I need to change the jumper arrangement on the board so it'll run with external power?

I have just tested all combinations of power plugging and unplugging on my Leonardo. No problem with anything.

And what "jumper arrangement" are you on about? There's no jumpers on a Leonardo.

The ICSP section - I thought it might have something to do with it. I guess i've just got a dud board then. It's a Leonardo R3 by the way.

The ICSP is a header for a connector, not for jumpers! This question is related to your previous question: https://arduino.stackexchange.com/questions/60405/leonardo-always-on-power-status-remains-between-computer-reboots With a new question please show us also the sketch. I think a arduino board with seperated usb-serial chip and removed the reset via the dtr signal is better for your project. But I don't know the ideal combination that can do it all. You are in uncharted waters.

@Jot I think this board would be idea if it would work as obviously Majenkos does when you plug in power. As there are no settings or code related to this, I can only come to the conclusion there is a fault on this board.

I just grabbed an unregulated power supply of 12v and measured 18v. Please show a sketch that we can try, tell us what kind of power supply you use.

I was just testing with Blink. You get the CDC/ACM endpoint regardless, so enumeration can be tested and the blinking confirms constant sketch execution.

I think key to my sketch is that it's working over USB-HID - it's that connection which is never made when powering externally - it doesn't appear to the computer at all. As soon as I pull the external power it connects to the computer as a HID device.

Still fine if I add Keyboard.h and Keyboard.begin() to Blink. Enumerates fine and creates a HID input device every time - with or without external power, with external power added first, or USB power added first. All combinations are fine.

I am testing it and everything is working as it should be. Can you give more information? Do you know how old the leonardo board is and which bootloader is on it? What kind of power supply? What is your sketch?

Also what version of the IDE and boards package?

by USB device not appearing you mean  the virtual com port or a HID device?

4xAA won't work as the VIN voltage must be greater than 6.6V to get precedence over the USB voltage. Did you check the polarity? The middle contact is positive, the surrounding contact is GND (negative).

@Pylon While a voltage lower than 6.6V will cause the USB's P-fet to get turned on when it's not desirable. It won't affect the operation of the sketch at all. Worst case scenario the computer will disable the USB port completely to isolate the external power. And it would alert you to that fact (Windows would pop up a bubble, linux / OS X would put it in dmesg, etc).

I tried with my Leonardo Microboard and the sketch runs just fine - so for whatever reason there's a fault on the Leonardo R3 board. Makes things a bit more annoying as i'll have to solder onto the micro board to complete the project instead of just using the shield, but supplying 5v from the shield to the micro works fine.


text:
What's the required voltage for ws2815?
I am working on ws2815 led strip with the esp8266 on arduino 1.6.6 fast led library.Using CD40109B level shifter to convert 3.3V of esp output to 12V .It's working fine upto 31 leds according to the program pattern if i increase the led count it's giving random pattern .What can be the issue.
This is the code that i am using
#include <FastLED.h>
#define LED_PIN     5
#define NUM_LEDS    50

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2813, LED_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  for (int i = 0; i <=NUM_LEDS ; i++) {
    leds[i] = CRGB (255,0 , 0);
    FastLED.show();
    delay(40);
  }
  for (int i = NUM_LEDS; i >= 0; i--) {
    leds[i] = CRGB ( 0, 255, 0);
    FastLED.show();
    delay(40);
  }
}

EDIT
We checked in oscilloscope and we observed that after internal signal reshaping of the ws2815 IC ,the RGB values are not as intended.This is also seen on the led strip with changing colour of the leds.
We are trying to generate a single colour on the strip so this colour changing is quite clear.

The current rating of the power supply I am using is 12.5A, which is enough to drive the LEDs, and the voltage is also 12V at the 32nd LED.

The voltage levels needed for the WS2815: see the datasheet. Your question is inconsistent. You ask about voltages in the subject but in the text you mention averything is fine up to 31 LEDs. So what makes you think the voltages are not OK? The LEDs work so the voltages must be OK. How about there being something unexpected happening in the program?

@Bimpelrekkie That's what i am confused .previously i was worked on ws2812, after using level shifter it worked fine but not sure what is causing the problem to this one.

Well then it's not the voltage, is it? Note that 31=2^5-1 and 32=2^5. My hunch is there is some part of your code that is hard-coded for less than 2^5 bits or uses a 5-bit field for some important value.

@ElliotAlderson but it worked fine for ws2812b led strip.Same principle for ws2812 and ws2815 only difference is data pin voltage which is 5V for ws2812 and 12V ws2815.

If this code worked for other kinds of LEDs, you were just lucky. You've committed the common error of writing beyond the end of your array, in both of your for() loops. The last location in leds[] is NUM_LEDS-1, not NUM_LEDS. It sounds like you finally got unlucky and started clobbering something important. It isn't too surprising that this occurs at a power-of-2 boundary.

@Dave Tweed sorry i used NUM_LEDS-1 only while copying i did mistake.

Well, the code in your question still shows the error. How did a simple copy-paste operation create an error like that anyway? If this isn't an exact copy of the code you're actually running, how are we to know whether there are any other differences?

You say you are level-shifting the data from 3.3V to 12V, but the datasheet for the WS2815B indicates the maximum rating for the logic input (the DI pin) is 5.3V. It is only the supply voltage that is 12V.

Another issue that I have noticed is that the code works fine with the brightness level upto 150 and the programmed pattern is observed on the led strip. However, if I increased the brightness level to 255, the code fails after a certain length. What could be the issue?

Same issue here, actually, after the 400th led maybe. My goal is to drive 639 leds.
I tried with both arduino nano and stm32, but, nothing worked. Please, tell me if you got a solution.
Regrds,
Tommy


text:
Calling external function from a class function
I'll try to explain my need:

I have a generic library I created, called myIOT.h.
This class have a pre-configured  MQTT and wifi setup.
Inside this library there is a mqtt_callback function, for all generic commands, such as boot_time and connection_status.
BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that iot.mqtt_callback(ext_mqtt_func) will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:
void myIOT::mqtt_callback(ext_mqtt_func){
if (a == true ) {
do something

};

else {

ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

}

Note that it is better to use if (a) than comparing a boolean with true or false. If you name a better so it is clear it is a boolean it is better maintainable.

@MichelKeijzers it is a string compare function to set a MQTT comman

Yes, you can do it.
You pass function pointer as function parameter.
See this stackoverflow question:
https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter

thank you, it works great. Since it have to a string using a MQTT, this ext_fuct needs as well to pass this string - and the explanation above is for a no-arg function, so I did upgrade it to be  typedef void (*cb_func)(char msg1[50]) that passes its string ( and it works great ), but I would rather pass it as a pointer to that string ( which fails )


text:
Dynamic allocation/ Pointer to Pointer to update an Array containing parameter
topicArray defined as follows:
const char* msgTopic = "Home/Messages";
const char* groupTopic = "Home/All";
char* deviceName = deviceTopic;
const char* topicArry[2] = {deviceTopic, groupTopic};

But deviceTopic can be changed during code run, and I wish that topicArray containg deviceTopic will have the correct value after deviceTopic has changed.
What is the right way doing so ?

don't make the array 'constant' with const and you can change the values (pointers) it contains

@Juraj I did remove const ouf of array and all other variable, but still array is not changed

do you change it?

as said " I did remove const"

to be able to set the value topicArray[0] = "something"

You may try something like this:
const char* topicArry[2] = {NULL, groupTopic};
const char** const pDeviceTopic = &topicArry[0];
#define deviceTopic (*pDeviceTopic)

Arguably not very elegant, but now when you assign, e.g.
deviceTopic = msgTopic;

you are actually writing into topicArry[0].


text:
Attempting to read random string from SD card
I was wondering if anyone knew how to read in a random string from a file named "PhraseList.csv" or "PhraseList.xlsx" (whatever is easier)? There is a list of 10k.
#include <SD.h>
#include <SPI.h>

File myFile;

void setup()
{

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

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

  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // re-open the file for reading:
  myFile = SD.open("PhraseList.xlsx");
  if (myFile) {
    Serial.println("PhraseList.xlsx":);

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
        Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening Phrase List");
  }
}

void loop()
{
    // nothing happens after setup
}

what is random string? ......... what does this mean? There is a list of 10k.

Reading an individual string from a list in a file is not a simple operation. Well, it's "simple", but takes a lot of work.
It's not possible to say "Get me line number 2984 from the file" with a normal text file.  You, instead, have to get each line in turn, discarding the ones you don't want, until you get to line 2984.
A better way would be to create custom "indexed" file format with a file header structure describing the rest of the file.  That header structure would contain (amongst other possible things) the offset within the file of each string it contains.
For example you may choose to have the simplest arrangement - a list of 32 bit integers (4 bytes each), each one a simple offset from the start of the file for the string that corresponds to the same number, and have the strings NULL terminated in the file.
Such as:
00000000: 0c000000 17000000 22000000 53747269  ........"...Stri
00000010: 6e67206f 6e650053 7472696e 67207477  ng one.String tw
00000020: 6f005374 72696e67 20746872 656500    o.String three.

The idea with this now is you can seek in the file to "String no * 4" and read 4 bytes as an unsigned long (arranged little endian, like the Arduino uses), then use that value to do another seek. From there you can read bytes until you hit \0, at which point you know you have finished the string.
In the example above the string "String one" is located at offset 12 within the file.  That's 0x0C in hexadecimal, or 0x0c 0x00 0x00 0x00 as a little-endian 32-bit integer.  That's the first 4 bytes in the file.  So you read those, interpret them as a 32-bit integer (12), then seek to that location in the file to get your string.
void readString(int num) {
    // Seek to the index entry
    myFile.seek(num * 4);

    // Read the index entry
    unsigned long offset = 0;
    myFile.read(&offset, 4);

    // You might want to add some sanity checking here

    // Seek to where the index points to
    myFile.seek(offset);

    // Read each character until you get a NULL.
    char c = myFile.read();
    while (c > 0) {
        Serial.write(c);
        c = myFile.read();
    }
    Serial.println();
}


text:
Am I able to set up a code where I can have two ways of turning something on?
I am pretty new to Arduino.
I've created a code with the help of many YouTube tutorials to control a servo with a button. I decided it has gotten a little un-exciting so I've been trying to add a sound sensor module to it so that if you clap or whatever, it will control the servo in the same way the servo did. Is it possible to control the servo with the button and the sound sensor so that I have to ways of turning on the servo at the same instance.
The code I currently have just runs the servo constantly and does not stop, you'll probably see what I mean when I attach the code below.
I'm just looking for help on this issue as I don't have a lot of experience with this, but my guess is it is not possible.
    #include <Servo.h>;

    const int buttonPin = 8;
    int soundSensor = 2;
    Servo servo;

    int buttonState = 0;

    void setup()
    {
      servo.attach(3);
      servo.write(80);

      pinMode(buttonPin, INPUT);

      pinMode (soundSensor, INPUT);
    }

    void loop() {
      int statusSensor = digitalRead (soundSensor);

      if (statusSensor == 1)
      {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);
      }
      else
      {
        servo.write(80);
      }

      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH)
      {
        servo.write(80);
      }
      if (buttonState == LOW)
      {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);
      }
    }

Yes, you can. You just have to change your thinking from "The button is being pressed" to "The button has been pressed".

you have to realize that controlling a servo, detecting a button press and detecting sound are all completely separate functions ..... you can have a boolean variable moveThatServo .... if the variable has a value true then the servo is moved and if it is false then the servo stops ..... you can have multiple buttons, some set moveThatServo to true and some set it to false .... you can have a sound detector that sets moveThatServo to true ...... you can write a timer function that does the same..... just use your imagination

Just cobled this together,
untested but should give you some hints in the right direction.
In the main loop it checks the condition of the button and also the sound detector.
If either are active it sets a bool to true.
at the end of the loop, if either are true it calls the servo function that then powers the servo.
hopefully you will be able to pull this apart to add more triggers
#include <Servo.h>;

const int buttonPin = 8;
int soundSensor = 2;
Servo servo;

int buttonState = 0;
int statusSensor = 0;

bool runServo = false;  // bool setting to start the servo

void setup()
{
  servo.attach(3);
  servo.write(80);

  pinMode(buttonPin, INPUT);
  pinMode (soundSensor, INPUT);
}

void loop() {
  statusSensor = digitalRead (soundSensor);
  buttonState = digitalRead(buttonPin);

    runServo = false;  // start of loop reset the runServo flag

  if (statusSensor == 1)
  {
    runServo = true;
  }

  if (buttonState == HIGH)
  {
    runServo = true
  }

  if (runServo == true)
  {
    servoFunction();//call the servoFunction code
  }

};

void servoFunction(){
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(500);

}

Spriggsy


text:
Keyboard.h: No such file or directory - Arduino pro micro (leonardo)
I've just bought a new pro-micro and I want to simulate some keyboard inputs with it, the thing is the Arduino IDE (version 2:1.0.5) can't seem to find neither HID.h or Keyboard.h libraries. The steps to reproduce the problem are:

plug the device using usb cable on the pc
Open arduino ide
try to compile my code
it fails with the error

test_keyboard.ino:27:22: fatal error: Keyboard.h: No such file or directory
  compilation terminated.

The code is:
#include <Keyboard.h>

void typeKey(int key)
{
  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */
void setup()
{
  // Begining the Keyboard stream
  Keyboard.begin();

  delay(400);

  //Keyboard.press(KEY_LEFT_GUI);

  Keyboard.press(KEY_CTRL);
  Keyboard.press(KEY_ALT);
  Keyboard.press(KEY_T);

  Keyboard.releaseAll();

  delay(100);

  Keyboard.print("echo 'hello world'");

  typeKey(KEY_RETURN);

  delay(100);

  // Ending stream
  Keyboard.end();
}

/* Unused endless loop */
void loop() {}

By the way, I'm running this on linux, after pluging it and running lsusb on terminal I got:
  Bus 002 Device 071: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

Remove the line #include <Keyboard.h> from your sketch.
Update to a modern version of the Arduino IDE. Note that when you install the Arduino IDE via sudo apt-get install arduino, you end up with the very outdated IDE version you're using. I recommend always installing the official Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software.

For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:
#if ARDUINO > 10605
#include <Keyboard.h>
#endif

Reference: https://github.com/arduino/Arduino/pull/3304

Don't hang around in the stone age, step forward to 2019 and join us with the newest Arduino IDE.
Do you use the newest linux version, for example Ubuntu 18.10?
Remove all arduino related packages from the repositories.
Be sure to remove the package librxtx-java.
You don't need to install Java, jdk, openjdk, jre or any of those.
If you use snap, remove the Java and Arduino from the snap as well.
When you have used such an old version, I suggest to delete the hidden .arduino15 folder from your HOME folder.
Perhaps you have downloaded libraries that are now included with the Arduino IDE. You could check the "libraries" folder (in the same folder as the folders of your projects) and delete unused libraries.
Download the Arduino IDE from the arduino.cc website.
The 32-bit version for a 32-bit linux system, and the 64-bit version for a 64-bit linux system.
Unpack it somewhere in under your HOME folder. You can make a shortcut to the file "arduino" and run the shortcut.
Don't make changes to the stardard Arduino system files (the Arduino IDE that you have downloaded and unpacked). Sometimes it is needed to make changes to the files in the hidden .arduino15 folder.


text:
Can the IDE handle a 32khz main clock?
I read somewhere that having the main clock be 32768Hz messes not only with micros() and millis(), but with some other stuff too. Is this true? Will I have to forgo the Arduino IDE to program for an avr running at 32768Hz?

Do you still need to know if filter capacitors are required? https://electronics.stackexchange.com/questions/416523/32khz-crystal-for-avr-caps-needed

@VE7JRO No. And are you able to answer this question?

Sorry, I don't have a definitive answer for you. There is a debate about it here: https://forum.arduino.cc/index.php?topic=75397.0

Please tell us why you want a main clock of 32.768kHz. Have you heard of the XY-problem http://xyproblem.info/ Most microcontrollers and processors that are used in arduino boards are capable to use a crystal of 32.768kHz but the arduino code is not for such a low clock.

Yes, things will break. The main culpret is this:
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

With any value below 1000000 the result of that calculation will be 0.
That means code like micros() will break, since it uses:
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());

64/0 is ... um ... yes... And whatever that ends up being is then multiplying the tick count. So ... the result of micros() is ... um ... yes...
In fact, when trying to compile anything you get (certainly on UECIDE):
• Error at line 103 in file wiring.c:
    ‣ division by zero [-Werror=div-by-zero]

Since that's erroring when compiling code there's not a lot you can do about it.
However, one idea does spring to mind - one that is a little "crazy" I guess.

Set your boards.txt entry to 3276800Hz

The calculations will all then be valid - however, they will all be out by a factor of 100.
With the board actually running at 32768, and the API thinking it runs at 3276800, all you need to do is use values 100x less than you would normally in your calculations.
For instance, to delay 1 second you'd use delay(10); instead of delay(1000);.  Or you'd multiply the return value of millis() by 100 to get the real number of milliseconds.
Baud rates will have to be 100x faster - so use Serial.begin(960000); instead of Serial.begin(9600);.
Of course, the clockCyclesPerMicrosecond() is not geared towards working with values like 3276800, and F_CPU/1000000L will result in 3 not 3.2768 as you'd like, so timing calculations will be a little bit off. You may need to tweak things like baud rates accordingly to compensate.


text:
WifiNINA WebServer not receiving connections
I use a MKR 1010 (firmware 1.2.1), download WifiNINA library (version 1.3.0) and started to play with it.
I can connect to my Wifi network, and WifiNINA library examples such a WifiPing (which repeatedly pings www.google.com) works fine.
However, I can't get any of the server examples (e.g. WifiWebServer) to work.
I can see that the board connects to the network and gets an IP and the Serial monitor is printing this :
09:11:15.989 -> SSID: OfficeNet
09:11:15.989 -> IP Address: 192.168.1.44
09:11:15.989 -> signal strength (RSSI):-36 dBm
09:11:15.989 -> To see this page in action, open a browser to http://192.168.1.44

But if I browser to http://192.168.1.44, I never get any answer.
The loop code is just from the example :
void loop() {
  WiFiClient client = server.available();   // listen for incoming clients

  if (client)
  {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
(...)
  }
  // close the connection:
  client.stop();
  Serial.println("client disonnected");
}

I am never getting inside the if client()loop ("new client" never printed).
Any suggestions?

on what port do you start the server? didn't you forget to call server.begin()?

This is the out-of-the-box example code, so port 80, and server.begin() is on the last line of setup()

is your computer on the same WiFi network?

Yes, same network "OfficeNet". I did some more tests, the arduino can ping google server, but no computer from my network (I tried with 2 of them - and they can ping each other). I forced fixed IP address for all of them, no change...

is the network mask 255.255.255.0 or is it different?

Thanks for your interest Juraj ! Not sure how to check this. In my TCP/IP configuration there is something I would translate by "sub-network" which value is indeed 255.255.255.0. It is now quite late in my time zone. I'll go to sleep and delete/re-install everything tomorrow.

yes I meant sub-network mask. it determines which IP addresses 'see' each other. in case of 255.255.255.0 all addresses with the same first 3 numbers of IP address should be able to communicate

Dawn ! I deleted the whole Arduino IDE and re-installed everything yesterday night, and I got it working without any modification ! I even could ping any machine from my network. Switch off everything, came back this morning, and same problem again. Nothing works...


text:
Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?
I need to control 4 DC brushless motors. I have no experience with arduino or coding. After some research the cleanest setup seems to be using the Adafruit motor shield, however the motors I'm using have 5 wires. Can I still make this work? I envision the motors being connected to the shield via the negative and positive power wires, but what do I do with the rest?  Thank you in advance.

Those motor have a "built-in drive". It has electronics inside to control the motor. You don't need the adafruit motor shield for those motors. The pwm wire is used to control the speed of the motor with a pwm signal. I think the pwm signal needs to be between 15kHz and 25kHz. That is more than the 500Hz of the analogWrite arduino function. A hall signal output gives pulses when the shaft is rotating. You can use that to measure the speed. There is also a wire to control the direction (clockwise or counterclockwise).

I'm trying to get a set-up with the fewest amount of wires. Would it be possible to use these motors without making use of the built in drivers?

Not really. When you don't need to control the speed, then you can tie the pwm input to GND and power them with 12v or 24v. If two wires per motor is okay and three wires is not, then you have an other problem.

What if I switch the motors to brushed DC? https://www.aliexpress.com/item/ChiHai-Motor-CHR-GM16-050SH-Permanent-Magnet-Miniature-DC-Metal-Tooth-Speed-Reduction-Motor-DV-6v/32826266828.html?spm=2114.10010108.100009.1.33603ae1FeAwMD&gps-id=pcDetailLeftTopSell&scm=1007.13482.95643.0&scm_id=1007.13482.95643.0&scm-url=1007.13482.95643.0&pvid=d7b4942c-3c6e-4747-8026-e7cf8bc0ed32

You don't need the motor shield at all. The motor you link to has its own driver built in.
According to the connection table on the page you link to:

Red wire to +24V
Green wire is for sensing the RPM - you can ignore it
Yellow wire is the direction select - connect to any GPIO
Black wire is ground - connect to 24V GND and Arduino GND.
Blue wire is PWM control. Connect to any PWM output on the Arduino

Note that the motor will probably spin immediately power is applied until your sketch tells it to stop by driving the PWM output LOW (or 0% duty cycle).  There appears to be a 15-25kΩ (typical) pullup resistor on that pin, so adding a smaller pulldown resistor (say 1kΩ) on it should force it to be off until you turn it on.

Majenko, I'm sure that the 15-25k are not resistors but is the frequency for the pwm signal. I read elsewhere ( https://www.aliexpress.com/item/BLDC-brushless-gear-MOTOR-DC24V-12V-High-torque-high-efficiency-long-life-Motor-diameter-25mm-10v/32654537700.html ) that it can operate with a pwm frequency of 1kHz. When the pwm signal is low, the motor is on. And the motor has also a gear.

@Jot Could be. It's hard to tell from that Chinglish spec sheet. The OP may just have to make do with having the motors spin out of control at powerup - or add extra power control so they only get power once the IO pins are set LOW.

I'm trying to get a set-up with the fewest amount of wires. Would it be possible to use these motors without making use of the built in drivers?


text:
Arduino as Modbus RS485 slave using only 2 Digital pins
I want to use RX(0) and TX(1) Pins to make Arduino as an RS485 slave. To do this I am using MAX485 IC (Breakout board) https://datasheets.maximintegrated.com/en/ds/MAX1487-MAX491.pdf
The problem here is that I don't have any other pins remaining to interface with the module in order to pull the DE/RE pin HIGH/LOW.
Can anyone suggest a way to do this without using one additional pin?

http://www.ti.com/lit/ug/tidubw6/tidubw6.pdf

@Majenko Thanks. I could definitely use the NA555.


text:
code for OLED display suddenly crashes arduino Nano
Today i've been playing with my monochrome oled 128x64 adafruit screen. I've got it connected using SPI. Previously today i had no problems att all and i was able to print messages and variables on the screen. But suddenly my functions causes the arduino Nano to restart and initialise Setup() again!
It is very frustrating and i cannot figure out what part of my code is causing the crash!
I have tried running the adafruit example code to test the screen and it is working, so the screen is not broken and the wires must be correct.
Here is the code for my display:
display.h :
#include <Adafruit_GFX.h>  // Include core graphics library for the display
#include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Define SPI pins:

#define OLED_MOSI   9
#define OLED_CLK   6
#define OLED_DC    7
#define OLED_CS    8
#define OLED_RESET 13

// Create display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#include <Fonts/FreeMonoBold12pt7b.h>  // Add a custom font
#include <Fonts/FreeMono9pt7b.h>  // Add a custom font

void initDisplay(){

  delay(100);

  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();  // Clear the buffer

  display.setTextColor(WHITE);  // Set color of the text

  display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

  display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                               // To override this behavior (so text will run off the right side of the display - useful for
                               // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                               // with setTextWrap(true).

  display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

  Serial.println("Display initiated..");

}

void printMessage(String message){
  display.setFont(&FreeMono9pt7b);  // Set a custom font
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
  display.setTextColor(WHITE);
  display.setCursor(0,50);
  display.clearDisplay();
  display.print(message);
  display.display();
  Serial.println("printing message on display");
  delay(1000);

}
void printTemp(long temp){

  display.setFont(&FreeMono9pt7b);  // Set a custom font
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

  display.clearDisplay();  // Clear the display so we can refresh
  // Print text:
  display.setCursor(25, 15);  // (x,y)
  display.println("temp:");  // Text or value to print
  // Draw rectangle:
  display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                           // It draws from the location to down-right

  display.setFont(&FreeMonoBold12pt7b);  // Set a custom font
  // Print variable with left alignment:
  display.setCursor(83, 20);  // (x,y)
  display.println(temp);  // Text or value to print

  display.display();  // Print everything we set previously
  Serial.println("Printing temp..");

}

main.ino:
#include "display.h";
#include "DHT.h";
#include "Radiocom.h";

long temperature;

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

  initDHT();
  initDisplay();
  //initRF();
}

void loop()
{
  //temperature = readTemp();
  //delay(1000);
  //printTemp(temperature);
  String message = "123456789abc";
  printMessage(message);
  //sendMsg();
  //RFlisten();
  delay(1000);
}

If anyone can help me out in any way, i would be really thankfull!

W/o looking closely at the code, my go to answer for such situations is to make sure your power supply can handle the maximum current demand.  Especially when the display is totally lit up.  Hum, what happens when your code prints nothing (dark screen) to the OLED display?

Well it was working earlier today and the adafruit example code makes the display work.

To be clear, are you saying you changed nothing in the code?  And now it is not working?   But the Adafruit example code is working?  Well, other possibilities: 1) You did accidentally change something in your code. 2) You updated the libraries (supporting code) for your platform and changed something.  3) You updated the libraries (supporting code) from Adafruit and changed something.  4) You really are not running your code (uploading it to the Arduino) for some reason. Follow up on these and try to come up w/a few of your own.

Where's the rest of your code? Rarely is it the case that the bit you think is the problem actually is the problem. We need all your code.

Okay i will add the rest of the relevant code

I edited in the code in the original post

Well, that String use will be making a mess of your heap - a heap already crowded with the SSD1306 buffer.

The graphic library, the fonts, the radiocom, the String, it is probably a memory problem. Do you have a arduino mega 2560 or a arduino zero or arduino mkr? When it is not a memory problem then it is still a memory problem but also a power problem.

Aha! a memory problem seems plausible.. Is there a better way to manage the text than using strings? The program is running on an arduino nano ch340

When i replace "display.begin(SSD1306_SWITCHCAPVCC)" with "  if(!display.begin(SSD1306_SWITCHCAPVCC)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}  "
as they use in the adafruit example sketch, i get "SSD1306 allocation failed" in the console.. not sure what causes this

The arduino does not crash and restart anymore. I stripped away the custom fonts. But it still wont turn the display on or print my message..

https://majenko.co.uk/blog/evils-arduino-strings


text:
AK4524 with Arduino
I have some AK4524 ADC/DAC chips from an old M-Audio Delta 10/10 sound card in my hand.
I would like to use them for precision sensor reading and voltage generating with a arduino nano.
My experience with digital electronics is limited, i have used mcp4822 as a dac before with arduino and a bit familiar with SPI.
Would you point me to the right direction on this matter.
https://people.freebsd.org/~lofi/4524.pdf
This is the datasheet.
Thank you.

You can't use those with an Arduino Nano. You need a microcontroller that can generate a full duplex I2S data stream, and that usually means one of the 32-bit boards. Probably a Teensy 3.x is your best bet.

Also audio CODECs aren't really suitable for sensors.

Thank you very much, why would an audio codec not suitable for sensors? Because of the DC AC difference? Also would these be easy to interface with a Teensy?

They don't work quite the same as a voltage DAC like you're used to. They need a constant stream of data feeding to them to control the output voltage (which is a differential output, not single-ended), and the ADC gives a constant high speed stream of data - tens of thousands of readings per second. You can't just go "Set DAC A to 23" or "Get me the current ADC value from channel 1".

Thank you I will do more reading on the differences.


text:
Array is affecting digitalread values
i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.
This is the first set of code that works properly:
class Button {

  public:

    int pin;
    int state;
    int location;
    int Speed;
    int Direction;
    int active;
    int prevstate;

    Button(int pin1, int state1, int location1, int active1, int previousState)
    {
      pin = pin1;
      state = state1;
      location = location1;
      active = active1;
      prevstate = previousState;
    }
};

Button button(7,0,0,0,0);
Button button2(8,0,0,0,0);
Button buttons[2] = {button, button2};

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

void loop() {
   if (digitalRead(button2.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
       if (digitalRead(button.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
}

this is the code i want to use but it is not working.. the led stays in the on position:
void loop(){
  for (int i = 0; i<sizeof(buttons); i++){
    if(digitalRead(buttons[i].pin) == HIGH){
          digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
    }
}

also if i change
if(digitalRead(buttons[i].pin) == HIGH)

to
if(digitalRead(buttons[0].pin) == HIGH)

the code works for the first or second button alone in the array.. but not both???

sizeof(buttons) is not the count of elements in the array. it is the size in bytes. so you read some other pins too. use #define BUTTONS_COUNT 2

"If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed" - Just put the buttons in parallel and use only 1 I/O pin ;-)

You seem to have made 4 button objects: button, button2, and buttons[2]. buttons[0] and buttons[1] are full button objects whose first member, .pin, is initialized to the addresses of button and button2, respectively. This is probably not what you intended.
Did you mean to create:
Button buttons[2] = {
   {7,0,0,0,0},
   {8,0,0,0,0}
};

, an array of two initialized button objects?

I have to disagree that your first sketch is working. I suppose that a very fast blinking led seems to be "on".
When you describe what should happen in a logic way, then you can put that into code.
The logic is: The led is on, if at least one of the buttons is pressed.
In other words: The led is off, if no button is pressed, else the led is on.
This logic has as a result that the led stays on if a second button is pressed and after that the first button is released. I assume this is okay.
For two buttons it is possible to check both conditions.
if (digitalRead(button.pin) == HIGH || digitalRead(button2.pin) == HIGH)
  digitalWrite(ledPin, HIGH);
else
  digitalWrite(ledPin, LOW);

Or test for LOW:
if (digitalRead(button.pin) == LOW && digitalRead(button2.pin) == LOW)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);

For multiple buttons, a bool can be used or the number of pressed buttons can be counted.
A fixed number for the array size is easy and has less chance for a mistake:
#define BUTTONS_COUNT 2

It is also possible to use sizeof(). The total size has to be divided by the size of one element:
int count = 0;
for (int i = 0; i<sizeof(buttons)/sizeof(Button); i++) {
  if (digitalRead(buttons[i].pin) == HIGH) {
    count++;
  }
}

if (count == 0)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);


text:
Arduino Uno and FastLED WS2812B Glitching
I’m using an Arduino Uno and a fastLed WS2812B.
I have the leds set up correctly. Every 2 seconds, the lights pause of about a second and display seemingly random colors.
Does anyone know what's wrong?
My code:
#include <FastLED.h>

#define LED_PIN   7
#define NUM_LEDS  10

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

}

void loop() {
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(0,0,255);
    FastLED.show();
    delay(100);
  }
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(255,0,0);
    FastLED.show();
    delay(100);
  }
}

Is this on an Arduino or something else like ESP8266?

It is an Arduino Uno

How are you powering the LEDs?

I noted that each example in fastled library, ‘’clear’’ the array, after running ‘’show’’ function. Try with: leds[i]= CRGB::Black; after ‘’show’’.

what happens if you put FastLED.show(); and delay(100); after the for loop

I am powering with three AA batteries

How are you connecting those batteries?

I just connect them in series directly to the lights. Should I also attach them to the 5v and ground on the arduino?

connecting the grounds fixed it =D, does anyone know why?

https://majenko.co.uk/blog/importance-sharing-grounds

I have run the code on the Arduino simulator online. If it is working in the Arduino Simulator chances are less that it has to do something with the code itself.
Hence, also as the root cause was found to be about sharing the ground @Majenko
This is also one example of solving the problem step by step. validating one section after the other. using the simulator you can verify that the code is working fine. later, proceed to verify the hardware. I hope this helps.
You can verify the FastLED code here (you can modify the parameters)

Is this really answering the question? It seems to be saying what the problem isn't.

@NickGammon I too agree ☑. I tried to show how I could deduce the root cause to be hardware and not the library or the code itself. The OP has also found the root cause to be hardware.


text:
How do I make a Servo Stop if it Hits Resistance?
I am trying to make a device which will turn a turn key with a servo.
However, I want it to stop turning the turn key if the resistance is too great (meaning it is locked and will not ever turn).
How do I do this? Would I just tell it to turn and then have it turn back after a time (because if it is locked or not it should be done within that time)?
I do not want to damage my servo by having it try to turn something that it can't turn.
I am using an Arduino Uno and the library "Servo.h". The servo being used is a Batan S1123.

It depends on what kind of failure you expect. If you're afraid the motor may break your linkage (the gears, cranks, belts, whatever you have in place), you have to react very fast, and it's only feasible with a current measurement. That would require sensing the current and reacting very quickly on over-current to be effective.
If you know for a fact that your linkage can withstand the stall torque of the motor, you just have to worry about overheating the motor. Such a protection can be done with a position sensor or a limit switch if you happen to have one. You could even implement a protection with no sensors at all: drive the motor for just long enough to do its job and then stop: either it will turn the key or it won't, but it won't overheat if stalled for a second or two.

You could either:

Use a limit-switch to sense that the servo has completed it move. If it doesn't complete it a reasonable time, return it to its original position. Or,
Measure the motor current by putting a low value resistor inline with the ground side of the motor's power supply. With one of the A/D pins, measure the voltage on the motor side of the resistor, which increases with motor current. You'll need to have figured out how much current the motor draws when operating normally. If the motor stalls, your controller could sense that by seeing that current increase. Pick a value (try 150%, for example) of over-current as an indicator that the motor is stalled, and return it to its original position.

The first way is easier to implement but possibly lets the motor stall while you wait for the expected move time to expire. The second way lets you detect stalling and take action immediately.

I don't think the limit switch solution would prevent the servo from stripping its gears if it binds before you check the switch. Option 2 would be the better avenue to explore.

You should understand that you control the servo with PWM pulses. The servo translates the width of the pulse to an amount of rotation. A standard servo has no means of indicating its current position. You can only tell it where you want it to be.

If it could strip gears, it's under-built; it shouldn't be able to damage itself under forseeable circumstances (stalling). But even then, current-sensing should give you sufficient opportunity to protect it.

"If it could strip gears, it's under-built" - this is usually true for toys and small applications (so it's likely the OP's case as well), but not true in general. Most products where a motor is not designed to work at 0RPM (mixers, etc.) will happily strip gears when stalled, unless they have protection implemented in software.

The best way is use external feedback. Hall sensor for example.
200-250ms after using servo check status of hall sensor

Or a current sensor on the Servo power line, back off the position when you detect the current rising from the motor being stalled.

Yes, that's possible. Hall seems easier

Could you expand on how you would use a hall sensor to complete this task?

Put little magnet on key and hall sensor near end point of key.

Ah. So if sensor fails to detect magnet x moments after servo push has started, resistance has been encountered, stop pushing.

I suggest detecting the current flowing through the servo or using a potentiometer to detect whether the servo is moving. You could also put a clutch between the servo and the key, but then you wouldn't know the angle of the key at any given time.


text:
Can't connect to the server
I am working on a specific project that requires a database.
I have done the 'connection' and the "write" of data using a PHP file.
I have even reconfigured everything so it would be possible to access the database through a different device that is connected to the same wifi network as my computer.
All tested and working properly.
The Arduino for some reason is not connecting to the server, where Serial.println(client.connect(serv, 8095)); is returning 0, I have tried every possible solution but nothing seems to work.
I am using xampp, and I changed the port to 8095.
any possible information would be much appreciated.
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
  0xFDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

byte sensorInterrupt = A2;
byte sensorPin       = A2;
float calibrationFactor = 4.5;
volatile byte pulseCount;
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;
char valvestatus= 'ON';
byte ip[] = {192, 168, 1, 4 }; //Read the code explanation https://102.159.198.42/
byte serv[] = {192, 168, 1, 3} ; //Read the code explanation  192.168.1.3
EthernetClient client;

void setup() {
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
delay(1000);
   pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

}

void loop() {

  if((millis() - oldTime) > 1000) {
    detachInterrupt(sensorInterrupt);
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    oldTime = millis();
    flowMilliLitres = (flowRate / 60) * 1000;
    totalMilliLitres += flowMilliLitres;
     unsigned int frac;
    Serial.print(int(flowRate));  ////////
    Serial.print(totalMilliLitres); /////////////
   pulseCount = 0;
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

    }

    Serial.println(client.connect(serv, 8095));
    if (client.connect(serv, 8095)) { //Connecting at the IP address and port we saved before
client.print("GET /ost/write_data.php?"); //Connecting and Sending values to database
client.print(flowRate);
client.print(totalMilliLitres);
client.print(valvestatus);
 client.stop(); //Closing the connection
    }
 while(!client.available()){}

}

void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

firewall on the computer

tested with the firewall off already, yet not working.