button connection without connection to 5V pin There are two types of tutorials for buttons:

I don't understand how a button on the first image works. Do we just hope that there is some non zero voltage and hope its enough? I think the first image is really bad, but can't explain why.

There is a pullup resistor you don't see in the diagram because it is internal to the Arduino. I have added it in red. To make pin 7 an input, you can write:
digitalWrite(7, INPUT_PULLUP);

, which not only makes the pin an input but also engages the internal ~20K pullup  resistor.
So, you're right about the first diagram - it looks like the pin is left floating. Without the code, or an explanatory note, the pullup resistor isn't documented. In such a diagram, once you are familiar with the processor and know that there are optional pullups on the pin-drivers, you can assume that the optional pullup will be used.

Update: I drew in the resistor assuming the red rail was connected to 5v - I should have drawn that in, too.


What is the type parameter on the NRF24NetworkHeader member Link of the member
What is the character parameter in the above member of the class NRF24Network
I cannot understand the use of it.

It's to identify the type of packet.  Apparently that code supports types of 0-127, and I guess (impossible to tell without digging into the code) that what you use them for is entirely up to you.  Basically it would typically define what is in the rest of the packet - again something which is up to you.


How do I use a i2c port expander to read buttons with pull ups and inverting the resulting uint16_t? I am using a mcp23017 to read button presses for my joystick project and am using the internal pullup to minimize complications. Is there a way to invert all the bits in the uint16_t so i can send the values as normally off?

I'm using this Adafruit library.

And the reading code: uint16_t buttons = mcp.readGPIOAB();

The inversion operator in C++ is ~.

Serial.print(buttons, BIN);
Serial.print(~buttons, BIN);


Why doesn't pin 19 work when powering the EzSBC Esp32 board from batteries? I recently got an ESP32-01 Breakout and Development Board from EzSBC.com.  It is advertised as a board specifically designed for use with batteries because of it's low current draw when in sleep.

As a test I loaded the basic Arduino blink sketch onto the board using pin 19 as the built in test LED.  When I power the board from the computer through the USB connection the LED blinks as expected, but when I connect a battery accross VIN -> GND nothing happens.

What am I doing wrong?

There is a subtle design choice in this board that took be hours to figure out.

According the connection schematic the blue leg of the LS3528RGB LED is connected to IO19 through a 1k resister (R2-1).  However the power leg is connected to Vusb not 3.3V like the other RGB LED.  This means that the LED connected to IO19 is only usable when the board is connected through the micro-USB port and not when connected directly to battery.

This can be useful for programmatically reading whether the board is running on battery or USB.


How to combine two different sensor sketches to one complete sketch? How to combine two different sensor sketches to one complete sketch for a complete circuit that attaches to one Arduino Uno?

Sharp Dust Sensor

int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

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

void loop(){
  digitalWrite(ledPower,LOW); // power on the LED
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin); // read the dust value

  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH); // turn the LED off
  delayMicroseconds(sleepTime);

  // 0 - 5V mapped to 0 - 1023 integer values
  // recover voltage
  calcVoltage = voMeasured * (5.0 / 1024.0);
  dustDensity = 0.17 * calcVoltage - 0.1;

  Serial.print("Raw Signal Value (0-1023): ");
  Serial.print(voMeasured);

  Serial.print(" - Voltage: ");
  Serial.print(calcVoltage);

  Serial.print(" - Dust Density: ");
  Serial.println(dustDensity); // unit: mg/m3

  delay(1000);
}

MQ-135 Sensor

int airquality = A2;
void setup()
{
  Serial.begin(9600);

}
void loop()
{

  int sensorValue = analogRead(A2);
  Serial.print("Air Quality = ");
  Serial.print(sensorValue);

  Serial.print("*PPM");
  Serial.println();
  delay(1000);

}

I will leave a simplified answer and I would recommend to read https://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/ or similar to get a understanding of how to code.

An Arduino sketch has a structure.

Initialising values
A void setup() this code only run once the MCU is started
A void loop() and this code runs continuously.

So to merge two sketches you need to combine the code that is in the same sections and of course avoid duplicate code and ensure that you have unique variable names

Sharp Dust Sensor

int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

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

MQ-135 Sensor

int airquality = A2;
void setup()
{
  Serial.begin(9600);
}

Combined code

int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2
int airquality = A2;

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


Question on pin management using PCA9534PW IO Extender There is an IO expander PCA9534PW, Arduino UNO. I don’t really understand how I can manage this expander using UNO over I2C.

I found an example, but here is the reading mode.

What I need:
Set the IO0 pin to exit mode,
set the HIGH / LOW level to IO0.

In the datasheet, I just realized that to enter the settings mode - you need to write Wire.write(0x03).
How can I do it?

You set the pin mode by setting the configuration register.

Wire.beginTransmission(0x20);
Wire.write(0x03);                   // Configuration Register
Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
Wire.endTransmission();

Then write the output port register with HIGH and LOW.

Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x01);                   // IO0 HIGH
Wire.endTransmission();
delay(500);
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x00);                   // IO0 LOW
Wire.endTransmission();

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.


Charging Li ion cell using arduino 2days back I opened my cousin brothers laptop battery as it was a spare one left unused over a year.
I disintegrated it and found 6x 18650 batteries when I checked them with voltmeter individually I found that 2 were dead I.e.0V and 2 read 2.15 V and the last two read 1.5V. I thought of making a power bank using them individually. The battery are ideal for a power bank because they have 2200ah capacity. I need a circuit to charge it. I thought of chraging it with arduino. But how?
To get the datasheet just search "lr1865ah" in google and click the one and only pdf link that is the cell's datasheet. I need the charing circuit using arduino.

There is a far easier (and safer) way to charge them without using an Arduino. Over-voltage is an issue and another crucial factor with the 18650 batteries is to not let the voltage drop below 2.5 volts when you are dis-charging them. There is a simple "Charge/Discharge Board Module for 18650 Lithium Batteries" that sell for approx. $1 US:

http://www.ebay.ca/itm/2in1-1A-USB-Charge-Discharge-Board-Module-for-18650-Lithium-Battery-Phone-Bank-/302039028674?hash=item4652edd3c2:g:bDkAAOSw9NdXrBoE.

The board has a "fast charge" current of 1000 mA until the battery reaches 4.2 volts, then it switches to a "trickle charge mode". The circuit board also stops current flowing out of the battery once the voltage drops to 2.5 volts. Most of the older charger boards do not have this feature and it's almost as important. It also has a "over-current" protection current of 3.0 amps in case you try to draw too much power from it.

The circuit board has a mirco USB connection on it but be VERY careful before you plug it into a computer USB port. My old MacBook only provides up to 500 mA at each USB port, half of what's required.

The circuit board is 0.700" X 1.050". Here is a picture of it:


Homemade fan - motor madness i hit the forums again with my homemade fan idea, this time i got the right servo. everything works fine until i try turn up to the 2nd speed of the servo, the buttons just go mad and the response in the serial monitor is ridiculous. I press the button once, x goes to 1 the motor starts spinnin' at its lowest speed, all fine, i hit the button one more time and "x" goes mad, in the serial monitor it shows that it goes to infinte, it just adds and adds and adds and never stops. Any suggestions? I appreciate all the help you guys gave me so far and I'd really like to finish this project

Here's the code:

const int button1Pin = 2;
const int button2Pin = 3;
const int ledPin1 = 13;
const int ledPin2 = 12;
const int ledPin3 = 11;
const int motorPin = 9;

int x = 0;
int button1State = 0;
int lastButton1State = 0;
int button2State = 0;
int lastButton2State = 0;

void setup() {
  pinMode(motorPin, OUTPUT);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    int Speed1 = 50;
    int Speed2 = 100;
    int Speed3 = 200;
    int Speed4 = 0;
    button1State = digitalRead(button1Pin);
    button2State = digitalRead(button2Pin);

     if (button1State != lastButton1State)
     {
        if (button1State == HIGH)
          {
             x = x + 1;
            Serial.println("on1");
            Serial.print("Speed:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off1");
          }
     }

    if (button2State != lastButton2State)
      {
        if (button2State == HIGH)
          {
            x = x - 1;
            Serial.println("on2");
            Serial.print("Speed:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off2");
          }
      }

lastButton1State = button1State;
lastButton2State = button2State;

  if( x == 0 )
    {
      analogWrite(motorPin, Speed4);
    }

  else if(x == 1)
    {
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      analogWrite(motorPin, Speed1);
    }
   else if (x == 2)
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);
      analogWrite(motorPin, Speed2);
    }
   else
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, HIGH);
      analogWrite(motorPin, Speed3);
    }
}

When debouncing buttons it is easiest to think of a 4 state machine.

The button is open and you will not jump to the next state until you see the button closed.
You saw the button closed.  Now you need to wait until the button stops bouncing open and close.  After about 100ms, if the button is still closed, jump to the next state.  Otherwise go back to state 1.
You are sure the button is closed.  Do the stuff you want to do when the button is pressed.  Now wait in this state until you see the button is open.
You saw the button open.  Now you need to wait until the button stops bouncing open and close.  After about 100ms, if the button is still open, jump to the first state.  Otherwise go back to state 3.

It is good practice to code this up.  However, there is an existing Arduino (de)bounce library to do this for you.


UART communication - Serial is always empty I have a payment terminal which uses UART (or simply speaking Rx, Tx, Gnd pins) and I have an Android tablet app which is connected to the terminal using USB to DB9 adapter based on PL2303 chip. The Android app works well and it uses https://github.com/felHR85/UsbSerial to support serial communication. The protocol is very simple, basically Android sends strings like "REQINFO,4", "L2,xxx,xxx,*" etc. and recieves back a string statuses.

I'm trying to replace Android app with Arduino UNO, for which I naively assumed would be enough just to connect Tx,Rx of the terminal with Rx,Tx pins of the Arduino and also to connect Gnd pins. But I can't get it working. The only thing I noticed is when I connect Arduino Rx to terminal Tx, the terminal's screens briefly shows "Connecting..." but that's probably because it detects some incoming voltage. When it comes to reading Serial (or also I tried SoftwareSerial) nothing is ever returned.

String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
    } else {
      data += c;
    }
  }
}

So do I miss anyting in order to have a proper communication? Thanks.

There is already an answer and comment about possible hardware / flow control issues, so this answer is only dealing with your Arduino sketch. Iv’e added a couple of print statements and the FreeMemory library to test your sketch.

#include <MemoryFree.h>
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    } else {
      data += c;
    }
  }
}

When I repeatedly enter the following text in the serial monitor "1234567890", here is the results of the print statements:

REQINFO,4
1234567890
freeMemory()=1770
1234567890
freeMemory()=1770
12345678901234567890
freeMemory()=1760
12345678901234567890
freeMemory()=1760
123456789012345678901234567890
freeMemory()=1750
123456789012345678901234567890
freeMemory()=1750
1234567890123456789012345678901234567890
freeMemory()=1740
1234567890123456789012345678901234567890
freeMemory()=1740
12345678901234567890123456789012345678901234567890

Every time you receive new data, it is appended to the data string, causing the string to grow and available memory to disappear. Using the String object should be avoided.

Here is a simple sketch that uses a char array as a buffer for the incoming data:

// Set the buffer size to accomodate the largest
// "chunk" of data you will be receiving.
const byte bufferSize = 64;
char inputBuffer[bufferSize + 1];

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

void loop(){
  if(Serial.available() > 0){
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    Serial.print("inputBuffer=");
    Serial.println(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}


Measure position of gear with arduino So, my plan is to be able to turn a motor, with a gear on the end, for a certain amount of gear teeth then stop it. I can’t find a data sheet for the motor but it is very fast, brushed and DC. I was thinking putting something like this below the gear so when a tooth goes past, it turns on and off. Like I said before the motor is very fast (faster then being able to see the teeth as it spins)  and I don’t think the arduino will be able to read that kind of speed with digital read, I may be wrong. Any suggestions would be appreciated. Thanks.

EDIT:
The motor runs off 2 cell or three cell lipo which is 7.4-11.1v, it’s maximum current is 20 amps.

Edit: For anyone wondering how to use the sensor, the datasheet is here and it shows the positions of the collector, emitter, anode and cathode.

If memory serves, the clock speed of an arduino Uno is 16Mhz. Some are faster, some much faster and a few are slower.

Most assembler instructions take around 1-3 clock cycles. A few take more. Assuming an average of 3 ticks per instruction, that translates to executing over 5 million instructions per second.

So, unless your motor is approaching supersonic speeds, the arduino should be able to "keep up" with polling your motor's sensor in your loop() function.

If you are doing a few other things in your loop, you might consider using an interrupt to trigger some code when the motor "activates" the sensor. In this case you will unlikely need to worry about the speed of the CPU at all. When using an interrupt, you do not need to worry about polling the state of your sensor inside the loop() function.

Always remember to keep the code in your interrupt service routine as short and fast as possible. In this case, probably you would just turn off the motor and return when the interrupt is triggered.

Having said all of that, you will still need to do some work to get the most appropriate implementation as only you know what other things you need to take into account at this time.

One other thing to note is that a single high level instruction will normally equate to more than one assembler instruction. Even a simple statement like int x = 1000; will be more than one assembler instruction and thus take more than 1 clock tick. However, if memory serves, the individual instructions generate to execute x = 1000 will all take just one clock tick.

Others will vary the amount of instructions that are generated to execute them. For example

float x = 1.0;
x = x + 2.0;

will likely take more instructions to execute than it's integer counterpart:

int x = 1;
x = x + 2

I hope this helps and enables you to try controlling your motor via Arduino. If not, you can always ask a more specific question later.


Altering SoftwareSerial to transmit more than 1 byte at a time I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.

One of the really good suggestions I have heard is to use Manchester encoding on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I assume.

Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems?
Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.

size_t SoftwareSerial::write(byte* b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

//Doubtful of this loop ------------------
for(int i = 0; i < 128; i++)
{
  if (inv)
    b[i] = ~(b[i]);
}

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);
for(int j = 0; j < 128; j++)
{
  // Write each of the 8 bits
  for (long i = 8; i > 0; --i)
  {
    if (b[j] & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b[j] >>= 1;
  }
}
// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

Here is the original function.

size_t SoftwareSerial::write(uint8_t b)
{
if (_tx_delay == 0) {
  setWriteError();
  return 0;
}

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

if (inv)
  b = ~b;

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

The serial buffer can only hold 64 bytes at a time, but I am using the following code, courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.

So far you have asked a lot of questions about your project which uses SoftwareSerial to send a lot of bits:

How to transmit more than 1 byte continually?
Basic Serial Transmission Protocol
Synchronization and Implementing hamming code on Software Serial
Encoding clock signal into linear block codes
How to fix baud rate when hardware capacity has a low limit?
Unable to tell if error is from receiving or transmitting end
Read function in Software Serial

And now we have another one (this question).

I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.

In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.

To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is 128 * 10 * 104.17 µs = 133.338 ms.

To use your system you need 1024 bits plus one start and stop bit, so that is 1026 * 104.17 µs = 106.878 ms.

So far you have only saved 26.46 ms.

You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?

Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for 10 * 104.17 µs = 1.0417 ms. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you millis and micros. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.

As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an 8-bit byte. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.

Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of 1024 * 104.17 µs = 106.670 ms between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.


How can I tell which pins I will have left available by looking at a shield? I'm very new to Arduino and came to a point where I'm interested in playing with shields, such as LCDs.

For example, I really like the looks of "LCD 1602 with keypad" module, but it seems to be using a lot of pins.

By looking at a module / shield, how can I tell (or at least estimate) which pins will be used and which ones I will have left if I stack them with my Uno or Mega without printed schematics?

If you look in the 'Tutorials' section of this page you can see the pins used. All of the buttons come through in one analogue input and you'll need a further 7 digital I/O pins. So 8 in total which would leave 5 analogue and 4 digital (I think) pins on an Uno.

As for how to tell which ones, does it matter in advance? I would just map the I/O in the sketch to suit. If you need to plan that far in advance though, it seems that J5 in this schematic shows which pins travel through the shield (i.e. are available to use in conjunction with the shield). Also J6 shows the 5 remaining analogue pins.


Preprocessing problem I've a little problem, I'm trying to create a library with processor variables for tune it.

So in .ino I declared my preprocessor var, but preprocessor variables appear not defined in my library. (Notice that I've create a folder test/test.h in libraries directory of Arduino IDE)

Some code to reproduce the problem :

test.ino :

#define TEST

#include "test.h"

void setup() {}
void loop() {}

test.h (edited, reverse error message, this is solution)

#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

If I compile it, I fall on #error "NOT DEFINED".

Somebody with an idea ?

Have a good day

The code is working properly. You have mixed up your error messages. The code should be:

#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

UPDATE: The question was edited after the time of this answer to correct the mixed up error messages.


Help Troubleshooting L298n connected to dc motor I am relatively new to Arduino, and I am trying to power a DC motor with the L298N dual H-Bridge. I have done as follows:
I am powering everything with the Arduino that is connected to the PC. (I know this isn't ideal, but I don't have a better power supply yet)
I connected the 5V output from Arduino to the 12V terminal of the L298N, and connected it to the Arduino ground. The red light from the L298N shines brightly.
Then, I connected the IN3 and IN4 pins to the Arduino digital pins 7 and 8, respectively.
Finally, I connected the Out 3 and Out 4 to my DC motor, but it doesn't turn at all. I use the following code:

int In3=7;
int In4=8; //idem para In2

void setup() {
  pinMode(In3,OUTPUT); //avisa que nuestros pines son todos outputs
  pinMode(In4,OUTPUT);

  digitalWrite(In3,HIGH);
  digitalWrite(In4,LOW);
}

void loop() {

}

For the time being I decided to not use the PWM, so that I can start simple. I tried changing all cables and even the motor, but it just won't rotate. The L298N is brand new, so it's unlikely that it is damaged. What could I try next?

I realized that I had the jumper disconnected from the ENB pins, which immediately solved the problem when I reconnected it, so it is now fixed!


Wifi101 ad-hoc network I've reviewed the WiFi101 library but have found no way to make the 101 an ad-hoc network.  Am I missing something?  I'd like to be able to emulate the RedFly example:
http://notebook.kulchenko.com/embedded/storing-wifi-configuration-in-eeprom-on-arduino

Can the 101 become an ad-hoc network?  I understand the security problem with the ad-hoc capability so it would make sense that Arduino prohibits it.

Apparently you can have an ad-hoc network, you can see the example on the github here:
https://github.com/arduino-libraries/WiFi101/blob/master/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino

It shows how to create an open ad-hoc network, for a secured one, you might need to check the datasheet + the method implement "beginAP".


Connect to ch340 on MacOS Mojave I recently upgraded my MacBook Pro to Mojave. Now I'm not able to connect to my Arduino board with ch340g usb-to-serial chip. It is a Arduino board with AtMega 328 and ESP8266 integrated. I downloaded the drivers from the Chinese website for the ch340 and also removed old installations, like some tutorials tell me. I just can't get a /dev/cu.* port (besides the /dev/cu.Bluetooth-Incoming-Port.

I do have an external FTDI usb to serial board. I didn't get to it to try to connect it.

Does someone know how to get the ch340 to work on MacOS Mojave, or as a last resort: use the FTDI to program/monitor the Arduino board?

Ok, this is the solution for me:

remove all old drivers:

sudo rm -rf /Library/Extensions/usbserial.kext
sudo rm -rf /System/Library/Extensions/usb.kext

Now reboot the computer.

And then (very important, because it took me 10 cables to find the right one) use a fully connected cable ;-)

Now I have these ports:

/dev/cu.wchusbserial1410
/dev/cu.usbserial-1410


How to program an empty Mega2560 with an Arduino sketch? I am writing code on Arduino mega. My current code is working fine. However, I'm not using all the pins.

My question is:

I have the hex file for my code and I can purchase a Mega2560 MCU. Is there any way to upload the hex file to it and how?
What are the circuits I would need to to build?
Eagle files of the Arduino mega are available here. Is this circuit more than enough?

If you buy an empty mega2560 IC. It won't contains any bootloader.
That means that you need an extra circuit, a programmer, to upload your HEX file into your MCU. "When to use the bootloader" questions link

But, if you buy your mega2560 from an Arduino provider, you should be able to order the MCU with the arduino booloader already programmed. Then a simple serial link from your PC to your MCU will suffice to program the MCU with your Arduino sketch using the Arduino environment. You could clone the serial part that you have on the Eagle files of the original Arduino to do this.

In summary:

Programming an empty chip requires a programmer
Programming a chip that has a booloader requires either a programmer, or a simple serial link.

You may also use another Arduino with the suited sketch as a programmer and use it for programming another empty MCU. There are examples of this on the web.


Custom sleep function for Nextion I have a Nextion 7 inch enhance type display.
I have enabled sleep using thsp = 120 and thup = 1 line of code. Now display become sleep mode after 2min, if there is no any touch event.

But, this sleeping is completely turn off the display.

I have several pages and I want to reset to a specific page, if there is no any touch event in any page instead of sleep function.

Greatly appreciate if someone can give a solution for this.

I solved the problem using a Nextion timer. (tm0)

I got a timer and change tim value. ( unfortunately Nexion allow to maximum to 65535mS). vscope should be globle, otherwise you cant use timer in every page.

I reset the timer in page touch event. In timer event I put this code.

if(tm0.tim==60000) //reset time in mS
{
   page 0 //specific page to load
}


Terminal read-only serial monitor without blocking serial port for sketch upload I would like to have all serial output from Arduino (nano) dumped to the terminal in Linux, without blocking the serial port for uploading new sketch version (for quick debugging loop), when using Arduino-Makefile:

[Errno 16] could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'

Is there something made for that already? I did read about 10 related questions here and elsewhere (using screen, socat and others) but none of them deals with the question how to not block the port.

I might eventually code something in Python, which will disconnect when  signalled and reconnect again after a few seconds (I use custom Makefile for the upload) and I imagine Arduino's IDE serial monitor does something similar.

Other pointers on how to solve the issue are appreciated!

(using screen, socat and others) but none of them deals with the question how to not block the port.

Other pointers on how to solve the issue are appreciated!

I say:

Virtually all hardware problems can be solved with software. But, sometimes, the $50000 software problem can be solved with the $2 hardware solution.

This is one of those cases. Buy a CP2102 6-pin serial UART USB adapter for < $2 on Ebay, or for < $10 on Amazon, to provide a second serial interface to the same Arduino (both connected to the same hardware UART built in to the Arduino's ATmega328 mcu). Let the main USB serial interface handle code uploads to the Arduino. Let this 2nd, external UART handle READ-ONLY from the Arduino!
Plug it in:
Arduino     CP2102 USB 6-pin UART
-------     ---------------------
Tx          Rx
GND         GND

Done. Do NOT plug in the CP2102 Tx to anything.
Now, use screen, or my crude datalogging Python serial terminal I wrote here (eRCaGuy_PyTerm), or a 2nd instance of the Arduino IDE with the Serial Monitor, or any other serial terminal for that matter, to read from the CP2102 while the Arduino's built-in USB adapter does code uploading.
Two serial interfaces to the same pins on the Arduino: one does Tx/Rx to/from the Arduino, while the other does only Rx to read from the Arduino.
I use a 2nd UART like this all the time as a trick to allow me to read the data from the Arduino into one Serial Monitor in one instance of the Arduino IDE so I can see the numbers, and I use the external CP2101 USB adapter to read the same exact data from the Arduino into the Serial Plotter of another instance of the Arduino IDE so I can see the live, plotted graphs!
It's amazing how well this works. Quick hack. Easy solution.

Note: to you use my eRCaGuy_PyTerm Python serial terminal, first set all your serial parameters inside the user_config.py file, then run python3 serial_terminal.py to run the program. It is a 2-way serial terminal, with datalogging. It works quite well. I really should improve its readme and post some examples someday.


Connecting an ESP8266 to WiFi without hardcoding the credentials I've recently achieved connecting my board, an ESP8266 to my local WiFi, but I've had to hardcode the credentials to the code, just like in 99% of the tutorials online. My code looks somewhat like this:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

void setup() {

    USE_SERIAL.begin(115200);

    WiFi.mode(WIFI_STA);
    WiFiMulti.addAP("SSID", "Password");

}

void loop() {
    // Some more code
}

The thing is, I would like to know if there is some way to parametrize the credentials so I don't have to recompile and upload the code to the board everytime my WiFi password changes.

One of my ideas was to connect all the boards to a local router without actual connection to the internet and have a server in that same LAN manage the sensitive information, not the boards. That would allow me to manage credentials properly. Does this even make sense?

The common way to do this is to put the ESP8266 into AP (Access Point) mode and then serve a web page with the configuration interface.

To make it even easier, you can create a captive portal so that the user doesn't need to open a specific IP address in their browser. The captive portal will cause the configuration page to be loaded no matter what address they open.

A popular Arduino library that makes this all very easy is WiFiManager:

https://github.com/tzapu/WiFiManager


Making the speaker play a certain frequency of sound I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.

The code is as below:

digitalWrite(buzzer, LOW);
delayMicroseconds(1000000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(1);

What could be the problem?

Have you looked at the Tone library?  That does what you want, with some other niceties besides.

Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:

digitalWrite(buzzer, LOW);
delayMicroseconds(500000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(500000 / frequency);


Arduino shield bluetooth I have this arduino motor shield, and I want to connect a Bluetooth module, but don't know how (the tx and rx pins are used by the plate). Tried to sold it but now I don't have the tin to do it. So I want to know if I can use this holes (don't know their names) "the ones encircled in red" to connect the Bluetooth module. Thank you folks.

You are looking at the wrong place. Tx and Rx are at the bottom of you picture (new picture at the bottom to help you). What you need to do is to get a jumper, heat up the Rx pin and put the jumper in the molten solder. That is not the ideal choice but because you don't have enough solder, thats the way to go. To the same to the Tx pin, GND, and VCC.

A more permanent and clean way of doing this will require extra solder (which you dont have at the moment) and some "shield headers" (aka stackable headers). This will let you connect the shield to your Arduino while still leaving you with all of your female headers.


Confusing Arduino Leonardo PWM I'm having problems with using Arduino Leonardo PWM outputs (I'm actually using YUN board).

I need 4 PWM outputs that generally have the same base frequency of around 10 to 20 Hz or so.

I'm using timer 1 (A-pin-9,B-pin-10,C-pin-11) and timer 4 (A-pin-13)

I get pins 9,10,and 13 PWM output working decent, but for some reason pin 11 PWM frequency is much much higher.

Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Here is my code can anybody see anything wrong? thanks!

    #define PWM_4A_PIN  13
    #define PWM_1C_PIN  11

    #define PWM_1B_PIN  10
    #define PWM_1A_PIN  9

    void setup() {
     TCCR1B = TCCR1B & 0b11111000 | 0x05;
     TCCR4B = TCCR1B & 0b11110000 | 0x09;
     analogWrite(PWM_4A_PIN,128);
     analogWrite(PWM_1C_PIN,128);
     analogWrite(PWM_1B_PIN,128);
     analogWrite(PWM_1A_PIN,128);
    }

    void loop()
    {
    }

Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Unless D11 is configured as OC0A instead of OC1C, which means that it will work off timer 0.

TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
TCCR1A |= _BV(COM1C1) | _BV(COM1C0);
 ...
OCR1C = ...;


I cannot upload any code to my arduino nano Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Nano, ATmega328P"
Sketch uses 934 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
An error occurred while uploading the sketch
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x49
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

For me selecting the ATmega328P (Old Bootloader) from the Tools --> Processor menu in the Arduino IDE solved the problem.
See: https://gyorgybalassy.wordpress.com/2020/10/16/arduino-programmer-is-not-responding-not-in-sync-error/


tinkercad arduino simulator integers being outputted as larger numbers than they are? I am using an Arduino simulator on www.tinkercad.com (a seemingly nice free product from Autodesk).  Working on conversion of an integer to a 16 bit binary string for output to a DAC, but unfortunately even at the first step I am getting unexpected behavior.

void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.print("Sanity Check\n");
  uint16_t num = 12000;
  Serial.print("\nNumber: " + String(num) + "\n");
  delay(3000);
}

Surprisingly the above code gave the following output:

Sanity Check

Number: 12222

Is there something I am doing wrong, or something wrong with the simulator?   The error seems to crop up with any value over 10000.  10001, 10002, 10003 all print as 10000.  11000, 11001, 11002, 11003 all print as 11111.  etc, etc.  What could be going on?

Bug. No other explanation. Real hardware (Arduino Uno) prints 12000.

Even the debugger tells me that the value of that variable is 12000.

Outputs:

Number: 12222
12000
12222 something

Most interestingly if you Serial.println() the number, it is outputted correctly. The bug must be in the constructor of the String object, as demonstrated by the "test" String. This bug also occurs on other data types, e.g. int.

If you only use direct Serial.print[ln] calls you should be able to workaround that bug.


Arduino U8glib: how to display text? I have a Nokia 5110 screen using u8gliv. I have it displaying an image and I can get it to display text:

   u8g.setFont(u8g_font_osb18);
   u8g.drawStr(0, 20, "PRESS START");

The problem is that this font size is way too big. How can I make it smaller? Do I have to use different fonts? If so how do I do that?

Just choose a smaller font. You know, I showed you the documentation earlier. You really should read it, because it contains all the information you need.

For instance, here is the section on the available fonts: https://code.google.com/p/u8glib/wiki/fontgroup - each section contains a link to download the font group which of course you will need to do before you can use it.

You might find something like:

u8g.setFont(u8g_font_fixed_v0);

more to your liking. And don't forget to download it via the link above first.


Can you save data to heap section in Arduino memory? On normal computers, heap will be cleaned as you close the program, but can I save data to Arduino's heap with malloc function. And will it be cleaned after I power off the Arduino?

Yes, you can use malloc() on the Arduino - however it is not something I would recommend you use since memory is at a premium and excessive use of malloc() and free() causes heap fragmentation which can eat your memory up and cause random crashes (String is the biggest culprit of this).

I am not sure what you mean by "clean" the memory.  When power is removed the content of the memory is lost. The whole of the SRAM forgets its contents if there is no power to maintain that state.  A bit like when you unplug your computer it "forgets" that Windows is loaded.

If you want to retain information with the power removed you need to use the EEPROM.


Conncet Bluetoth module HC-05 to Arduino Uno Using UART Usb to enter in AT command I have connected Arduino Rx(pin 0) to Bluetooth module Rx pin. Tx od Arduino to Tx of Bluetooth . I am able to send command to Bluetooth module using Serial Monitor of Arduino on my PC.

I have uploaded the empty code in Arduino.

I want to know why we connected Tx to Tx and Rx to Rx i.e one to one connection?

If I send command "AT" from my PC using serial Monitor of Arduino , How is it flowing to Bluetooth module.

Why not we connect Rx to Tx pin in AT Mode of Bluetooth module?

Pls explain using diagram.

By using SoftSerial you can connect the HC-05 module to another pin than D0 and D1. Example connect HC-05 to D2 and D3 and define SoftSerial to use D2 and D3.

---------                        -----------                        ------
| HC-05 +---(SoftSerial)---(D2/3)+ Arduino +(D0/1)---(Serial USB)---+ PC |
---------                        -----------                        ------


Arduino not responding to macbook pro When I try to upload my code onto the Arduino it just gives me the error message: "avrdude: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions."

My Arduino used to function just fine. Now when a plug it in, the lights on the Arduino do not blink like they used to, and the only pins that do anything are the ones to power. It also said something like: Arduino is not optimized for mac os. It seems that the Arduino is taking in the power but not the code. here's the code:

int led = 13; // the pin the LED is connected to
void setup() {
  pinMode(led, OUTPUT); // Declare the LED as an output
}

void loop() {
  digitalWrite(led, HIGH); // Turn the LED on
}

I had this issue and it was because the port was not set in my Arduino IDE.
I fixed it by going to Tools -> Port, and selecting my usb device.  In my case it was called /dev/cu.SLAB_USBtoUART


Getting Firmata to control WS2801 LEDs I am trying to control a strip of WS2801 LEDs through an arduino uno running firmata from Python on my laptop.

I've written some basic code based on adafruit's library here (from line 187):

from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
import time

leds = [(255, 255, 0), (255, 255, 0), (0, 255, 255)]

uno = PyMata3()

uno.set_pin_mode(2, Constants.OUTPUT)  # signal
uno.set_pin_mode(3, Constants.OUTPUT)  # clock

def show(leds):
    for pixel in leds:
        for channel in pixel:
            i = 0b1
            for x in range(0,8):
                if i & channel:
                    uno.digital_write(2, 1)
                else:
                    uno.digital_write(2, 0)
                uno.digital_write(3, 1)
                uno.digital_write(3, 0)

                i = i << 1

    uno.digital_write(3, 0)
    time.sleep(0.001)

When I run the code it seems to run ok, but only the first LED will light up. I think (too quick to be certain) that it flashes through all the colours - ie displaying each colour rather than passing them through.

I'm wondering if there is something wrong with the timing for the clock pin making it latch, but I'm grasping here.

It's possible that time.sleep is causing a latching issue. You should instead use pymata-aio's sleep function:

uno.sleep(0.001)

The documentation for it can be found here: http://htmlpreview.github.io/?https://github.com/MrYsLab/pymata-aio/blob/master/documentation/html/pymata_aio.html#module-pymata_aio.pymata3

You could also try a different pin and see if you still have the issue?


Better cycling through the RGB colors I have been trying to achieve a way to tap into the 16 million colors RGB provides for this LED strip. I thought of using LEDS.setBrightness(); but I have not been successful in my attempts. I have read the documentation on color fading, but I have not been able to write this to my Arduino Leonardo. Here is my code below, which cycles through the initial rainbow of 0-255. I was wondering how to get more than 0-255 if not all the colors.

#include <FastLED.h>

#define LED_COUNT 60
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];
int wait_time = 5;

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void loop() {
  //start from red
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 255;
    int g = 0;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }

  //into blue
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = colorStep;
    int g = 0;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from blue
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 0;
    int g = colorStep;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into green
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 0;
    int g = 255;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from green
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = colorStep;
    int g = 255;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into yellow
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 255;
    int g = colorStep;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
} //end main loop

I think it's worth noting that the three 255 values for RGB colour space is just one way to encode the 255^3 (16,581,375) colours. These include each and every brightness level too.

If you are trying to get a rainbow effect, you may have more success or find it easier to use a HSL or HSV colour space.

HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:

https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors


AsyncWebServer giving wdt reset I am using 3 Esp32 modules. One being master and other two being nodes.
Nodes are connecting to the master's AP. Master is connected with GSM module to execute the web api.
Master esp is having a Async Webserver which takes the http requests from the nodes and executes the appropriate web api. This web api returns the result and finally this result is sent back to the node as the response to the http request.

While running this code, Randomly on any request i face wdt reset.

Hence my question is, how should i handle the wdt resets and keep my program running softly.

E (32706) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time:
E (32706) task_wdt: - async_tcp (CPU 0/1)
E (32706) task_wdt: Tasks currently running:
E (32706) task_wdt: CPU 0: IDLE0
E (32706) task_wdt: CPU 1: async_tcp
E (32706) task_wdt: Aborting.
abort() was called at PC 0x400e1cc3 on core 0
Backtrace: 0x4008c434:0x3ffbe170 0x4008c665:0x3ffbe190 0x400e1cc3:0x3ffbe1b0 0x40084771:0x3ffbe1d0 0x4016aaf3:0x3ffbc0d0 0x400e307a:0x3ffbc0f0 0x4008a361:0x3ffbc110 0x40088b7d:0x3ffbc130

My Code Snippet is given below,

Master

HttpClient http(gsmClient, "www.mydummyserver.com", 80);
AsyncWebServer server(80);

const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";
IPAddress ip(192,168,5,2);
IPAddress gateway(192,168,5,1);
IPAddress subnet(255,255,255,0);
const char* PARAM_MESSAGE = "message";

void notFound(AsyncWebServerRequest *request) {
    request->send(404, "text/plain", "Not found");
}

void setup() {

  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  delay(100);
  WiFi.softAPConfig(ip, gateway, subnet);
  WiFi.softAP(ssid, password);

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "Hello, world");
    });

 server.on("/myApi", HTTP_POST, [] (AsyncWebServerRequest *request) {

        String message;
        if (request->hasParam(PARAM_MESSAGE)) {
            message = request->getParam(PARAM_MESSAGE)->value();
        } else {
            message = "No message sent";
        }

        http.setTimeout(20000);
        String postData = "Param1=abcd&Param2=pqrs";
        http.beginRequest();
        http.post("http://www.mydummyserver.com/testapi.php");
        http.sendHeader("Content-Type", "application/x-www-form-urlencoded");
        http.sendHeader("Content-Length", postData.length());
        http.beginBody();
        http.print(postData);
        http.endRequest();
        int statusCode = http.responseStatusCode();
        String response = http.responseBody();

        Serial.print("Status code: ");
        Serial.println(statusCode);
        Serial.print("Response: ");
        Serial.println(response);
        request->send(200, "text/plain", "Response: " + message);

    });

 server.onNotFound(notFound);

    server.begin();

}

void loop() {

}

Node

HTTPClient httpClient;

void setup() {

  Serial.begin(115200);

  WiFi.begin("ESP32-Access-Point", "123456789");

  Serial.print("WiFi ");

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(10);

  }

  Serial.println("connected:" + WiFi.SSID());

}

void executeApi() {

  Serial.println("Executing Api...");

  httpClient.setTimeout(20000);
  httpClient.begin("http://192.168.5.2/myApi");
  httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  String contentStr = "Param1=abcd&Param2=pqrs";

  int httpResponseCode = httpClient.POST(contentStr);

  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);

  httpClient.end();

}

String cmd = "";
void loop() {

  if (Serial.available() > 0) {

    cmd = (Serial.readStringUntil('\n'));

    if (cmd.length() > 0) {

      if (cmd == "api") {
        executeApi();

      }

    }

  }

}

For sulutions i have tried following things,

a. I tried to write this into the loop() function.

 while(true){
   delay(1);
 }

b. Tried disabling the wdt

disableCore0WDT()
disableCore1WDT()

but none of these giving good results.

The following recommandations, as you are providing not enough relevant info

Install ESP-exeption decoder and analyse your backtrace - post it here so we see what indetail caused the wdt
Async webserver tends to cause this behavior if a response tends to take to long a well placed yield() sometimes helps to prevent that behavior - to anaylse you need ESP-exeption decoder
as loop() is running on core1 some/no process (idle) on core0 caused the behavior. You cann look up task assignment to cores be done manually to distribute the tasks (or send a yield() timed to core0 to reset the wdt
placing timeouts in combination with sleep/deep sleep (although you dont seem to use them) are also causes for wdt resets
a hackey trick is to set CONFIG_ASYNC_TCP_USE_WDT 0 but is ok for testing

If you look into async_tcp the possible culprit you see one line
xTaskCreateUniversal(_async_service_task, "async_tcp", 8192 * 2, NULL, 3, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE);
   Here an example how I use it to prevent wdt resetsPlace in setup()

disableCore0WDT();
disableCore1WDT();
disableLoopWDT(); // You forgot this one !

and because of this routine in the async_tcp lib

static void _async_service_task(void *pvParameters){
    lwip_event_packet_t * packet = NULL;
   for (;;) {
    if(_get_async_event(&packet)){
#if CONFIG_ASYNC_TCP_USE_WDT
        if(esp_task_wdt_add(NULL) != ESP_OK){
            log_e("Failed to add async task to WDT");
        }
 #endif
        _handle_async_event(packet);
 #if CONFIG_ASYNC_TCP_USE_WDT
        if(esp_task_wdt_delete(NULL) != ESP_OK){
            log_e("Failed to remove loop task from WDT");
        }
#endif
    }
 }
  vTaskDelete(NULL);
   _async_service_task_handle = NULL;
}

I set the CONFIG_ASYNC_TCP_USE_WDT 0 and it works so far.


UNO analog input voltage reading not accurate My loop code is this:

// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(float(sensorValue*5000.0/1023));
delay(1);        // delay in between reads for stability

When I read 5V it gives 5000 mV. When I read 3.3V pin it gives 3211 mV. When I read 1442 mV battery it gives 1392. What do you think about this situation?

NOTE: There is no any additive circuit. Just wires.

Your question contains a number of errors and misconceptions.

Firstly the maximum output of a successive approximation ADC (here 0x3ff) corresponds to Vref - 1 LSB
The voltage will thus be sensorValue*5000.0/1024. Note this error is less than the error of ±2LSB.

Measuring your 5V is futile, as this is the default analog reference, so the result must be 0x3ff.

Measuring the 3.3V pin will give a relative value to the 5V reference. Both are produced from commercial grade regulators with a accuracy of ±5%.

You are also confusing the precision of the reading (10 bit) with accuracy which is a best ±5% ±2LSB.

If you really want to measure voltage you should use the internal 1.1V bandgap reference. You would of course need to reduce the 5V and 3.3V to less than 1.1V. This introduces another potential error (even if you use 1% resistors), but would give more accurate results which are directly comparable.


How to map PID output to actuator control? I'm building a control system for the heating of a house. A sensor reads the temperature inside and is then used as the input in the PID control. The temperature is then controlled by a servo which opens and closes a shunt were water runs to the radiators. I understand all the inner workings of the PID library for Arduino and PID in general, but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive. In what way should the output signal correspond to how open or closed the shunt is?

I understand I can simply map the output signal to the servo signal, but is this the correct way? And with what angle coefficient should I map it with, cause that is basically set with the P parameter, isn't it? Is there some standard way to map the output signal to the actuator "signal", so that that tuning parameters are somewhat "standard".

Hope someone understands anything of what I tried to explain :)

I don't think you would need to use a PID library (or any control loop for that matter) to control a radiator. You could use a simple threshold code, like this:

Pseudocode:

Check temperature
If radiator is off and temperature > (ideal temp - threshold)
  turn radiator on
If radiator is on and temperature > (ideal temp + threshold)
  turn radiator off


Using Piezzo Electric buzzer 10V with an Arduino Lilypad USB I bought a 10 V Piezzo electric buzzer and I wonder how to connect it to an Arduino (in my case a Lilypad USB, but the question stands for any Arduino I guess...).
I hadn't realized this was a 10V buzzer, whereas the Arduino will support at most 5V.

I tried a simple layout such as below, with the sample code from a sparksfun tutoral, but that's not working!

So, how can I do it? ... or should I use another buzzer ?

Thanks

Your options:

Try it anyway with 5V: the buzzer might still produce loud enough sounds for your needs.
Use the line from the arduino to drive an "amplifying" stage (ex: 2N2222 in ON/OFF mode) - but this will also require a 10V source (like a step-up voltage converter)
Get a piezo that is designed to operate at 5V


Problem receiving data from RPi to Arduino via serial Our team has been trying to send data over from RPi to Arduino but there are some weird things happening:

If we open the serial monitor of arduino on RPi itself, the serial data is sent by RPi and received by Arduino successfully.

However, if we do not open the serial monitor of arduino on RPi, the serial data is sent by RPi but not received by Arduino.

The communication between them is via USB cable.

Below are the codes implemented on RPi (using RS232 Linux library in C):

void *rs232t_connect(void *arg)
{
 struct RS232Connection *connect = (struct RS232Connection*)arg;

 // connect to USB port ttyACM0
 fprintf(output, "Waiting for connection on Comport ttyACM0 (24)...\n");
 while(RS232_OpenComport(connect->cport_nr, connect->bdrate, connect->mode) == 1)
     sleep(1);

 // set connected flag to signal completion of connection to main()
 connect->connected = true;
 fprintf(output, "Connection accepted.");

 return 0;
}

void *rs232t_send(void *arg)
{
 struct RS232Connection *connect = (struct RS232Connection*)arg;
 unsigned char buf[4];
 int32_t g;
 bool reconnect = false, resend = false;

 while(1)
 {
   // sample
   g = 10;

   // convert from LSB->MSB to MSB->LSB
   memset(buf, 0, sizeof buf); // clear buffer
   buf[0] = (g >> 24) & 0xFF;
   buf[1] = (g >> 16) & 0xFF;
   buf[2] = (g >> 8) & 0xFF;
   buf[3] = g & 0xFF;

   if(RS232_SendBuf(connect->cport_nr, buf, sizeof(int)) == -1)
   {
     // Print error msg if sending failed
     fprintf(output, "Disconnected\n");
   }
   else
   {
     fprintf(output, "Outgoing Message: %d\n", g); // DEBUG
     g = 0;
   }
 }
 return 0;
}

Arduino Code:

long readSerialInt() {
  long result = 0;
  long temp[4];
  if (Serial.available() >= 4) {
    digitalWrite(13, 1);
    for (int i = 0; i < 4; i++) {
      temp[i] = Serial.read();
    }
    result += temp[0] << 24;
    result += temp[1] << 16;
    result += temp[2] << 8;
    result += temp[3];
    return result;
  }
  else {
     return 0;
  }
}

Any idea why this is happening? Its weird that we need to open the serial monitor of Arduino IDE on RPi before the message gets sent out.

We are sending data over to Arduino. However Arduino does not detect the messages we are sending to it (it didnt perform any action/light up any LED).

Thank you

The problem may be with your code, especially the function for opening the port. Try this in Python 3 and see if it works.

import serial, time

ser = serial.Serial('/dev/tty/ACM0', 9600, timeout=1)

while ser.isOpen():
    try:
        ser.write(b'Hello')
        time.sleep(0.1)
        print('Received: ')
        while ser.inWaiting():
            print(str(ser.read(), encoding='ascii'), end='')
        print()
    except KeyboardInterrupt:
        ser.close()

Arduino side:

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

void loop(){
  while (Serial.available())
    Serial.write(Serial.read())
}

Crude, but it is a lot more straightforward than your program and will help you isolate the problem.


Arduino controlling a heavy solenoid water valve So after burning up a couple Arduinos, I'm running out of ideas...

I am trying to power both a Solenoid valve and the Arduino(nano) with the same 12V-2amp power supply. I've tried it with both a relay breakout board, and via transistor switching, and both are giving me sporadic behavior for the Solenoid.

Early failures came from realizing that the solenoid water value was actually a coil (duh), and thus needed some kind of diode placed over its connections, so I'm assuming the back voltage spike is what fried the first two boards.

At first I added a small diode that helped but wasn't enough, so I beefed it up to a 3 amp "rectifier diode" 200PIV, which stopped the board frying.

Here is a link to the solenoid water valve. Not much to go on I'm afraid. 12V 0.02-0.8Mpa.

The behavior that I'm seeing now, is that the solenoid will engage, but it won't disengage.

Do I need to add a Capacitor for the solenoid?  If so, any recommendations on sizing?

int relayPin = 2;

void setup()
{
  pinMode(relayPin, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  Serial.println("starting");
  digitalWrite(relayPin, HIGH);
  delay(2000);
  digitalWrite(relayPin, LOW);
  delay(2000);
}

I have setup Arduino UNO and succeeded turning solenoid on when pot soil moisture dry, I was adding rain sensor when I mistakenly disvmcoonected the diode it fried my board, but atleast I had it working . I am using 24 volt normally closed solenoid , since I was monitoring over web I also had ethernet shield attached. And I was powering over ethernet using splitter and extracter.

The vin should only feed in 3.3 volt which you can get using stepdown buck converter , and use remains power to connect to solenoid. The transistor should be on the ground same as arduino nano the ground
The top became messy later


How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino? I have an arduino UNO with atmega 328 whose microcontroller got burnt. I bought a new atmega328. I have another working arduino with atmega8. I followed the instructions in http://arduino.cc/en/Tutorial/ArduinoToBreadboard but I got a little confused.

I burnt the bootloader into my new atmega328 using atmega8 arduino as described in the link above. Now, can I replace my old atmega328 with this new bootloaded atmega328 to upload sketches to it? Or should I follow the steps described in the link to upload sketches?

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


Prevent function inlining I'm trying to shrink the compiled code size, and I have noticed that the compiler inlines functions a lot, even the ones I have not marked "inline", but I can't manage to turn that off.

It looks like the compiler uses the -Os flag by default (optimize for low program size), because when I add it, the resulting program size is the same.

I tried adding "__attribute__((noinline))" to the functions but it makes no difference. Any idea how to prevent function inlining?

I'm using Visualmicro on Visual Studio Community 2017. Arduino 1.8.8. Arduino Uno board.

As I wrote in the comments, I can't recreate this problem again. So I apologize for wasting everyone's time. But I still find it weird how the -Os flag works. I assumed it meant smallest possible size. But I now think it means "fairly small, but also make it run fast". Look at the code below, and how using the noinline attribute makes the code smaller. I added the -Os compiler flag to be sure, but I think it is already on by default.

class InlineClass
{
public:
    void __attribute__((noinline)) testFunc(int arg1)       // 570 bytes
    //void testFunc(int arg1)               // 602 bytes
    //inline void testFunc(int arg1)        // 602 bytes
    {
        _var1 = arg1 + 1;
        _var2 = arg1 + 2;
        _var3 = arg1 + 3;
        _var4 = arg1 + 4;
        _var5 = arg1 + 5;
    }

private:
    volatile int _var1 = 0;
    volatile int _var2 = 0;
    volatile int _var3 = 0;
    volatile int _var4 = 0;
    volatile int _var5 = 0;
};

void setup()
{
    InlineClass ic;
    ic.testFunc(1);
    ic.testFunc(2);
    ic.testFunc(3);
    ic.testFunc(4);
    ic.testFunc(5);
}


ESP8266-07 no work after reboot I try move my projects from atmega to ESP8266-07 modules. I connect ESP8266-07 to FT232:

(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) EN -------- VCC 3.3V (FT232)
(ESP) GPIO0 ----- GND (FT232)
(ESP) GPIO15 ---- GND (FT232)

I can upload sketch and it's work. BUT...

... WHEN I restart ESP (software reset or hardware reset - unplug power) program no starting. I try change connections after upload like:

Try 1:
(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) EN -------- VCC 3.3V (FT232)

Try 2:
(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) EN -------- VCC 3.3V (FT232)
(ESP) GPIO0 ----- VCC 3.3V (FT232)

Try 3:
(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) GPIO0 ----- VCC 3.3V (FT232)

But everytime sketch does not start after upload. This is not a code problem, because I try start "blink" sketch or other. Everytime ESP work once, after upload.

Thank you gre_gor. You were right about correct pins. If you want start ESP on "normal mode" you must plug pins like:

(ESP) GND ------- GND
(ESP) GPIO15 ---- GND
(ESP) VCC ------- VCC 3.3V
(ESP) EN -------- VCC 3.3V
(ESP) GPIO0 ----- VCC 3.3V
(ESP) GPIO2 ----- VCC 3.3V

But if we must use GPIO0, GPIO2 and GPIO15 how we have 9 GPIO, 2 UART and 1 ADC?


What is the best and most reliable way to detect if a book is pulled out of a book case? What is the best and most reliable way to detect if a book is pulled out of a book case?
I have a book case which I want to mount sensors to so that I can detect when certain books are pulled out, I don't need to know how much, all I need is a boolean trigger if the book has been pulled out 2+ cm or so (works with lower too). I would preferably also want to know when they have been replaced but that is just a bonus.
The goal of the project is to move a servo which may or may not open a secret door when 3 books are pulled out in a certain order.
The sensors need to be able to work continuously 24/7 for years.
Here is a masterfully drawn picture to explain it even better.

So far I have been thinking of mechanical switches, Ultrasonic Sensor (HC-SR04), or possibly some sort of infrared light and sensor that can detect a change in intensity (where a lower intensity is book being pulled out).
The mechanical switch I could easily do, but I would prefer something that is less obvious, and less "clicky" when it's triggered. I don't want to give away that there is something special with a book if someone picks it up on accident.
Any ideas on how it can be done?
Would love tips for specific components as I'm not native to the arduino world and have a hard time finding exactly what I'm looking for.

As Majenko stated in the comments, an easy and discrete way would be using IR proximity sensors behind each book. The IR light from them is invisible to the eye, they are easy to read with an Arduino and often the casing of the IR LED and IR sensor are black, so that you could easily hide them in a black backplate of your book case.
The IR sensor will output one pin state (HIGH or LOW depending on the sensor), when something (the book) is near it (on most sensor modules you can change to threshold to your liking), and the other, if nothing is near it (empty place in the book case)
Searching "ir proximity sensor" at amazon gives multiple good looking results for ready to use sensor boards.

Another - more hacky - way would be to build your own switches at the top of the book case. As a switch is nothing more than 2 electrical contacts with some mechanic suroundings, you could add a small piece of cardboard above each book, which falls down a bit, when the book is removed, but not enough, that it is easily spotted (a few millimeters should be enough). At the top of the case and on the cardboard piece you put some piece of tinfoil or aluminum tape. When the book is put in the box, the tinfoil pieces get pressed together by the book, thus make contact. Wire one piece to ground, the other to an Arduino pin.
I find the IR sensor solution better, but I wanted to include a solution, where you don't need to buy extra sensor modules.


If any kind of character gets loaded into a string, what do I use for an end-of-line character? I have an Arduino project that is converting floats to characters and then transferring those characters via the serial to a Python program. This is a portion of the Arduino code:

#define MEM_LEN (16 * 4 * 4) + 1
uint8_t dataBuf[MEM_LEN];

typedef union {
  float f;
  uint8_t b[4];
} cvt_t;

cvt_t cvt1;

// set up sensor stuff
MLX90621 sensor;
 .
 .
 .

void loop() {
    sensor.measure(); //get new readings from the sensor
    count = 0;
    for(uint8_t y=0;y<4;y++){ //go through all the rows
      for(uint8_t x=0;x<16;x++){ //go through all the columns
        cvt1.f = sensor.getTemperature(y+x*4); // data at position x/y
        dataBuf[count + 0] = cvt1.b[0];
        dataBuf[count + 1] = cvt1.b[1];
        dataBuf[count + 2] = cvt1.b[2];
        dataBuf[count + 3] = cvt1.b[3];
        count += 4;
      }
    }
    dataBuf[MEM_LEN - 1] = '\n'; // not a good delimeter
    Serial.write(dataBuf, MEM_LEN);
}

The problem is that float conversion loads any and all characters into dataBuf, so I don't have a good delimiter or "end-of-line". When the Python program ingests the incoming string, there's nothing to use to know it's received a complete frame. I don't want the Python to just count characters to know when it's received a frame. No good delimiter - what should I do?

Framing binary messages is not as simple as choosing a delimiter.
Counting the characters could be an option, but you need some way to
check that your reception has not gotten out of sync. You could for
example send messages that looks like:

struct Message {
    uint32_t magic;
    uint8_t data[MEM_LEN];
    uint16_t crc;
};

Where magic in a magic number, i.e. a random but fixed value that
is very unlikely to happen by accident, and you end the message with a
CRC. On the Python side, you check that both the magic number and
the CRC are OK. If they are not, you have a communication error, but you
can re-synchronize by looking for the next occurrence of the magic
number.
Another option is to choose both a delimiter (say, ASCII 10 = LF =
'\n') and an escape character (say, ASCII 92 = backslash = '\\'). On
the sending side, you prefix by the escape character every accidental
occurrence of either the escape character or the delimiter:
void send_byte(uint8_t c)
{
    if (c == '\\' || c == '\n')
        Serial.write('\\');  // prefix by escape character
    Serial.write(c);
}

and on the Python side you do the reverse operation. The only issue with
this approach is that your messages are not constant size anymore.


Arduino Uno with ESP8266 #include <stdlib.h>
#include <SoftwareSerial.h>

#define SSID "name-of-my-network" //replace XXXXX by your router SSID
#define PASS "password-of-network" //replace YYYYY by your router password
#define IP "184.106.153.149" //thingspeak.com IP

const int tempPin = A0; //configure Arduino pins
String GET = "GET /update?key=thingspeak-api-key&field1=";
SoftwareSerial mySerial(10,11); //Serial communication to ESP8266 module(RX, TX)
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long delay_time = 60000;

void setup() {
  Serial.begin(57600);
  while(!Serial) {
    ;
  }
  mySerial.begin(115200);
  Serial.println("Initializing...");
  //communication with wifi module
  mySerial.flush();
  mySerial.println("AT");
  delay(2000);
  if(mySerial.find("OK")) {
     Serial.println("Communication with ESP8266 module: OK");
   } else {
     Serial.println("ESP8266 module ERROR");
   }
   connectWiFi();
   //initialize timer
   starttime = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
  if ((millis() - starttime) >= sampletime_ms) {
    char buffer[10];
    int analogReading = analogRead(tempPin);
    String temperatureStr = dtostrf(analogReading, 4, 1, buffer);
    temperatureStr.replace(" ","");
    updateSensors(temperatureStr);
    //wait next sampling cycle
    Serial.print("Wait ");
    Serial.print(delay_time/1000);
    Serial.println("s for next sampling");
    Serial.println();
    delay(delay_time);
    //initialize new cycle
    Serial.println();
    Serial.print("Sampling (");
    Serial.print(sampletime_ms/1000);
    Serial.println("s)...");
    starttime = millis();
  }
}

void updateSensors(String tempStr){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  mySerial.println(cmd);
  delay(2000);
  cmd = GET;
  cmd += tempStr;
  cmd += "\r\n";
  delay(1000);
  int strsize = cmd.length();
  mySerial.println("AT+CIPSEND=" + String(strsize));
  delay(2000);
  mySerial.print(cmd);
  if(mySerial.find("OK")) {
    Serial.println("Transmission completed with success");
  } else {
    Serial.println("Transmission failed!");
  }
}

boolean connectWiFi(){
  Serial.println("Connecting wi-fi...");
  String cmd ="AT+CWMODE=1";
  mySerial.println(cmd);
  delay(2000);
  mySerial.flush(); //clear buffer
  cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  mySerial.println(cmd);
  delay(5000);
  if(mySerial.find("OK")) {
    Serial.println("Connection succeeded!");
    return true;
  } else {
    Serial.println("Connection failed!");
    return false;
  }
  Serial.println();
}

I am using the above code and have connected the ESP8266 to the Arduino as follows:

  TX of ESP8266 to pin number 11 of Arduino
  Rx of ESP8266 to pin number 10 of Arduino
  Vcc of ESP8266 to 3.3V power supply taken from Arduino
  GND of ESP8266 to GND taken from Arduino
  CH_PD of ESP8266 to GND

It seems that I can't get the ESP8266 working. Could anyone could help me? I would really appreciate any help since I cannot continue my project.

This code is used to upload temperature data on pin A0 to things speak
Create thingspeak account and create channel you get api key it seems that this code uses field1 to upload data upload this code to arduino the change ssid and password


How would I go about measuring an analog signal on my arduino mega that has both positive and negative voltages I have a signal that fluctuates between -70mV and 50mV. How would I get the arduino to read this.. Ultimately I am trying to graph the data in real time so it looks like this.

https://imgur.com/a/mZYnErY

Here is my try at this: if your voltage source doesn't mind sinking
something like 150 µA, you could try something like this:

simulate this circuit – Schematic created using CircuitLab

This should map the input range [−70 mV, +50 mV] to
[0.04 V, 4.06 V].


How can you have two blinking leds and a fading one I am trying to make a alarm and I have two blinking leds (red and blue). They work fine but I want two more that fade in and out.

I have a buzzer on it too.

I am very new to programming. By the way, the code below runs with no errors; just does not do what its intended to.

int led = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  delay(200);
  digitalWrite(11, LOW);
  delay(200);

  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(12, LOW);
  delay(200);

 digitalWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);
}

While there are better ways to do this, as pointed out by other posters, for what you're trying to learn right now, your program (almost!) works just fine. You'll need the more advanced techniques as you progress to more complex programs. But for now, I made a couple of edits to your program to get you going:

The most important one was to use analogWrite() for the PWM LED (LED 9). That makes it fade in and out instead of turn on and off (with a long period).
I turned one LED on and one off at the same time, getting rid of the dark periods and 400ms of combined delay.
I doubled the fadeAmount to fade in and out a little faster; it wasn't very visible with an increment of 5.

Here it is with those changes:

int led = 9;
int brightness = 0;
int fadeAmount = 10;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);

 analogWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);

}

Update:

  what if i wanted to add a a second led

I'm assuming you mean a fading LED, that it's pretty clear where you'd a blinking one?

Blinking in-phase is easy - write the same brightness to both. To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED.

But note how your code starts getting more complex as you add components and try to manage them in a single loop, with delay()s? That's when you'll want to try the Blink Without Delay example, and compare adding new LEDs that way, to adding new LEDs to your current program.


How Atmel Studio 7 compile Arduino code? Atmel stated in their website:

  Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?

It is almost always the case that a high-level environment like an IDE provides an interface to an existing tool-chain rather than being truly an all-in-one mega-application, which would a maintenance nightmare. Atmel Studio 7 is no exception, and according to Atmel, uses and includes (quite likely by downloading it during the install process) the GCC tool-chain.

  Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

Probably for the Arduino libraries, which are contained within the Arduino IDE executable.


How to dim background LEDs on TFT display with ILI9341 I have bought a 2.5" TFT shield online, which is equipped with the ILI9341 controller. I need to dim the intensity of the background LEDs to match ambient light.
This particular shield does not provide a pin to control the intensity of the LEDs with PWM via a separate input, so I need to dim the background LEDs of this display via software.
The zip file with the libraries can be downloaded here.
Does one of you know how can issue a command to the TFT display to dim the background LEDs?
Thanks in advance!
UPDATE 1:
I wrote a new function to set the display's brightness by controlling the background LEDs, but something is missing as I can seem to be writing correctly to the display. So I'm trying to get the display to answer to a known command first, like 0x28 (Display Off).
The new function is defined in Adafruit_TFTLCD.cpp:
// Set display brightness (background LED's)
void Adafruit_TFTLCD::setDisplayBrightness(uint8_t x) {
  // Try with 0x28 (Display Off) to see if display reacts
  writeRegister8(0x28, 0);
  return;
}

The function prototype is defined in Adafruit_TFTLCD.h
// New functions
void setDisplayBrightness(uint8_t x);

Then I call the function in my main loop. To make sure, I first write some rectangles on screen, wait 5 seconds, then fill the screen with blue, call the new function and enter an endless loop so no other commands can interfere:
  tft.fillScreen(BLUE);
  tft.setDisplayBrightness(10); // Which really is command 0x28 to test

Any clues what I might be missing?
Thanks!
UPDATE 2:
I got so far as to have the ILI9341 react to some commands, but not all the time, and not to all commands. I suspect there is something in the way you issue the commands that I'm missing( timing?, sequence?, other?)
Here is what I have found out so far:
I can get the display to react to the Display Off command (0x28), but only when I issue it in the begin(..) function. So, the original code in Adafruit_TFTLCD.cpp is like this:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);

If I change it to the following the display reacts by remaining white:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
writeRegister8(ILI9341_DISPLAYOFF, 0); // Display off is declared as 0x28
delay(500);

So, I have a reaction to command 28h.
Then I tried function 0x51 like this in the begin(...) function:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);
writeRegister8(0x51, 0x80); // Test command 0x51 - background intensity
delay(500);

To no effect :-(
I even added command 0xBE (background PWM frequency) to see if it had any effect, but nothing :-(
void Adafruit_TFTLCD::begin(uint16_t id) {
  ...
  writeRegister8(ILI9341_DISPLAYON, 0);
  writeRegister8(0xbe, 0x80);
  delay(500);
  writeRegister8(0x51, 0x0);
  delay(500);

Also if I issue the 0x28 command:
writeRegister8(ILI9341_DISPLAYOFF, 0)

elsewhere in Adafruit_TFTLCD (e.g. in FillScreen, Fill Rect etc, it doesn't work either).
Any ideas? They would be highly appreciated!

I got in contact with the manufacturer of the shield, they informed that the background LEDs are hardwired and not controllable via the ILI9341. So, it is not possible to dim the background light in this shield

:-(

I will look for another TFT shield and make sure it's dimmable before buying.


I2C between Arduinos without Master I am working on a library for some Arduinos that should talk between each other.
The aim is that I can load the same binaries onto each Arduino. The I2C ID will be set by DipSwitches.
So far everything works pretty nice but once a while everything gets stuck.

I am not asking you to resolve and debug my code, but I am not sure if i have done something completely wrong:

To make all Arduinos interchangeable I have no Master (Wire.begin()) in my I2C Bus.

I read, that the Master would be responsible for the pulse on the Clock line. As I have no Master in my setup maybe that is the reason for the instability.

Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

You have to have a master for an I2C bus to work.  Can't you allocate one of the dip switches to define the master?

Edit to be able to remove the downvote
Nick his answer seems to imply that you do not need masters but that is wrong.
What Nick is saying is that you can swap masters over time.
But each time there is communication there is a master.
So the statement "You have to have a master for an I2C bus to work" is 100% right.
As I misunderstood this myself I downvoted this answer. I hope this edit will enable me to remove my downvote and add a upvote.


Arduino with nRF24L01 I am using nRF24L01 with Arduino Nano and Mini. I feel they are very useful when we want to connect multiple Arduinos together.

In market we can buy Arduino with WiFi and Bluetooth, why don't they make Arduino model with nRF24L01? Is there any specific valid reason?

Or am I wrong in using nRF24L01 and there is a better cost and power efficient way to connect multiple Arduinos together wirelessly?

NordicRF (the company behind nRF24L01) has released two series of SoC devices that are compatible with nRF24: NRF51 and NRF52. Thanks to the effort by Sandeep Mistry and other contributors, they can be programmed using the Arduino IDE and libraries. Instructions are available here: https://github.com/sandeepmistry/arduino-nRF5

I have tested NRF51822, which is the cheapest variant (costing slightly more than Arduino Pro Mini + NRF24L01+ but in a single small and power-efficient package) and it works great.

The BBC Micro:bit is based on NRF51. More information is available at https://forum.mysensors.org/topic/9722/bbc-micro-bit-and-mysensors-a-great-match

Compared to the Atmega328-based Arduino Pro Mini, NRF51822 has 8x larger flash and 8x larger RAM. It also has Bluetooth 5 and BLE support and a 32-bit ARM Cortex M0 CPU.

There is also this alternative: https://www.ebid.net/eu/for-sale/arduino-ide-compatible-controller-with-the-nordic-nrf24l01-radio-transceiver-156695123.htm

Specifications:

Dimensions 59mm x 18mm
The Nordic nRF24L01+ 2.4 GHz Radio transceiver on board
Supply voltage up to 6.5 Volts
The Digital and Analog pins are 5 volts
ATMega328P frequency is 8 Mhz
4 battery connector pins
FTDI header for programming

Full disclosure: I am member of the MySensors core team. A MySensors user (not affiliated with the core team) created and is selling this board.


How to receive data via Bluetooth on an Arduino 101? The Arduino 101 came out recently, and it has built-in "Bluetooth Low Energy" capabilities. The tutorials and code examples that can be found for the 101 all seem to be about transmitting data, but I can't find anything about receiving data. I've tried to go through the source code of the CurieBle library to find some hints, but I feel a little overwhelmed/lost. Could someone point me to a code example which demonstrates how to do this?

Context: I was previously using an HC-05 module paired with an Arduino Nano in order to receive data. In this case it is quite easy to connect the HC-05 to the Nano's digital pins and receive data like so:

#define RxD 7 // This is the pin that the Bluetooth (BT_TX)
              // will transmit to the Arduino (RxD)
#define TxD 8 // This is the pin that the Bluetooth (BT_RX)
              // will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);

void setup() {
  blueToothSerial.begin(9600);
  Serial.begin(9600);
  // Allow Serial communication via USB cable to computer
  pinMode(RxD, INPUT);
  // Set up the Arduino to receive INPUT from the HC-05 on Digital Pin 7
  pinMode(TxD, OUTPUT);
  // Set up the Arduino to send OUTPUT to the HC-05 on Digital Pin 8
}

void loop() {
  char recvChar;
  while(1) {
    if(blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      Serial.print("Read character: ");
      Serial.println(recvChar);
      // Print the character received to the Serial Monitor
    }
  }
}

Is there equivalent, and equally simple, code available, which would do the same thing via the BLE built into the Arduino 101?

According to the Arduino Callback LED tutorial, you can use the dedicated library to access the BLE features of the board. All the Curie Libraries are covering the new Arduino/Genuino 101 embedded characteristics .
In your case you must incluse the CurieBLE.h and configure the bluetooth service with Read/Write access.

Have a look to this page for a complete sample.


What's the difference between pow and sqrt in this code? I'm not the best at Arduino so I'm sorry for my "noobiness".

I'm extending some code that I found online to work on the gyroscope that I'm building.

I'm wondering what the difference is between pow and sqrt in this code.

I'm also wondering what the 180/pi is used for. I haven't gotten my mind around this part yet.

arx = (180/3.141592) * atan(ax / pow((ay, 2) + pow(az, 2));

What's the difference here?

ary = (180/3.141592) * atan(ay / sqrt(square(ax, 2) + square(az, 2)));

Converting Gerben's comment into an answer:

pow(x, 2) is the second power, in other words:

sqrt(x) is the square root of x, that is:

A whole circle is 360 degrees or 2π when measuring in radians. So this ratio of 180 / 3.141592 is used to convert an angle in radians to an angle in degrees.


mthread and multiple header files I'm using mthreads (https://github.com/jlamothe/mthread) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.

I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files.

here is what I got:

main: call header:

#include "tcan.h"

tcan.h:

#ifndef tcan_h
#define tcan_h

#include "Arduino.h"

class tcan : public Thread {
  public: tcan();
  protected: bool loop();
  private:
};
#endif

tcan.cpp

#include "Arduino.h"
#include "tcan.h"
#include <mcp_can.h>

bool tcan::loop() {
  // lala
  return true;
}

but I get an error when compiling:

  tcan.h:6:28: error: expected class-name before '{' token  class tcan :
  public Thread {

Thanks in advance

The compiler error is due to that the compiler does not know what Thread is.

  tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. A good practice is to include all header files that are needed to read the header file. As Thread is defined in mthread.h the tcan.h file should be:

#ifndef tcan_h
#define tcan_h

#include <mthread.h>

class tcan : public Thread {
public: tcan();
protected: bool loop();
private:
};
#endif

Cheers!


How to control an 12V 2A Car lamp using relay or MOSFET in Arduino I am working with the project controlling an 25W 12V Car lamp. I have a 12V car battery. I want to control it with the Arduino using a relay or MOSFET.

Any suggestion for my project would be appreciated.

You can use a RFP30N06LE mosfet. It can support up to 60V 30A

Here is a wiring schema


default parameter class method I have this function (which works fine):

String Esper::rtcTimeString() {
  DateTime now = rtc.now();
  char buf[] = "MM/DD/YY hh:mm:ss";
  return now.toString(buf);
}

I'd like to have a default value of "MM/DD/YY hh:mm:ss" but also pass an argument to a parameter such as "MM/DD/YYYY" if I want to override this default behavior.

Typically, in the definitions .h file I would do something like:

String rtcTimeString(char ts[] = "MM/DD/YY hh:mm:ss");

and subsequently in the .cpp:

String Esper::rtcTimeString(char ts[]) {
  DateTime now = rtc.now();
  return now.toString(ts);
}

However that results in the same returned time string every time.

e.g.

1/6/2020 12:01:12
1/6/2020 12:01:12
1/6/2020 12:01:12

How can I implement a parameter such that the functionality is the same as in the first code block?

You cannot pass an array of characters as an argument (implicit or not)
to a function. When you write

String rtcTimeString(char ts[] = "MM/DD/YY hh:mm:ss");

The array notation is implicitly converted to a pointer. The line above
is then equivalent to:

String rtcTimeString(char *ts = "MM/DD/YY hh:mm:ss");

And this is incorrect: you are initializing a pointer to modifiable
characters using the address of an array of constant characters. The
compiler should have warned you about this... if you enabled compiler
warnings. The correct prototype should be

string rtcTimeString(const char* ts = "MM/DD/YY hh:mm:ss");

But then you cannot pass this pointer to DateTime::toString(), as this
method expects the template string to live in a buffer it can overwrite:
that's where it will write the formatted string.

I suggest this solution:

string rtcTimeString(const char* ts = "MM/DD/YY hh:mm:ss") {
    DateTime now = rtc.now();
    char buf[strlen(ts)+1];  // allocate a fresh buffer
    strcpy(buf, ts);         // copy the template there
    return now.toString(buf);
}