text:
motor controll holding ir remote button
im controlling some small dc motors using arduino uno and tle94112el shield. currently, i can independently controll motors by pressing remote's buttons, but i wanna keep one motor rotating by holding a button. for example, by holding "unu" button, i wanna power the motor with 50% duty cycle, as i currently do by just pressing "unu".
thank you!
#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1
#define patru 0x4
#define sapte 0x7

int RECV_PIN = 2;

// Tle94112 Object
Tle94112 controller = Tle94112();

// Tle94112Motor Objects
Tle94112Motor motor1(controller);
Tle94112Motor motor2(controller);
Tle94112Motor motor3(controller);

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  // Enable MotorController Tle94112
  // Note: Required to be done before starting to configure the motor

   irrecv.enableIRIn();
  controller.begin();

   // Connect motor1 to HB1 and HB3
  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);

  // Drive HB1 with signal from PWM1
  // Note: This allows to control the speed of the motor

  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);

  // Set PWM Frequency, default is 80 Hz
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == unu)
    {
      motor1.start(127);
    }

    if (results.value == patru)
    {
      motor1.start(255);
    }

    if (results.value == sapte)
    {
      motor1.start(0);
    }
  }

}

thanks for replying. i followed your instructures. when i hold the button, my remote sends continuously the same code it sends for a single press too. so in the brackets of second "if", i used the same condition that i used in first "if". following your instructions, when i prees the button, motor starts, even if i release or keep holding the button, the motor keeps rotating, but when i press the same button second time, the motor stops. so instead of "timestamp = millis()", i used "timestamp < millis()", so in this situation, the motor was rotating as long as i kept the button pressed. now the problem is that the motor is powered with pulses, aprox. 2 impulses per second, it doesnt rotate smoothly. i tryed incresing and decreasing TIMEOUT with no effects. i also used all the pwm frequencies (80, 100, 200 hz) that the shield provides, and different duty cycles, also with no effects. but when i add 2 more motors, to controll them in the same way, each with it's own button, the pulses period was even bigger, with aprox one impuls on second. do you have any ideea about this? sorry, but its my first arduino project, i also have no experience on engineering forums. thaks for your time.
here is the code im using now:
#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1

unsigned long timestamp = 0;
#define TIMEOUT   200

int RECV_PIN = 2;

// Tle94112 Object
Tle94112 controller = Tle94112();

// Tle94112Motor Objects
Tle94112Motor motor1(controller);

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  // Enable MotorController Tle94112
  // Note: Required to be done before starting to configure the motor

   irrecv.enableIRIn();
  controller.begin();

   // Connect motor1 to HB1 and HB3
  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);

  // Drive HB1 with signal from PWM1
  // Note: This allows to control the speed of the motor

  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);

  // Set PWM Frequency, default is 80 Hz
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == unu)
    {
      motor1.start(127);
      timestamp < millis();

    }

    if(results.value == unu){
      timestamp < millis();
    }

    if(millis() - timestamp > TIMEOUT){
      motor1.start(0);
    }
  }
}

Please format your code correctly, so that it gets readable. In the question editor select the code and click the {}button or press control+K

Replacing the assignment = with a comparison < breaks the logic of my solution. You are doing something else wrong. Please add your new code to the question

i understood now the logic of your solution, and i understood that replacing = with < breacks the logic, but it worked as i described.

I formatted the code for you and put the old part of the question back in. That way future readers can understand the thoughts and learnings behind the question.

I edited my question to address the problems of the new code

As I understood you want the motor to run only while you are pressing the button, stopping as you release the button. IR remote controls normally don't send a "release" signal. But they often send a "repeat" signal in a defined frequency. The value of this signal depends on the remote, that you use. A quick search showed this forum thread, where the value is 0xFFFFFFFF.
So to check, if the button is still pressed, you need to regularly check, if the repeat code was received. When receiving the unu signal, turn on the motor and start a timeout counter. Every time you receive the repeat signal, you reset the timeout counter. If the timeout hits (meaning, that no repeat signal was received anymore), stop the motor.
The timeout counter is best done with the millis() function, which returns the number of milliseconds since startup. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE. Basically you save the time in a variable, when the unu code is received (the receive if statement is pseudo code). You reset the timestamp in the same way for every repeat code. Then you check, if the different between the current time (returned by millis() and the timestamp is over the timeout value (here 200ms). If yes, turn the motor off.
unsigned long timestamp = 0;
#define TIMEOUT   200

void loop(){
    if(unu was received){
        // turn on motor here
        timestamp = millis(); //take timestamp
    }
    if(repeat was received){
        timestamp = millis();
    }

    if(millis() - timestamp > TIMEOUT){
        // turn off motor here
    }
}

In your new version you replaces the = with a < to make it work. That is wrong. The lines, where you did it,  will just do nothing then. Instead the problem lies at a different place:
The millis() if statement
if(millis() - timestamp > TIMEOUT)

has to be placed directly in void loop(), outside of the receive if statement. In your current version the timeout will only take effect, when something was received, which was not unu. But you want it to take effect also when nothing is received. In that case the receive if statement will not execute. So just move the millis() if statement outside of that receive if statement:
#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1

unsigned long timestamp = 0;
#define TIMEOUT   700

int RECV_PIN = 2;

// Tle94112 Object
Tle94112 controller = Tle94112();

// Tle94112Motor Objects
Tle94112Motor motor1(controller);

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  // Enable MotorController Tle94112
  // Note: Required to be done before starting to configure the motor

   irrecv.enableIRIn();
  controller.begin();

   // Connect motor1 to HB1 and HB3
  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);

  // Drive HB1 with signal from PWM1
  // Note: This allows to control the speed of the motor

  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);

  // Set PWM Frequency, default is 80 Hz
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == unu)
    {
      motor1.start(127);
      timestamp < millis();

    }

    if(results.value == unu){
      timestamp < millis();
    }
  }

  if(millis() - timestamp > TIMEOUT){
    motor1.start(0);
  }
}

That way the timeout will be checked at every loop() iteration. As you described, that you get the code about 2 times per second, I increased the timeout value here to 700ms, which then should be enough to not let the motor stop between the receiving of the unu command.

Btw: To stop the motor you are using motor.start(0);. While it works perfectly, you might want to write your code more speaking. The used library internally just calls it's motor.coast(); function, when the parameter is zero. So to make it more obvious in your code, what you are doing there, you could replace motor.start(0); by motor.coast(). That can help others to understand your code better and also yourself, when you are revising the code yourself after some time, when you may have forgotten, what you thought at that time about the code. It is always better to write code, that speaks by itself about what it is doing.

oh thanks!!!!
it works now!!


text:
Arduino 5V pump digital pin
I am trying to control a 5V pump with arduino and ultrasonic sensor however i can't make it work with the pump connected to a pin.
I saw on the forum that you need transistor or relay but i don't understand why ?
Thanks !

Probably because the pump will use more current (mA) than a GPIO pin of the Arduino can deliver.
A GPIO pin on the Arduino can deliver 20 mA, or 40 mA max (but not advised for longer time).
Therefore, a separate power supplyis used, where the base pin of a transistor is connected to a GPIO pin (with a resistor) to 'switch' the transistor on and off.
The transistor base can be very low current (way within a GPIO's current range), which result in a much bigger current from the collector (connected to the power supply) to the emitter (connected to GND). The pump is somewhere between the external power supply and GND).
If you search for 'transistor as a switch' you will find many examples.
You also can use a relay if you don't need to switch it on often. Relay's are typically used for net-powered devices (110+ volts) and/or high current. See also Duncan's comments for additional notes regarding relays.

Good answer as usual, but if you use a relay the relay's coils will almost certainly need more current than a GPIO pin can provide, so you'll still need a transistor (And a "flyback diode") to drive the relay. There are various "digital relay" modules that have all that built in and are meant to be controlled directly from a  5V GPIO pin. You feed them a 5V supply line, plus the control signal, and they turn the relay on or off based on the digital pin.

Also note that if you drive an inductive load like a pump from a transistor, you should have a "flyback diode" to protect the transistor from back EMF from the inductor.

@DuncanC Good comment as usual :-) ... I have to admit for some tests I indeed did not use a 'bare' relay, but a relay module, which contains the flyback diode and opto coupler probably together with a transistor. I added a line in my answer to read your comments.

Thansk for the answers ! i did with transistor and it worked thanks however if i connect the pump straight to the 5v it work so it means that the pin on the arduino have less voltage/ ampere ?

The pin on the Arduino is 5V ... to get the max. recommended 20 mA your pump should be max 5 * 0.02 A = 0.1 W. However, the Arduino will go dead (or the pin) when using more than 40 mA, but between 20 mA and 40 mA it will work, but it's definitely not good for the Arduino (especially over a longer time). So what you can do, use you a digital multimeter (DMM) to check the current and verify if this is max. 20 mA. Also check how to measure current (Amperes) on a DMM. 0.1 W seems like a very tiny pump to me.

Okok gonna check that ! thanks a lot for your help!

@michel-keijzers has pointed you in the right direction. Depending upon the power requirements for your pump, you might consider looking specifically at logic-level power MOSFETs as the type of transistor in your circuit.
You might also investigate the use of a pull-up resistor to fully turn on a MOSFET.

MOSFET is actually a tag in this forum (https://arduino.stackexchange.com/questions/tagged/mosfet). You might get some ideas from other questions.

Indeed, logic level MOSFETs are often an excellent choice because they draw almost no current from the controlling GPIO pin. They have VERY low "on resistance" so they can control high current (DC) loads while generating very little heat and wasting very little power.

source: Stack Exchange

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

sort: votes


text:
PWM Input Pins Never Receive a Value from Working Receiver?
I have a very simple sketch that's supposed to intercept the signal from an RC receiver and print the pulse duration from that channel.
Sketch
int PwmPin = 9;
unsigned long duration;

void setup() {
  pinMode(PwmPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  duration = pulseIn(PwmPin, HIGH);
  Serial.println(duration);
}

Output
0
0
0
...

My setup is the normal one that would occur without an Arduino, and only the battery is connected through the ESC to provide power to the receiver. The Arduino is connected via USB because I'm just trying to read values.

I have been trying to plug between the receiver's data pin to the Arduino's PWM pin and read the pulses from the rudder channel. (I have previously tested the channel with a servo and know that it works correctly). However, no signal (0) is being printed to the serial monitor. I have difficulty understanding why.
I checked the documentation for pulseIn(), and it seems simple enough. I tested PWM pins D3, D5, D10... none of them works. I don't understand where the problem is at this point. Update: I am now connecting from the receiver's negative pin to one of the Arduino's GNDs.
This is a simplistic scenario, so I don't see what's going wrong (my programming experience is good, but my experience with Arduino is near nil).
The goal of this experiment is to program lights to change according to throttle input, and asymmetric thrust through two motors for a boat. I know that pulseIn isn't the best function to use, but for the moment I just want to do some quick development before getting into the weeds.
Update:
I am attempting to follow this video, except that connecting the Arduino to the receiver didn't work, possibly because the ESC's BEC sends some sort of power signal that arms the receiver. (The receiver's LEDs usually make a visual signal, but they just turn on without a signal when connected through the Arduino).
According to the manual on page 6 and page 8, "receivers have an operational voltage range of 3.5 to 9 volts", with an ideal voltage being above 4.8V (because servos tend to brownout sooner). This should fall within Arduino range at 5V.

First: Never show code and serial output as an image. Copy and paste them as text into the question and format them as code. Second: You really need to connect the ground between Arduino and receiver. That is not optional. Are you sure, that there really is a signal on the receivers pin?

No ground connection?! https://majenko.co.uk/blog/importance-sharing-grounds

@chrisl Yes, I'm sure there's a signal; it's marked on the receiver as - + (signal), and I tested the pin, and it works fine with a servo. Even when I connect the ground it doesn't work with Arduino, however.

On what voltage does the receiver run? 5V as the Arduino?

@Majenko Because I'm a little confused. I'm only connected to the signal pin, not the positive pin, so both the positive pin and the signal pin of the receiver ground through the negative wire?

Everything needs a common ground in order to work.  You need a common point to reference voltages to.

You can't measure a voltage with only one connection. You have to connect the grounds.

BTW, there is no such thing as a "PWM Input Pin" - PWM is output only. You are just using the generic GPIO functionality of the pins, and as such you can use any pin.

your exact code works for me so i think th board is the problem.

What misled me is the pin numbers. I was referencing this diagram:

I thought that all the pins were numbered sequentially, so that pinMode(9, ...) would set D6 (09 in the diagram). However, this sets D9. Connecting to the correct pin works fine.

If you're still doing this without a ground connection then it may only appear to be working fine for now.  IT may simply stop working at any time it sees fit based on that voltage reference.

I read the article Majenko commented previously and understand that. IDK whether working on my unplugged laptop proves the concept. Since there are only two grounds, I'm already running out. I am running the receiver and an ESC from the Arduino, but still need to add another ESC, plus LEDs... @Delta_G

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


text:
STM32F103 (Blue Pill) with stm32duino + BME280 + SSD1306 strange behavior
I'm going crazy trying to understand some strange reads from BME280 sensor.
With this code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

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

#define SAMPLES_NUM             100
#define SAMPLES_OFF             256

#define GRAPH_X                 (SCREEN_WIDTH - (SAMPLES_NUM + 1))
#define GRAPH_Y                 16
#define GRAPH_W                 (SAMPLES_NUM + 1)
#define GRAPH_H                 47
#define DATA_X                  10
#define DATA_Y                  0

#define SEALEVELPRESSURE_HPA    1000
#define PRESSURE_HPA_MIN        980
#define PRESSURE_HPA_MAX        1045

TwoWire Wire1(PB9, PB8);
TwoWire Wire2(PB11, PB10);
Adafruit_SSD1306 *display;
Adafruit_BME280 *bme;

void setup() {
  pinMode(PC13, OUTPUT);
  digitalWrite(PC13, LOW);

  delay(500);

  Wire1.begin();
  Wire1.setClock(400000);

  Wire2.begin();
  Wire2.setClock(400000);

  delay(100);

  display = new Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2);
  bme = new Adafruit_BME280();

  while (!display->begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    delay(500);
  }

  delay(500);

  display->clearDisplay();
  display->dim(0);
  display->setTextSize(1);
  display->setTextColor(WHITE);
  display->setCursor(0, 0);
  display->println("Display initialized");
  display->display();

  int b = 0;
  display->println("init bme...");
  while (b == 0) {
    b = bme->begin(BME280_ADDRESS_ALTERNATE, &Wire1);
    display->print("b=");
    display->print(b);
    display->print("; ");
    display->display();
  }
  display->println();
  display->display();

  if (b == 1) {
    bme->setSampling(Adafruit_BME280::MODE_FORCED,
                    Adafruit_BME280::SAMPLING_X1, // temperature
                    Adafruit_BME280::SAMPLING_X1, // pressure
                    Adafruit_BME280::SAMPLING_X1, // humidity
                    Adafruit_BME280::FILTER_OFF);
  }
  delay(5000);
}

void loop() {
//  bme->takeForcedMeasurement();
  float _t1 = bme->readTemperature();
  float _h1 = bme->readHumidity();
  float _p1 = (bme->readPressure() / ((float)100.0F));

  display->clearDisplay();
  display->setCursor(0, 0);

  display->print("T  : ");
  display->print(_t1, 1);
  display->print((char)247);
  display->println("C");

  display->print("RH : ");
  display->print(_h1, 1);
  display->println("%");

  display->print("P  : ");
  display->print(_p1, 1);
  display->println("hPa");

  display->display();

  delay(5000);
}

And if I uncomment //  bme->takeForcedMeasurement(); it wait forever.
I get an obviously erroneous read:
T  : 66.1°C
RH : 100.0%
P  : -1599.7hPa

With this code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

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

TwoWire Wire1(PB9, PB8);
TwoWire Wire2(PB11, PB10);
Adafruit_SSD1306 *display;
Adafruit_BME280 *bme;

void setup() {
  pinMode(PC13, OUTPUT);
  digitalWrite(PC13, LOW);

  delay(500);

  Wire1.begin();
  Wire1.setClock(400000);

  Wire2.begin();
  Wire2.setClock(400000);

  delay(100);

  display = new Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2);
  bme = new Adafruit_BME280();

  while (!display->begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    delay(500);
  }

  delay(500);

  display->clearDisplay();
  display->dim(0);
  display->setTextSize(1);
  display->setTextColor(WHITE);
  display->setCursor(0, 0);
  display->println("Display initialized");
  display->display();

  int b = 0;
  display->println("init bme...");
  while (b == 0) {
    b = bme->begin(BME280_ADDRESS_ALTERNATE, &Wire1);
    display->print("b=");
    display->print(b);
    display->print("; ");
    display->display();
  }
  display->println();
  display->display();

  if (b == 1) {
    bme->setSampling(Adafruit_BME280::MODE_FORCED,
                    Adafruit_BME280::SAMPLING_X1, // temperature
                    Adafruit_BME280::SAMPLING_X1, // pressure
                    Adafruit_BME280::SAMPLING_X1, // humidity
                    Adafruit_BME280::FILTER_OFF);
  }
  delay(5000);
}

void loop() {
  bme->takeForcedMeasurement();
  float _t1 = bme->readTemperature();
  float _h1 = bme->readHumidity();
  float _p1 = (bme->readPressure() / ((float)100.0F));

  display->clearDisplay();
  display->setCursor(0, 0);
  display->println(_t1, 1);
  display->println(_h1, 1);
  display->println(_p1, 1);

  display->display();

  delay(5000);
}

I get perfect read:
24.5
45.7
1009.8

I can't understand the problem.
Wiring it's ok and I can detect on both I2C bus devices address with i2cscanner.

Your question isn't clear: when you uncomment that line, does it wait forever or do you get an erroneous read? What else is different between the 2 sketches?

Sorry sorry if i wasn't clear enough. However if I uncomment it wait forever, otherwise it take erroneous reads. However, I tried, if I change some print, for example a display->print("Temperature:"); before display->println(_t1, 1); , reads changes systematically. It seems like a stack overflow or a memory bad allocation, or something like that...

So basically, if you uncomment that function call, the code waits forever (where does it "wait" exactly? Within the takeForcedMeasurement()? Find out exactly where.). But if you leave the line commented out, you get wrong values. And aside from this, you get unstable behaviour just from changing the Serial.print() statements. Like you said, this is possibly some issue with memory. Is there a reason you're allocating display and bme on the heap? Take them out of setup() and declare them statically in file scope, then see if anything changes.

Yes I tried to declare statically and is not that the problem. I think it wait forever on takeForcedMeasurement() because the same problem, and it not get the reply and wait forever for it.

That's a different issue from the strange behaviour you observed. Does changing the Serial.print() strings still affect the execution?


text:
Load Adafruit GFX bitmap fonts on desktop for pixel-level design
I am designing UI for 160x128 ST7735-based TFT display which will be displayed using Adafruit's GFX library (and the driver in Adafruit_ST7735.h). I am using the default bitmap font (custom fonts don't provide the white-out functionality, causing flicker) and would like to load it in some desktop pixel editor (like Gimp or some pixel-art editor) so that I can work the design out on desktop.
There are many posts about converting regular (TFT, OTF) fonts to the c-style array, I need to do the opposite. If possible, including the scaled variants, so that I have 1:1 corespondence :)
Any tips on this?

As explained here and here the font format in the GFX-library is GFXglyph, you can use the free tool from the second link adafonteditor v1.0.3 on the desktop.EDITOk so its actually decompile the gfx header file to something on the desktop. Take a look at the Adafruit GFX Font Customiser Source can be used as basis for own projects or compiled to the designated OS.

Thanks, but that's the opposite direction. I don't have a problem parsing the GFXGlyph format, but would like to convert it to standard (BDF, PCF) raster font formats desktop programs can use, without writing the converter myself. Adafonteditor is mac-only. I think I will just use standard 5x7 font shipped with x11.

Thanks, the font customiser might be a useful reference.


text:
Edit JSON File on SD Card
I am currently Working on a project, where I save values in a JSON File on an SD Card.
The JSON looks something like this:
{ "ID1":{[[starttime, endtime],
          [starttime, endtime],
          [...]],
  "ID2":{[[starttime, endtime],
          [starttime, endtime],
          [starttime, endtime],
          ...],
...
}

I have to add start and endtimes to IDs, so I have to edit the file.
Is there a nicer/easier/better way than the following?:

Create Buffer (e.g. 512 Bytes)
Read 512 Bytes from file to buffer
Edit/Add Values in Buffer
Save Buffer to another File
Repeat 2. to 4. until end of file
Remove old File and rename new File

I am currently using the ESP32 Core SD.h Libary

you could seek() in the file and overwrite bytes in the file. but not add or remove bytes.

To add data, no, there is no better way. The way you describe is called "stream editing" and is the normal way on low-memory machines. TBH I'd work in lines, not blocks of 512 bytes.

Also TBH I wouldn't use JSON. It's not great (as you see) at editing. Instead a simple CSV format would be better where you can just append data to the end of the file, then collate it later on the computer in excel.

Going by line is a good Idea! I will give it a try. I need a JSON File, because I want to use the data in a React App. The reason why I use the SD Card is in case of a failure I want to be able to retrieve the data. Thanks a lot!

you can use notepad++ text editor to sort a csv file and to add JSON formatting to the columns

react can read csv, you just have to parse it into an array of arrays or an array of objects. you also have enough RAM on the 32 that you can just template the whole file and print it in one go.


text:
How to use this Toggle Switch?
I purchased this toggle switch recently because I want to use it in my project:

But I don't know what to connect up the three pins to and I can't find any information about it online. Nor can I find sample code. Can someone show me how to wire it up and provide sample code please?

Did you read the description? It's basically a push-button toggle switch that connects and disconnects the middle pin from either of the two side switches with every click.

the description suggests that it is a SPDT with center off ... that means that the switch has three states

It's basically a push button. Possible examples depend on what you want to do. As it seems, you simply want to start interfacing it with Arduino, just use it as a normal push button. Use the DigitalInputPullup example, that comes with the Arduino IDE:
Middle pin to pin 2 on the Arduino
One of the other pins to ground (depending on which state you want to be reflected with a HIGH in the Arduino)
The other pin unconnected

Look at these two schematics. The left one is a normal push button. It connects, when pressed and disconnects, when released. The right one is your button. When pressed it disconnects the upper  pin and connects to the lower pin. When released vice versa.  When you don't use the upper pin, your button behaves just like the push button on the left.

simulate this circuit – Schematic created using CircuitLab


text:
Does Adafruit PowerBoost 1000 Charger support data transfer?
As the title says - Does Adafruit PowerBoost 1000 Charger support data transfer?
I mean that if I connect USB on one side to PC and Arduino on other side - can I still program it and get serial monitor communication?
Are the data lines connected??

No it doesn't.
As you can see from the schematic the incoming data lines aren't connected, and the outgoing are wired through appropriate resistors to set the current availability.


text:
Connect multiple pins to same VCC using breadboard
Ok so I am pretty green as far as AVR programming is concerned so bear with me.
I am doing a project with an ATmega32 MCU on a dev board which has 4 VCC pins.
The project includes a GPS, SD card and a TFT display. Currently, the GPS and SD card take up 2 out of the 4 VCC pins for powering themselves up. I have two free left.
The display controller I have is the SSD1289:

I've connected it to my MCU, the VCC pin on the display took up one more VCC pin so I have one VCC left.
I've been reading up and I've found that the LED_A and RD pins need to be connected to 3.3V, that is VCC.
The LED_A pin should also have a resistor on the line connecting it to VCC.
First question - can someone confirm this is the way to connect it?
Second question - Is it possible to, for example, connect the VCC and RD pins of the display to the same VCC using a breadboard? So then I have one VCC left to connect to LED_A pin through a resistor? I don't know if multiple pins can share the same VCC. Will the voltage drop if I connect two pins to it?
Is this safe to do?

can you connect two garden sprinklers to one water supply? http://hyperphysics.phy-astr.gsu.edu/hbase/electric/watcir.html

You have basic misconceptions there:

Vcc is the power input (!) for the Atmega, not an output to provide current to other parts. Your power supply (whatever you use as one) should be connected to every Vcc pin at the same time. Sure, the Vcc pins are internally connected, but the Atmega has multiple of them, so that the needed current does not have to flow through a single pin. Also you don't want to draw the current for peripherals through the Atmega chip itself (which would happen, when you connect the power source to one of them and the peripherals to another). So every device in your circuit, including the Atmega, has it's own Vcc pin, which needs to be connected directly to the power supply. That is ok and correct, as long as the power supply can provide enough current for all components. If it doesn't, you need to buy a power supply, that can.
When connecting device to one pin, the number of devices is not imporant. The current draw is what is important. For example let's take simple digital output pin of the Atmega. It can provide up to 20mA (recommended value; max. 40mA for a short time). We must no exceed that value. So we can connect 1 device, that draws 20mA, or 2 devices, that draw 10mA each. Or 100 devices, which draw 0.2mA each. The number is not important, only the total power draw. The current will drop, when you draw more current, that the source can provide. In that case often the source will be damaged or at least go into thermal emergency shutdown (as for the voltage regulator of a genuine Arduino).

So the Todo for you: Connect every Vcc pin, that you have, directly with the power source.

Thanks for the answer! But I think you may be wrong here with 1)
Here is the datasheet for my board: https://docdro.id/YoZ3ZNp
It says the 4 VCC pins are power output.

Hmm, but those VCC pins are no GPIOs and therefore the 20mA limit does not apply. I assume, the motivation behind breaking out 4 VCC pins is that they can be used to power external devices. The current rating for dupont pin headers is in the order of some amps, so they are not the limit and as the atmega doesn't source the current on the VCC pins, it should be fine to connect even power lines to the remaining VCC pins.

@Machi, why is the link to the datasheet included as an afterthought? ... that kind of information should be included in the question when you write the question  ... chrisl's answer to your question is correct and it remains correct unless you edit your question

Sorry, should've included it right away. Thought it was clear what I was asking from the get go.
Anyways this answers my question now so thanks everybody!


text:
How can I understand which arduino I need to run some code?
I want to build this project (but any other project would give me the same uncertainty):
https://github.com/ltpitt/arduino-n64-controller-library
But I cannot understand which arduino I can buy that will be compatible and also very small / easy to program / cheap.
There are countless possibilities but I cannot understand how can I match available code and compatible hardware.

Code written for an Uno will run as well on a Nano or a standalone atmega328P, if that's your question ? ? ? My concern were rather about the 3.3V signal level. Did not dive too deep into the underlying instructable, though.

I'd need a very small solution that can work with 5v or 3.3v (it will end inside a Nintendo 64).
Would this be ok for this code? https://www.kiwi-electronics.nl/beetle-arduino-leonardo

In this case, the description on Github says specifically that it is compatible with the Uno:

Based on the work in
  http://www.instructables.com/id/Use-an-Arduino-with-an-N64-controller/
  here comes a comfortable library for usage with e.g. Arduino Uno.

If you know in advance that you intend to write a very large body of code, of which this library is only a part, you can anticipate needing an Arduino with more memory at some point, but an Uno will get you a long way there. And, with all due respect, the fact that you're asking this question also suggests that an Uno will be more than adequate.
Genuine Italian Unos just barely exceed U$D 20 and Uno clones are about 2/3 of that price. Some of the clones may not be quite up to quality of the genuine boards, but reputable board makers' products are usually quite good. The best advice I can offer would be to buy a genuine Uno for your first board, both for the most likely best experience starting out, as well as to support the folks who did the upfront work and released the design as open source. Then maybe branch out to other board-makers' products for price, or especially, for added features (assuming those are useful to you) that some of them have engineered into their versions of the product.
Update:

My final goal is to put it into a Nintendo 64 so its size is really
  important. Something like this could be ok?
  kiwi-electronics.nl/beetle-arduino-leonardo

The Beetle's processor, AtMega32U4, has a similar memory complement as the Uno's AtMega328. In fact it has a little bit more RAM than the Uno. It should be quite doable to compile it for the Beetle.

My final goal is to put it into a Nintendo 64 so its size is really important.
Something like this could be ok?
https://www.kiwi-electronics.nl/beetle-arduino-leonardo


text:
DigiSpark External Oscillator
I am trying to set up a PJON SoftwareBitBang network with a bunch of DigiSparks. My setup works well with any other Arduino devices except the DigiSparks. Based on some internet searching I came to the conclusion that it's because DigiSpark doesn't have a built in oscillator.
I bough a bunch of 16Mhz Crystal Oscillators hoping the internet will help me set them up but I couldn't find any resources on how to do that
Does anyone know any resources on how to use an external oscillator on DigiSpark?
Alternatively, can anyone think of any other reason why SoftwareBitBank goesn't work with Digisparks?
Thanks,
Andi

Is "SoftwareBitBang" a library? I see no reason why bit banging shouldn't work and I think the problem probably is a different layer

SoftwareBigBang does support Attiny85/DigiSpark. It is also possible to add external xtal to Attiny85 with the trade-off of losing two precocious GPIO pins, but you can't just add the external crystal without modifying the firmware of DigiSparks. I think you should focus on why SoftwareBitBang doesn't work.

BTW, did you installed the DigistumpArduino core to your Arduino IDE which defines the pin 1 and 2 that the SoftwareBigBang is looking for to communicate with Attiny85/DigiSpark.


text:
My Arduino smokes every time I connect an AC/DC wall adapter to it. Can someone help me to fix it?
I copied the schematic below and when I ran the code from my laptop, it worked well but every time I unplug it to my laptop and connect an ac dc wall adapter, my Arduino smokes. Why does it smoke and how to fix it so that I can connect an AC/DC wall adapter to power my Arduino? EDIT from the comments: My AC/DC adapter has 19.5V DC out.

disconnect the motor ... the arduino voltage regulator does not have enough capacity to run it  .... disconnect the motor red wire from the arduino ... disconnect the top black wire on the relay from the arduino .... insert a battery between the motor red wire and the top relay black wire

is there any way to power this up without the use of my laptop?

@VE7JRO the output voltage is 19.5 V and i am connecting it through the barrel jack

@jsotola can i still use or connect a wall adapter if I already connected it to a battery or no need?

the relay contacts is simply a switch ... use it to turn on the battery power to the motor ... do not connect any part of the motor circuit to the arduino .... the arduino and the wall adapter are electrically separate from the motor and the battery

@jsotola so i can still use the wall adapter to power my sensor?

@jsotola okay thank you very much for the help! appreciate it :)))

19.5V on the barrel connector is too high, especially when powering a motor. It needs maybe half that. The "smoking" part is probably the voltage regulator on your Arduino.

Just as a fun fact. It's called a "Magic Smoke" https://en.wikipedia.org/wiki/Magic_smoke

@StarCat Instead of a 19.5 V on the barrel connector can I use 12 V?

@FilipFranik Thank you for the information, I could really use it!

How will I know how much power supply do i need to make this work

You'll have to know how much current your motor draws. Ideally, you power the motor from a different supply than directly from the Arduino board because the voltage regulator on the Arduino can only deliver a limited amout of current. If you do decide to power the motor from the board, make sure the voltage of the external power supply is not too high (i.e. it needs to be just a few volts above the regulated output of 5V), I would aim for 7-9V at 1 A.

@StarCat so if a use a wall adapter from 7-9 V, it would be enough to power this up?

That should work but you should make sure it can deliver enough current and it would be better to power the motor from a separate supply (or at least not via the Arduino voltage regulator).

@StarCat thank you so much for answering! It helped me a lot!!!!!

As already stated in the comments, the voltage of your power supply is the problem. The Arduino has a linear voltage regulator at the Vin pin. It dissipates the excess voltage as heat. The higher the supplied voltage, the lower the current, that you can draw before it overheats. The regulator on a genuine Arduino should go into thermal shutdown, while the regulators on most cheap clones will just get destroyed.
19.5V is too high for the Arduino. The Vin pin is meant for  6 to 12V max. You need a power supply, that can provide a voltage in that range. Or you can buy a regulated power supply, that directly gives you the 5V, that the Arduino needs.
Also you should be really carefull with powering the motor through the Arduinos 5V pin. Motors can easily draw a big amount of current. When drawing too much current through the Arduino (to be specific: through the voltage regulator or the protection diode), the same as explained above will happen. Only very small motors can be supplied through the Arduino. As you use a relay to control it, I guess the motor draws a lot of current. You need tp connect it directly to a fitting power supply, so that the current for it does not flow through the Arduino.
And always be sure, that the used parts can work with the voltage, that you want to supply, including the motor.

Sorry but can i use a wall adapter without an output of 12 V and still power up the motor and sensor?

What do you mean by without 12V? With what voltage instead. If you only have a supply with more voltage, you need to buy an extra voltage regulator to bring the voltage down. Be sure, that is is a switching regulator instead of a linear one, and that i can provide more that the needed current

I'm sorry I meant with 12V, thank you but is it possible to power all this up with that output? Also how will I know how much output volts does my arduino needs to power this up? Sorry, I'm new to this and i really appreciate your answer

also i would also like to know how will i know the right voltage or power supply to make this work

You need to check, with which voltage your motor can work. Your supplier should have this information. Or - if you have one - look the the motors datasheet. The Arduino needs either 5V on USB/5V pin or 6V - 12V on the Vin pin. Get a power supply, that fulfills the requirements of the Arduino and the motor, and that can provide enough current for both your Arduino and the motor (plus a bit overhead). Then it should work

so if I use a wall adapter between 6V to 12V and instead of connecting the motor to the 5V in the arduino, I connect it to the vin pin? would it work?

Yes, the 6V to 12V supply to Vin and the motor. Of course only if the motor can work with that voltage

Oh okay sir!!!! thank you so much for helping and teaching me, I've learned a lot!


text:
Can two electronic speed controllers be connected to the same ground pin?
I have a setup to read two sets of signals from a radio control receiver using an Arduino NANO: the throttle channel and the rudder channel. With some programming knowledge (which I have) this isn't too difficult, but I need help on the electrical side of things. This is the current setup I have (it works, though I'm told there is the possibility that my computer is acting as a ground for the PWM signal wires from the receiver):

OK, great. I'm able to control the motor programmatically, mix values from the receiver, etc. See this video for what I'm doing. However, this setup leaves some gaps:
Question 1
I actually need two motors for dual thrust. Each motor is to be controlled individually by the program (for asymmetric thrust). Since there are only two grounds on the Arduino, can I plug both ESC grounds to the same pin? Currently, the receiver is getting power from the Arduino, and grounds back. The speed controller grounds to the second ground pin. Diagram below:

Question 2
All that is great, but the NANO is still powered by USB: obviously I'm not putting my laptop in the RC boat just to supply a few volts! Incidentally, both electronic speed controllers (ESCs) have battery eliminator circuits (BECs), usually used to power the receiver. Would I be able to connect one of them to the VIN pin of the Arduino?
I tried something like that, but the Arduino got very hot near the pin, and it smelled. Unfortunately, I don't have my circuit at the time. The Arduino's Amazon page states support for 5V to 12V external power supply. Each ESC can supply 5V at 3A. Maybe there's a way to plug them to make 10V?
Question 3
My idea also calls for three sets of LEDs, which will be lit also based on inputs from the receiver. Can these be grounded to the same wire, like I was suggesting above for the ESCs?

Ground is ground. Whether it's got 1 pin or 100 pins, they are all the same. You can connect as many thing to ground as you need to. Whether you connect them all to one pin or each to its own, ground is ground. Like the ground under your house is the same ground as the ground under your neighbour's house.

@Majenko that effectively sums up the answer. It did work, so great!

You can connect all the grounds together and the circuit will be safe. If the BEC outputs 5V, you can feed it directly to the Arduino's 5V pin. Any more volts and you'll need to feed the BEC output to the Arduino's VIN pin.

Can I safely connect both ESC 5V outputs to the same VIN pin?

While you probably could get away with it, I would not try - 1 BEC supply will be fine. Regardless, all grounds need to be connected.

However, I'm not only supplying current to the receiver, but also to some 6 or 7 other LEDs.


text:
How to connect multiple NodeMCUs and 1 PC over wifi and have PC control NodeMCUs?
I am trying to design a laser tag system using multiple NodeMCUs in the guns. I am trying to figure out how to connect and control them over WiFi. I also need a computer connected that will control the game. I was origionally just thinking I could use the PC as a server that tells all the guns what to do. Im sure this is possible, but it looks very complicated and I dont know a whole lot about theese types of things. So then I was thinking it might be better to have another NodeMCU connected to the computer with USB. That NodeMCU would then act as a WiFi server for the clients(Guns). That way, the PC would only have a GUI for that MCU, and once started the MCU would actually control the game. Is that the best option or is there some easier and simpler way? That seems like the best solution to me. I am just making sure this will work. Are there any other solutions or tips? Here is a basic idea of what would happen when someone shoots someone else.
Gun 1 will send IR signal (Shoot) gun 2.
Gun 1 will tell the server that it tried to shoot gun 2.
Gun 2 tells server it got IR signal from gun 1.
Server will first make sure no other guns were shot accidentally at the same time. If they were, it will determine which gun received the IR signal stronger. That gun will be the one actually shot.
Server will add points to gun 1 score and remove points from gun 2 score on both PC monitor and small screens on guns themselves.
Thanks!

there is no reason why the server would have to decide who shot a target (gun 2 in your example)  ... the decision should be made by the target ... determining an IR signal strength can be a problem ... it would be easiest to award the kill to the first shot and award a kill to each of the shots if received simultaneously .... also, it is pointless to count that gun1 tried to shoot gun2 ... how would you determine that if gun1 misses the target?

@jstola At this point I have tried so many things and researched so many ways of making this work that I cant think right. What I said is more complicated than it would really be. I am just looking to connect 5 or 6 MCUs together in a network, along with a PC. The MCUs will control almost everything by themselves.

All the PC will do is change settings, keep track of score and tell MCUs when to start and stop the game. My main questions are 1, How to connect 5-6 MCUs and a PC together over WiFi and send information between them, and 2, how to make a simple PC program that keeps track of score, tells MCUs when to start and stop, and changes settings. Also, all of the ways Ive seen people communicate over WiFi use a server that broadcasts out WiFi. How can I just use my existing router now that I arent using a server?

Plz tell me how I can do this.

I would not consider it easier to connect a NodeMCU to the PC just to act as a Wifi interface. Most computers already have means of connecting to a network. Wether it is via Wifi or LAN is not important. Every PC has a LAN port on it's mainboard. You could connect it directly to your Wifi router.
Using a NodeMCU as you proposed would mean, that you have to program for 2 platforms: The main logic on the PC and the Wifi communication on the NodeMCU. That does not really make it easier.
The communication depends on your wanted topology. I would build the PC as Server and the NodeMCUs as clients. You can easily create a webserver programmatically with python, for example with Flask, as I have done it once. Though there even might be better webserver modules for python. It is really not that difficult and you already need to write a program for the game logic on the PC,so why not using python. Though of course you could choose any language, that you like. Python is just an easy choice, that I already did.

So i guess my question then is more how to make that game logic on the PC. How exactly do I do this? Could you maybe point me towards a totorial? Thanks!

There is no tutorial, that explains how to write the game logic for your specific project, because it is specific to your project. Choose a fitting programming language and learn the basics of it. Variables, arrays, conditions, loops,... Them write down the game logic as text, convert that into pseudo code and then into real code. We cannot explain more, since the question is so broad

Ok thx, I will check out some languages.

web server? what for? sorry @chrisl, but this answers shows that you shouldn't write an answer to this question

@Juraj Please be a bit more specific about what is wrong with the answer. That would help both the OP and me

the question is too broad and a major part is outside Arduino. simple TCP/IP communication on sockets level or UDP can be used. here a write about Arduino to Arduino https://arduino.stackexchange.com/questions/60819/esp8266-tcp-ip-communication/60821#60821


text:
How can I connect an OLED display to arduino
I'm new on this!
So I want to know if is it posible to connect this oled display: oled display to arduino nano and if is it posible where can I found information of how to learn about connect this type of mini display.
And if you can share some links about good learning site would be cool too!
Thanks!

I think you'll have trouble connecting it, as it does not seem to come with an interface card, just with a bare small pitch connector that will be very hard to solder. It looks like there's no technical documentation, which for me would be a deal breaker. If you're a beginner I would advise against it.

Yes, you can. If you have the adaptor board for it as shown in the video.
The key item from the description to note is the driver chip: SSD1309
That is what you need to know to find a library and connection schema.

Thanks for the answer.
And is it posible to buy a generic adaptor or made one?
Because I ask to seller and the adaptor is to expensive more than 10 times the price of the screen...
Thanks in advance
PD: I find this new oled display that I think it would be better.

No, there's no such thing as a "generic" adaptor. Every display is different. The datasheet for the display should have a schematic for what the interfacing needs are. If there is no datasheet then don't buy it.

Don't do it. It is an expensive display as it is, and it's not made to be easily used with an Arduino, especially without an interface card and 5V / 3.3V conversion. If you want an OLED attached to an Arduino Nano there are displays that are much easier to interface and use.

@StarCat Ah, but it's "transparent".  Gotta charge 10x as much if you remove that back plate...

So this one: https://www.sparkfun.com/products/15173 would be better I imagine?
And of the first one I have the datasheet.


text:
NeoPixel Gradient sweep function

I'm trying to create a function that takes two colours and creates a smooth gradient between them one colour at the beginning and one at the end
I just can't figure the math of mixing them evenly
I'm using neopixel library

I can think of two ways of doing this.
One is to use the H channel of the HSV colour space (as I show in the answer to this question. This would give you a smooth transition between two colours through the pre-defined spectrum of the hue range.
The second is to simply specify two colours and then mix them at different percentages depending on how far along the length you are.
For example, here's a (untested) small function that "mixes" two individual colour channels together and returns the result:
uint8_t mix(uint8_t a, uint8_t b, int pct, int range) {
    if (pct <= 0) return a;
    if (pct >= range) return b;
    return (((uint32_t)a * (range-pct)) / range) + (((uint32_t)b * pct) / range);
}

pct is the led number in your chain, and range is the total number of LEDs.
So you could (hypothetically):
uint8_t red1 = 0, green1 = 255, blue1 = 0;
uint8_t red2 = 255, green2 = 100, blue2 = 100;

for (int i = 0; i < 50; i++) {
    uint8_t red = mix(red1, red2, i, 50);
    uint8_t green = mix(green1, green2, i, 50);
    uint8_t blue = mix(blue1, blue2, i, 50);
    setLedColor(i, red, green, blue);
}

Very clever
However, only one LED lights up, sorry I can't debug it myself :<

My sketch: https://pastebin.com/0fYD6w3y

the sketch belongs in your question as text, not as a link ... please edit your question ... format the code properly using the {} button

The 50 in my example code is the number of LEDs. Obviously you need to tune that to the actual number of LEDs in your setup.

I tried both 8 leds and 50 and 7 counting from 0 but i think that even with more leds in sketch more than 1 led would light up

In the 2nd block of code on this answer, I believe all occurrences of 50 should be a reference to the variable holding the number of LEDs. Without it, you may not be notice the difference between the 8 LEDs depending on your initial color choices.
Also, and I think this may be your main issue -- I use a different NeoPixel library, but I would assume it is likely similar. After setting pixel values, I have to call strip.show() before the LEDs reflect the values I want.


text:
Inductive spikes upset Interrupts
I am using an Arduino Uno to create a kinetic sculpture with magnets and electromagnets (EMs). I have a setup with two externally debounced buttons using resistors,capacitor and CMOS 4584 hex inverter. All non-used inputs of the 4584 are grounded. These buttons deliver a clean signal to the board and trigger the two interrupts which set flags to turn LEDs on or off and trigger one or both optoisolators (OIs).
These connect to another board with a separate 12V supply. One of the OIs turns a BUZ71 power mosfet on and the other triggers a relay which can reverse the polarity of the power to a small 30 ohm EM coil. This can make the magnet suspended above like a pendulum fly away from the coil...
This works perfectly well with the buttons,  the LEDs and the two inputs to the OIs  But when I connect the relay/mosfet board  to the output of the OIs it stops working properly. button 2 turns off button 1  as well as itself. Button one always turns off and on cleanly But button two triggers ISR2 about 10 times and ISR1 a couple of times, leaving both off. If I disconnect the EM coil the buttons work properly. It seems that switching the polarity is somehow interfering with the Uno maybe due to a fairly hefty inductive spike generated by switching the relay. I have tried using shielded coax to the coil. I have 47000 uF caps on both boards. I tried a crude faraday cage around the relay board - no luck. Could the spike be coming through the household power supply somehow even though the Uno board and the relay board have different power supplies and are fully seperated by the OIs?
Here is the sketch I am using:
    //  Coding by Jeremy 070520
//  development for ricochet module

const int coilButton = 2;
const int directionButton = 3;
const int coilPin = 8; //coil driver
const int directionPin = 9; //direction driver
volatile bool coilFlag;
volatile bool directionFlag;
int coilLedState = LOW;
int directionLedState = LOW;

void setup()
{
  pinMode(coilButton,INPUT);
  pinMode(directionButton, INPUT);
  pinMode(coilPin, OUTPUT);
  pinMode(directionPin, OUTPUT);
  digitalWrite(coilPin,LOW);
  digitalWrite(directionPin, LOW);
  attachInterrupt(digitalPinToInterrupt(coilButton), ISR1, FALLING);
  attachInterrupt(digitalPinToInterrupt(directionButton), ISR2, FALLING);
  Serial.begin(9600);
  }

void loop(){
  if(coilFlag)
  {
    coilFlag = false;
    coilLedState = !coilLedState;
    digitalWrite(coilPin, coilLedState);
  }
 if(directionFlag)
  {
    directionFlag = false;
    directionLedState = !directionLedState;
    digitalWrite(directionPin, directionLedState);
  }
delay(1);   //I'm desperate I will try anything ....
} //end loop

void ISR1()
{
  Serial.println("ISR1");
  coilFlag = true;
  }

void ISR2()
{
  Serial.println("ISR2");
  directionFlag = true;
  }

Any chance to get schematic diagram here?

You using freewheeling diodes for the EMs?

A human pressing a button isn’t really an appropriate place for an interrupt unless it’s to wake from a sleep state.  This is a problem you shouldn’t ever even have.  Just poll the buttons and things will work.  You mention in a comment being desperate and will try anything, doing it the normal way might just be worth a try.

I'd suggest building a Faraday cage around the inductive coil. It's probably inducing enough current in all the wires around it to trigger logic level voltages in your signal wires, in the board, etc.
It sounds like the goal is for the coil to fling a magnet away, so you might have to settle for a "Faraday bowl" (an open-topped Faraday cage). Some magnetic field would leak out the top of the bowl, but if you place the control board below the bottom and several feet away it might be enough.
You might need to shield everything separately: Faraday cage around the Arduino. "Faraday Bowl" around the coil. Coax cables for everything, where the power to the coil is in a coax cable that's grounded separately, etc.


text:
Configuring the registers of i2c AD converter ADS122C04
I am not able to set the configuration registers of the TI´s converter chip ADS122C04 using arduino MEGA via I2C.
The code mainly consists of the following:
1-reset the chip (one byte)
2-choose register (WREG) and set register data (figure 59 of the data sheet) for all four registers
3- start conversion (one byte)
In sum, ten (10) bytes are sent in one i2c frame using an array of bytes as follows:
  //--------------------------------------------------------------------

int ADR_THeiz_Austritt = 0x40;                                  //hex Adress of the device

byte InitArray[10] = {6, 64, 54, 68, 10, 72, 5, 76, 112, 8};    //configuration array

 Wire.beginTransmission(ADR_THeiz_Austritt);            //  talk to Slave

 Wire.write(InitArray,10);             // bytes array is sent to slave on ACK handshaking

  status = Wire.endTransmission();     //status as in
                              //https://www.arduino.cc/en/Reference/WireEndTransmission

  Serial.print("Status Initialisierung = ");

  Serial.println(status);

//--------------------------------------------------------------------
status is a byte, which indicates the status of the transmission:
0:success
1:data too long to fit in transmit buffer
2:received NACK on transmit of address
3:received NACK on transmit of data
4:other error
after configuration, when reading the value of e.g. register 0, the result was 0 (default) !!
A second attempt was performed with a for loop
     //--------------------------------------------------------------------

      for (int i=0; i<10; i++)

  {

    Wire.beginTransmission(ADR_THeiz_Austritt);

    Wire.write(InitArray[i]);

    //delay(10);

  status = Wire.endTransmission();

  Serial.print("status Initialisierung ");

  Serial.print(i);                      //print the array element no

      Serial.println(status);          //print the status of transmision

      }

  //--------------------------------------------------------------------

the print function outputs the following: 00, 10, 23, 30,43,50,63,70,83,90 which means:
i=0, InitArray[i]=6, status =0 --> Reset of chip successfull
i=1, InitArray[i]=64, status =0 --> adressing Register 0 successfull
i=2, InitArray[i]=54, status =3 -->  value for Register 0 not transmitted !! (the same applies for all registers)
i=9, InitArray[i]=8, status =0 --> start chip successfull
My question: why am I not able to put a value in the registers? what am I doing wrong?
would appreciate your support!


text:
Atmega Millis with Quartz crystal
I followed https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard this tutorial to program my Atmega 328p to run on a breadboard with a 16 MHZ Quarz crystal and two 22pF capacitor.
I want to program a digital clock without a RTC (code below). So I wrote my code by using millis(), and set the time exactly to the time of my mobile. After two minutes the Atmega was about a quarter minute early, but it seems to stay there. Why is that? Doesen't it use the crystal? Do I have to program it differently? Or will it stay at this time difference and run more or less accurate now?
My code:
#define ZERO 0b01110111
#define ONE 0b00000110
#define TWO 0b10110011
#define THREE 0b10010111
#define FOUR 0b11000110
#define FIVE 0b11010101
#define SIX  0b11110101
#define SEVEN 0b00000111
#define EIGHT 0b11110111
#define NINE 0b11010111
#define SECOND 1000
static int changed = 0;

static int led01 = 1;
static int led02 = 3;

static int led11 = 4;
static int led12 = 5;

static int state = 0;
static int selP = 0;

static int blink = 0;
static int btn_1 = 0, btn_2 = 0;

static long last = millis();
static long tm = 0;

static int seconds = 0, minutes = 45, hours = 13;

static const int DATAH1 = 2, ST_CPH1 = 3, SH_CPH1 =4;
static const int DATAH2 = 5, ST_CPH2 = 6, SH_CPH2 =7;

static const int DATAM1 = 11, ST_CPM1 = 12, SH_CPM1 =13;
static const int DATAM2 = A0, ST_CPM2 = A1, SH_CPM2 =A2;

static const char numbers[10] = {ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE};
void setup()
{
  pinMode(DATAH1, OUTPUT);
  pinMode(ST_CPH1, OUTPUT);
  pinMode(SH_CPH1, OUTPUT);

  pinMode(DATAH2, OUTPUT);
  pinMode(ST_CPH2, OUTPUT);
  pinMode(SH_CPH2, OUTPUT);

  pinMode(DATAM1, OUTPUT);
  pinMode(ST_CPM1, OUTPUT);
  pinMode(SH_CPM1, OUTPUT);

  pinMode(DATAM2, OUTPUT);
  pinMode(ST_CPM2, OUTPUT);
  pinMode(SH_CPM2, OUTPUT);

  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);
}

// main loop
void loop()
{
  long curr = millis();
  tm += curr-last;
  if(tm < 0 || tm > 900000){
    tm = 0;
  }
  last = curr;
  if(digitalRead(9) == LOW){
    if(!btn_1){
      if(state == 0){
        state = 1;
        selP = 0;
      }else{
        if(selP >= 3) state = 0;
        else selP++;
      }
      tm = 0;
      blink = 0;
    }
    btn_1 = 1;
  }else btn_1 = 0;

  if(state == 0){ //ZEIT LAEUFT
    if(tm >= SECOND){
      seconds+=tm/SECOND;
      tm = tm%SECOND;
      changed = 1;
    }
    if(seconds >= 60){
      minutes += seconds/60;
      seconds = seconds%60;
    }
    if(minutes >= 60){
      hours += minutes/60;
      minutes = minutes%60;
    }
    if(hours >= 24){
      hours = 0;
    }
  }else{ //UHR STELLEN
    if(tm>=500){
        blink = blink?0:1;
        tm = 0;
        changed = 1;
      }
    if(digitalRead(10) == LOW){
      if(!btn_2){
        changed = 1;
        switch(selP){
          case 0:
            hours+=10;
            if(hours >= 24) hours -= 20;
            break;
          case 1:
            if(hours/10 < 2){ //in else case zaehlt man die 2. Ziffer nur noch bis 3, da 24 kein Bestandteil mehr ist
              if(hours%10 == 9){
                hours-= 9;
              }else hours++;
            }else{
              if(hours%10 == 3){
                hours-= 3;
              }else hours++;
            }
          break;
          case 2:
            minutes+=10;
            if(minutes >=60) minutes = 0;
          break;
          case 3:
             if(minutes%10 == 9){
              minutes-= 9;
            }else minutes++;
        }
      }
      btn_2 = 1;
    }else btn_2 = 0;
  }
  if(changed){
    led01 = hours/10;
    led02 = hours%10;
    led11 = minutes/10;
    led12 = minutes%10;
    byte str[4];
    str[0] = numbers[led01];
    str[1] = numbers[led02];
    str[2] = numbers[led11];
    str[3] = numbers[led12];
    if(blink){
      str[selP]=str[selP]|(1<<3);
    }
    digitalWrite(ST_CPH1, LOW);
    shiftOut(DATAH1, SH_CPH1,MSBFIRST, str[0]);
    digitalWrite(ST_CPH1, HIGH);

    digitalWrite(ST_CPH2, LOW);
    shiftOut(DATAH2, SH_CPH2,MSBFIRST, str[1]);
    digitalWrite(ST_CPH2, HIGH);

    digitalWrite(ST_CPM1, LOW);
    shiftOut(DATAM1, SH_CPM1,MSBFIRST, str[2]);
    digitalWrite(ST_CPM1, HIGH);

    digitalWrite(ST_CPM2, LOW);
    shiftOut(DATAM2, SH_CPM2,MSBFIRST, str[3]);
    digitalWrite(ST_CPM2, HIGH);
  }
}

I measured the time with a timer and the time between two minutes seems to be exactly a minute. So why the initial difference.

Maybe you could simplify your code by using RTC_Millis(), which already implements the logic of a millis()-based clock.

I don’t see anything in this code that allows you to set the time.  You set it by hard coding the numbers.  That’s fine but it takes some time to compile and load to the board and the board is going to start at that time you hard coded.  If the board doesn’t get to start running the program for a few seconds while you upload then it’s obviously going to be a few seconds off.
It’s going to be nearly impossible to guess exactly what time the program starts running.  Maybe you could set the time for several minutes into the future, upload, and then unplug and wait until exactly that time to plug the board in and start it.  Remember there’s a couple seconds for the boot loader before the program starts to run.  It may take some trial and error.
Or you can write code there that allows you to set the time through the serial monitor or something.

Seems to me like the switch/case construct is about setting the time with push buttons.

Oh ok. I see that part now.  I got confused there.  Delete the answer I guess.

Sorry, I am a IT student and used to write code, not build things - so yeah, thats why my code is that messy :) . So you are saying the global static long last = millis() makes the difference because of the startup time? could I prevent this by putting it at the end of setup()? I could also set it in the first iteration of loop

No that's not what I was saying.  First, if it is global then it doesn't need to be static unless there's a whole lot to this project that you're not showing us.  I was talking about the line where you give seconds, minutes, and hours their initial value.  I thought that was to set the time.  Imagine you gave hours an initial value of 13 and then you don't start the board until 15:00, it would be off by two hours.


text:
Arduino Uno with ESP8266-01 using PubSubClient with secure TLS
In my example, Arduino UNO (ATMEGA328p) connects using the SoftwareSerial library with the ESP8266-01 module.
Then I used the PubSubClient library to connect to the MQTT broker. The connection is to port 1883 and is not encrypted. Everything works fine.
How can this be done to make the connection encrypted (TLS) to port 8883 with the setting of my own CA certificate.
Example:
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>

...

static const char ca_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
)EOF";

...

SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX);
WiFiEspClient WIFI_CLIENT;
PubSubClient MQTT_CLIENT;

...

void setup() {
  wifiSerial.begin(9600);
  WiFi.init(&wifiSerial);
  if (WiFi.status() == WL_NO_SHIELD) {
    printLog("WiFi shield not present");
    // don't continue
    while (true);
  }
  printLog("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  ???   WIFI_CLIENT.setCACert(ca_cert);   ???
  printLog("Connected to AP");
}

if your certificate is signed by well known CA then the AT firmware accepts it. the WiFiEsp library has connectSSL on WiFiEspClient, but the PubSubClient will not use it. create WiFiEspSSLClient client which calls connectSSL() in connect().

if it is a client side private certificate, then you would have to upload it to esp for AT firmware to use it, if the AT fw version you use supports it or build the AT firmware with the key included


text:
Problem HTTP POST request with Thingspeak
I am trying to post a tweet using thingspeak but it is not getting posted. Am I missing something in my POST request or something wrong in my code?
#include <SPI.h>
#include <Ethernet.h>

const byte mac [] = {0x00, 0xC2, 0xA2, 0xE6, 0x3D, 0x57};
const int ledPin = 3;

const char webServer [] = "api.thingspeak.com";
const char webFile [] = "/apps/thingtweet/1/statuses/update";
const char apiKey [] = "xxxxxxxxxxxxxxxx";

EthernetClient myClient;

String msg = "This is my tweet";

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);

  Serial.println("Connecting to Network");

  if (Ethernet.begin(mac) != 1) {
    Serial.println("Connection Failed");

    while (true) {
      digitalWrite(ledPin, HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      delay(500);
    }
  } else {
    Serial.println("Connected to Network");
  }

  // connect to thingstweet server
  Serial.print("Connecting to ");
  Serial.println(webServer);

  if (myClient.connect(webServer, 80) != 1) {
    Serial.println("Failed to connect to Thingspeak");
  } else {
    Serial.println("Sucessfully connected to ThingsSpeak");
    myClient.stop();
  }

  myClient.print("POST ");
  myClient.print(webFile);
  myClient.println(" HTTP/1.0");
  myClient.print("Host: ");
  myClient.println(webServer);
  myClient.println("Connection: close");
  myClient.println("Content-Type: application/x-www-form-urlencoded");
  myClient.print("Content-Length: ");
  myClient.println(msg.length() + 32);
  myClient.println();

  //POST some data
  myClient.print("api_key=");
  myClient.print(apiKey);
  myClient.print("&status=");
  myClient.println(msg);

}

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

}

Raw POST request from reqbin website
POST /apps/thingtweet/1/statuses/update HTTP/1.1
Host: api.thingspeak.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48

api_key=xxxxxxxxxxxxxxxxS&status=new%20test%20msg

Raw response from Reqbin
HTTP/1.1 200 OK
Date: Thu, 14 May 2020 21:24:11 GMT
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Status: 200 OK
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH
Access-Control-Allow-Headers: origin, content-type, X-Requested-With
Access-Control-Max-Age: 1800
ETag: W/"6b86b273ff34fce19d6b804eff5a3f57"
Cache-Control: max-age=0, private, must-revalidate
Set-Cookie: request_method=POST; path=/
X-Request-Id: f9afc383-63d3-4c91-8f15-4d8e4a90f87b
X-Runtime: 0.172584
X-Powered-By: Phusion Passenger 4.0.57
Server: nginx/1.9.3 + Phusion Passenger 4.0.57

1

is the arduino able to connect to the internet?

yes the arduino is connected to the network. Also it is able to connect to the Thingspeak

It's possibly because your Content-Length shouldn't be msg.length() + 32 but rather msg.length() + 34 due to the extra CRLF from myClient.println(msg);; that CRLF isn't needed though. If fixing that doesn't work, you can also try sending the POST manually with a site like this: https://reqbin.com/req/yjok4snr. To verify that your request is well-formed and that the server responds as expected.

I have tried changing the content length but it didn't make any difference. Also by sending the POST request manually I am able to tweet. So I think the request is OK. But why doesn't it work with my arduino code?

When you tested manually, how exact did you get? Did you use the exact same headers, the exact same HTTP 1.0? Speaking of which, try changing that to HTTP 1.1, no reason to use 1.0, I think. Instead of fixing the changing the content length, get rid of the extra CRLF in your POST payload; make that print() instead of println(). And use the X-THINGSPEAKAPIKEY header in your request to specify your API key. Then update your question with the current sketch, if no combo of these works.

I used the exact same header except the HTTP version as the reqbin site didn't let me choose one or atleast I don't know how to specify that (may be in the header??). I have updated the original post with the raw POST request and response. Also when I change the api_key header to X-THINGSPEAKAPIKEY I get a HTTP/1.1 400 Bad Request.

@TisteAndii but thanks for telling me about reqbin and sending the response manually. I learnt something new

@Zaffresky Sure, you're welcome. The Bad Request response seems to originate from a HTTP 1.1 server, perhaps Thingspeak has disabled HTTP 1.0 support. That's why I'd suggest you try making both requests exactly the same; that is, make your Arduino code send the exact same hard-coded string as the one from reqbin that has been proven to work. Once you have that working on Arduino, then slowly substitute stuff back in, like your Connection header and then the calculated Content-Length, etc. Good luck.


text:
What is the meaning of the term FQBN?
So I'm reading the Platform specification and doing some programming and I'm getting the error:
Error missing FQBN

So what does FQBN mean?

My guess: Fully Qualified Board Name
I.e., a descriptor that uniquely identifies a board and its configuration.

That sounds about right. Just couldn't think of the right words for these letters and the net is quite silent about the meaning of it. But thanks and I'll be accepting when the site lets me

I guess it's a modification of "FQDN" - Fully Qualified Domain Name used in networking. If you know FQDN that only leaves the B to interpret, and there's not many things it can be in relation to Arduinos...

@TarickWelling, Arduino started to use this acronym recently with the new Arduino CLI.


text:
How send method POST with JSON? Arduino UNO R3 + SIM900
Why is the server side of php not loading any data from arduino? What did I do wrong?
  String reading="{\"latitude\": 12.983027,  \"longitude\": 80.2594}";
  mySerial.println("AT+HTTPINIT");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CID\",1");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"URL\",\"http://gerro.usermd.net/updateData.php\"");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(1000);

  mySerial.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  toSerial(5000);

  mySerial.println(reading);
  toSerial(1000);

  mySerial.println("AT+HTTPACTION=1");
  toSerial(15000);

  mySerial.println("AT+HTTPREAD");
  toSerial(1000);

  mySerial.println("AT+HTTPTERM");
  toSerial(500);

Result:
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","http://gerro.usermd.net/updateData.php"

OAT+HTTPPARA="CONTENT", "application/json"

OK
AT+HTTPDATA=46,100000

DOWNLOAD

OK
AT+HTTPACTION=1

OK

+HTTPACTION:1,200,55
AT+HTTPREAD

+HTTPREAD:55
array(0) {
}
array(0) {
}
nic ciekAT+HTTPTERM

OK

EDITING
void toSerial(int delay_ms)
  {
    delay(delay_ms);

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

PHP
<?php
var_dump($_POST);
if (isset($_POST['latitude']) && isset($_POST['longitude']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
//code
} else {
echo 'nic';
}

What exactly does toSerial() do? Post all of it.

Check your server first, as far as I can tell, your server return an empty array even when I test it with Postman, so it has nothing to do with your arduino code. It is your php code that doesn't handle the POST request correctly.

@hcheung as it tests with postman it all works and returns data from $ _POST. I think you tested it badly. In the php file there is var_dump ($ _ POST) and hence the result array (0) {}

@TisteAndii I've already edited the post.

on the server php shows that it does not receive CONTENT-TYPE and CONTENT-LENGTH from arduino

Good luck then if you are saying you could get the correct Postman result while I can't even test it correctly. If my Postman test get the same result as your Arduino code, what does that tell you?

@hcheung maybe you haven't enabled the POST method

Trust me, I use Postman on daily basis...

@hcheung however you were right, it was wrong in the php file, instead of $ _POST you had to use file_get_contents("php://input") !

You had to change the php file:
var_dump($_POST);

to:
echo print_r(json_decode(file_get_contents("php://input")));

Thank you !


text:
Using Arduino with through beam sensor on combine harvester
I have a project where I'm trying to capture the output from a through beam sensor (infra red) installed on a combine harvester. I'm not much of an electronics wiz but was hoping it was going to be simple to capture the output from this sensor whilst not interfering with the operation of the sensor as far as the combine harvesters electronics were concerned.
The receiver component of the sensor has 3 wires, ground, 12v supply and output (sensor) lead. If the receiver can see the transmitter the voltage on the sensor wire is 5v when it cant see the transmitter its voltage is 1.5v. Strangely if I remove the sensors from the combine and power them on the test bench, the sensor will pass the powered voltage i.e if supplied with 12v then the receiver will pass 12v on the sensor wire if it can see the transmitter. I think the combine electronics are doing some trickery way beyond my understanding BUT that's fine, all I want to do is capture the pulse from the sensor and pass it to an Arduino without interfering with the combines electronics.
I have tried a couple of setups to no avail this is my last attempt but I cant get a signal from the sensor. I'm not sure the diode (D1) is required but as I had it I added it. In a test environment I can add 5v through R2 and the PC817 triggers and I pick a pulse up on the Arduino. All grounds are linked and the Arduino is powered from the 12v coming from the ecu.

simulate this circuit – Schematic created using CircuitLab
Is there a clever bit of circuit or component which I can use to steal the pulse from the through beam whilst not interfering with its operation as far as the combines systems are concerned?
Any help appreciated with regards to how to properly design a circuit and how to make this work. I have been reading about op amps but not sure that will sort the problem.

The diode should not be needed, since the optocoupler has already an LED on that side incorporated, which is also a diode. Are you sure, that the signal pin can provide the needed current for the optocoupler? The resistor would cap the current at about 18mA, but can the signal pin provide that? You write, that the Arduino is powered from the Combine ECU and the grounds are also connected. Why do you want to use an optocoupler then? For keeping the voltage down a 5V zener diode and a resistor in series would be easier I think.

Thanks chrisl. To be honest I don't have a clue whether the signal pin can supply the power. I suspect not as I cant get any reading. Would the zenor diode circuit take less power? you wouldn't have a basic schematic on how to wire one up so I could give it a go?


text:
Print connection password typed by user on NodeMCU Lua ESP8266 ESP-12E
I want to make a WiFi Access point created with the ESP8266. Let's say that the SSID is 'net_work' and the password is '12345678'.
When a client tries to connect with a wrong password, I want to print that wrong password in the serial console. But nowhere in the docu I can find an event listener or something to do this... The only thing i can find in the docu is how to start the AP and wait for a successfull connection.

You can't print the password because you never know the password. The AP is never sent the password.

You can't.
The password does not exist.
In short:

The password is used to create a key
The key is used to encrypt the connection
If both ends agree on the encryption then it's "connected" and packets can travel back and forth.

There is no password for you to print, only the fact that encryption didn't agree.
It actuality it's more complex than that, but that's the rough outline of how it works.

Thanks for your answer. Maybe a question that does not belong in this topic, but do you know a book or a search term where to learn such deeper understanding about networks, connections and protocols?

https://www.ietf.org/standards/rfcs/


text:
very small PWM when timer says zero
I'am getting a little PWM signal when my potentiometer is at zero and OCR2B always reads zero on the serial monitor.  My LED has low forward voltage but I still get a little PWM on the pin when I prob it. I use timer 1 and it works good. I have a picture of the scope.

#include "RTClib.h"
RTC_DS3231 rtc;

#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analog0(A0, true, .001);

unsigned int nowHour;

int analogOutPin3 = 3;
int sensorValueTimer2Pin3;

long z;

int analogOutPin9 = 9;
int analogOutPin10 = 10;

void setup() {
  Serial.begin(9600);
  //===============mode 5 pin 3,11==================//
  TCCR2A |= (1 << COM2A1);
  TCCR2A |= (1 << COM2B1);
  TCCR2A |= (1 << WGM21);
  TCCR2A |= (1 << WGM20);
  TCCR2B |= (1 << WGM22);
  TCCR2B |= (1 << CS22);
  OCR2A = 249;   //1KHz frequency
  TCNT2 = 0;
  //====================mode 5 pin 3,11==============//

  pinMode(3, OUTPUT);

  rtc.adjust(DateTime(2014, 1, 21, 7, 0, 0));
}

void loop() {
  DateTime now = rtc.now();
  nowHour = now.hour();
  analogWrite(9, LOW);
  analogWrite(10, LOW);
  analog0.update();
  sensorValueTimer2Pin3 = ((analog0.getValue() * 249L) / 1024);
  if (nowHour >= 7 && nowHour <= 21) {
    z = sensorValueTimer2Pin3;
    OCR2B = z;
    Serial.println(OCR2B);
  }
}

My mistake, it wasn't actually in mode 5, it was in fast PWM, I changed it to phase correct and that worked, it turns off.

"My LED has low forward voltage" - what does that have to do with PWM? Hope you're using a resistor for the led.

When analogWrite writes 0 or 255 value, it actually disables PWM output and sets the output to 0 or 1 correspondingly (maybe just one of them).
That's because there is just 256 values, but with both fully off and fully on PWM you'll need 257 values to archieve it.
If you're using direct access into OCRx, you have to make a choice if you want to have not fully on pwm or not fully off pwm (by setting polarity with COM2Xx)
Btw, you should clear TCCR2A/TCCR2B as all of the timers are configured by Arduino core to be running and prepared for the analogWrites...

Pretty sure the data sheets mention a spike when trying to attempt 0% or 100% PWM via Fast PWM mode. As per KIIV you should set the pin to High or Low for either extreme of PWM duty.


text:
DHT11 is returning nonsensical values
I am trying to get humidity and temperature readings (eventually to trigger a misting system), but the values keep returning as 0C and 0%humidity (in general).  Originally, I was using an am2320 sensor and using the analog pins.  Here, I used the following code:
#include "dht.h"
#define dht_apin A2 // Analog Pin sensor is connected to
#define MIST 7
#define LIGHT 2

dht DHT;

void setup(){
 pinMode(MIST, OUTPUT);
 pinMode(LIGHT, OUTPUT);
  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);     //Wait 5 seconds before accessing sensor again.

  }

  //Fastest should be once every two seconds.

// end loop()
}

Thinking the sensor may have not been working, I tried using a different sensor (DHT11), and following the tutorials got the same result using this code:
#include <dht11.h>
#define DHT11PIN 4

dht11 DHT11;

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

}

void loop()
{
  Serial.println();

  int chk = DHT11.read(DHT11PIN);

  Serial.print("Humidity (%): ");
  Serial.println((float)DHT11.humidity, 2);

  Serial.print("Temperature (C): ");
  Serial.println((float)DHT11.temperature, 2);

  delay(2000);

}
// end loop()

The Arduino is being powered by a wall wart and is also connected to my computer via USB (I read that sometimes the USB doesn't supply enough power).  The weird part is that for about 1 minute I got reasonable results (humidity ~50%, temp 22C).  Then, I tried adding an if loop to turn on an LED if the humidity dropped below 60% (thinking I could use the same code to operate a relay to turn on a misting system).  The LED lit up, but the readout went back to the 0%humidity and 0C.  I have since deleted this loop but cannot seem to get reasonable measurements.  If I change the signal pin, I sometimes get a new readout 255% humidity and 255C, but I haven't been able to repeat this reliably.
For the wiring:  S to pin, + to 5V, - to GND
Note:  I have tried every analog pin and "regular" pin, so the code may designate something that is different in my picture.  When testing, I have triple checked that the signal pin in the code is correct for my wiring configuration.  I've also tried with a different Arduino with the same result.  I'm pretty new at this, but the code is pretty much copy-paste and there are only 3 wires.  I've read that there are many DHT libraries, so I'm thinking my issue has something to do with that, but I have no clue how to judge the appropriateness of a library for my application.

[[[[[[[[[[[[p

Does your DHT11 board has a pull up resistor on it? The Data pin requires a pull-up resistor (4.7k would be okay) to 5V.

Have you tried a different library, to rule out hardware issues?

You need to add the following line of code in the setup() function:
    dht.begin();

Connect the sensor as in this diagramm (including a 10k resistor!):

Watch the empty connector opposite to your breadboard plug-in
and use the following test sketch with this library:
// Example testing sketch for DHT humidity/temperature sensor

#include "DHT.h"

#define DHTPIN 4     // Digital pin connected to the DHT sensor

#define DHTTYPE DHT11   // DHT 11

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

2 issues:  1.) The code is giving an "error compiling for board Arduino" (full error message at bottom)  2.) I ony have 3 pins to connect, not four.  Should I try a resistor on the signal pin?
DataSheet https://www.velleman.eu/downloads/29/vma311_a4v01.pdf       Full error code

In file included from LIBRARY LOCATION/DHT_sensor_library-1.3.8/DHT_U.cpp:15:0:
LIBRARY LOCATION/DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory
#include <Adafruit_Sensor.h>
      ^~~~~~~~~~~~~~~~~~~

compilation terminated.
exit status 1
Error compiling for board Arduino Uno.

@sumbody32point5 do you see any resistor on the sensor's breakout board? If no, then add one between signal and Vcc.

You need the additiona llib installed its asking for - read the error message: Adafruit_Sensor.h: No such file or directory Add the Adafruit_Sensor lib Install it with IDE via lib manager

@Codebreaker007 Sorry that was dumb of me - got the library.  The output is now "DHTxx test!    Failed to read from DHT sensor!" There is a resistor on the breakout board, so I don't think that is the issue.  Just to be sure, I measured the resistance berween VCC and data line and got about 10Kohms.  I'm using pin 4 as in your code and tried on other pins as well. I got one reading where the output was "Read from DHT sensor," (one single line) but then it went back to "Failed to read from DHT sensor."  Is there a way to use a multimeter to verify eveything is working?

also I measured 0.13mA in the signal wire so I would think that meant that data was being sent

If your sensor is soldered onto a pcb it might be a cold solder blob or a non connecting pin on the breadboard. You could try to directly hold the signal wire to the sensor and test. If that works check the soldering or pin connections. A defect sensor is the least possible solution.

I think that might be it - I couldn't get a real reading, but I the output changed from "failed to read DHT sensor" to "DHTxx test!" but then went back to the original output.  The sensors are pretty cheap - I might get a second one, try the same configuration, and if it works try my hand at resoldering the original (I'm assuming I will probably mess it up).  I really appreciate your help and patience @codebreaker.