How do I make a proper long string scanner to detect specific tags in a stream of characters?

Another option is to not save the characters in buffer but instead check each one as they arrive to see if the character is the next in the tag sequence.

This has the advantage that you don't need a buffer to match the tag and you don't have to repeatedly search for the string in the buffer.

const char* TAG_STR="(__BOOK_UPLOAD_START__)";
int tag_pos = 0;
char c;
bool is_uploading_book = false;

void loop() {
  if (BTserial.available()) {
    c = BTserial.read();
    if (is_uploading_book) {
      //do book stuff
    } else {
      if (c == TAG_STR[tag_pos]) {
        // c matched the next character in the string
        tag_pos++;
      } else if (c == TAG_STR[0]) {
        // matched first char in the middle, restart
        tag_pos = 1;
      } else {
        // Did not match the next character so we should start over
        tag_pos = 0;
      }
      // The next character to match is the string terminator
      // so we must have matched the whole string.
      if (TAG_STR[tag_pos] == '\0') {
        is_uploading_book = true;
      }
    }
  }
}


Why does the PIN 13 LED of Uno R3 blink every time I upload some code?

See What happens when code is uploaded using the bootloader? - the flashing is by design.

Probably the reason is to confirm that the bootloader has started.


Not sure, if this is the only problem, but you are reading from the wrong register.

There are 3 registers associated with a digital output pin: DDR, PORT and PIN. To read a pin, you need to read from the PIN register. Currently you are reading the PORT register, which will only ever have the value, that you set it to (zero in this case, because you cleared the bit beforehand with cbi(SDA);). When you configure the pin as input with the DDR register, the PORT register determines, if the internal pullup resistor is activated or not, so it cannot reflect the actual state of the pin. For this you need the PIN register.

Besides that, you might want to look into another thing, that might or might not be a problem in your case: I2C is an open drain bus, meaning, that it is driven actively low and passively high (through pullup resistors). I guess you already have external pullup resistors on your lines, so that you really can deactivate the internal pullup without breaking the communication. But imagine the following situation: The slave get's a request, but cannot clock it out that fast (for whatever reason). It can pull the clock to LOW, until it is ready to push out the data bit, slowing down the clock speed. (This can be done for every bit, unless you are in highspeed mode, then only before the start of a new byte). (This behavior is called clock stretching - Thanks to Edgar for the information) You don't monitor the line, so it can happen, that you drive the clock line actively to high, before the slave has released it. This results in a significant current between master and slave, since the master drives actively high and slave actively low.

There are implementations of I2C communication, that are just doing that and are working fine in most situations. I just wanted to give you this information. And if you at some point want to implement bus arbitration (to allow a multi-master setup), you definitely need this open drain behaviour.


LCD5110 - How to make Direct Draw via 2D-array of boolean?

For a start the Arduino Uno is incapable of storing that array in RAM. You're using twice as much memory for that array as the Arduino has in total. You will have to place it in PROGMEM and use the right functions to access it.

Secondly, you have to use a special library to control the display properly. That library will contain functions to draw on the screen. So your function to draw it would look something (though not exactly) like this:

const bool picture[] PROGMEM = {
    1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
    ... etc ... ... 4032 numbers in total ...
};

for (int i=0; i<48; i++) {
    for (int j=0; j<84; j++) {
        lcd.setPixel(j, i, pgm_read_byte_near(picture + (i * 84 + j));
    }
}

Refer to the manual for the library for the actual function to run and how to configure and set up the LCD screen.


Ignacio's comment, “Start with something. Worry about making it efficient after you've figured out how to make it at all”, is good advice.

Note, to make the transition from one keyframe to another more efficient, use a variant of the Bresenham algorithm.  This allows use of fast integer arithmetic and is intrinsically accurate.  Instead of error accumulating and getting steadily worse (as will happen if you add constant increments), the Bresenham algorithm tracks error and minimizes it.  See, for example, “Simplified Bresenham's line algorithm: What does it exactly do?”.

This edit addresses Paul's question about accumulating error:

  I've added a note to my answer, in which I try to battle the accumulation of error, could you check if my assumption (that the last implementation doesn't accumulate the error) is right?

There can be several sources of error, including accumulation of round-off error; arithmetic overflow errors; time-base errors; and silly errors [it's always easier to poke holes in other people's code!].

To illustrate those error sources and a possible solution, consider the following code snippet:

 0   unsigned long int startTime = millis();
 1.  unsigned int totalTime = 3000, nSteps = 100;
 2.  int msPerStep = round(totalTime/nSteps);
 3.  byte startRed = 100, startGreen = 28, startBlue= 50;
 4.  int deltaRed   = endRed   - startRed;
 5.  int deltaGreen = endGreen - startGreen;
 6.  int deltaBlue  = endBlue  - startBlue;
 7.  byte nowRed=startRed, nowGreen=startGreen, nowBlue=startBlue;
 8.  for(int step= 0; step < nSteps; step++){
 9.     analogWrite(RPin, nowRed   += deltaRed/step);
10.     analogWrite(GPin, nowGreen += deltaGreen/nSteps);
11.     nowBlue = startBlue + (deltaBlue/amountOfSteps)*step;
12.     analogWrite(BPin, nowBlue);
13.     long int elapsed = millis()-startTime;
14.     analogWrite(RPin, startRed + (deltaRed*elapsed)/totalTime);
15.     delay(msPerStep);
16.  }

First, consider currentRed += deltaRed/step expression in line 9.  In the first loop pass it adds an undefined quantity, deltaRed/0, to nowRed; in the next, it adds deltaRed/1 to nowRed; then deltaRed/2; and so forth.

Line 10 corrects the silly error of dividing by step instead of nSteps.  But there can be significant accumulation of round-off error.  For example, if deltaGreen is 199 and nSteps is 100, it repeatedly adds 1 instead of 1.99, and ends up with the Green level 99 counts short of being correct.

Line 11 attempts to compensate for that problem by adding a step-proportional amount of deltaBlue to startBlue at each step.  However, due to the parenthesized order of arithmetic it has exactly the same round-off error problem as line 10 – it adds exactly one unit per step for my example numbers.  To try to avoid this problem, one might write (deltaBlue*step)/amountOfSteps in place of (deltaBlue/amountOfSteps)*step.  This will do accurate arithmetic except can easily overflow an int so should perhaps be written instead as (deltaBlue*(long int)step)/amountOfSteps.

Even if line 11 is rewritten to avoid truncation, round-off, and overflow errors, it still is subject to time-base errors.  Like the color numbers, the delay() parameter msPerStep is subject to accumulation of round-off errors.  During the for loop, several hundred milliseconds of error could accumulate, leading to mismatched or jittery color levels.  To avoid that error, instead measure elapsed time (as in line 13) and make color levels proportional to elapsed time (as in line 14).  In addition, one probably should change the for loop to a do { ... } while (elapsed < totalTime) loop, ie, let the loop run until the right time has passed, rather than some arbitrary number of passes.


Consider the sequence of values of "fadeIn". It starts at 8 and in incremented by 16.  So: 8, 24, ... 248, 264, ... .  It is never exactly 255.  So you never break out of your "for" loop.
There is only 1 delay in your example code.  It is difficult to associate the described behavior in your question and the location of the delay.
Arduino programming is actually C and C++ programming.  Developed at Bell Labs, this language has been around for decades and there are countless books on the subject.  Rather than rewriting your program (someone might yet still do this) I would recommend leaning C programming and if you want to write Arduino library software then C++ programming as well.


Arduino reading value from external devices on

Yes, with a small converter board it can be connected to an Arduino. The "9 pin serial cable" is very likely an RS-232 interface.

RS-232 is like UART with a few extra connections. Here is what the cable looks like:

Basically UART with flow control and other modem lines. Most likely it hasn't any of them conencted but that standard RXD, TXD and GND. These are all the connections needed for the microcontroller.

The voltage level of RS232 is however specified in a wide range (plus/minus 3V to 25V), so you need a converter chip (e.g. this one with a MAX3232, search for "RS232 to TTL Converter Board"). You need to measure the voltage levels with a multimeter to see what converter for what voltage rage you need.

Then conencting it to an Arduino is as simple as just connecting these 3 wires to the Arduino, either to the Hardware Serial port (D0, D1, GND) or via a software serial port.

Reference project:

http://www.picprojects.net/rs232_communication/

However, receiving the communication data is only half the battle. You still have to figure out what the sent data represents and what commands you can send the device. Without datasheets from the vendor, you are left alone. This is where reverse-engineering starts.

As a starting point, you can "eaves-drop" on the communucation that PC software does with the device by just connecting a USB-RS232 converter to your computer and connecting the RX line line to either the TX or RX line of the the target device's COM port. This allows you to see the entire communication exchange. From this you might be able to see what commands you're supposed to send. But as I said, from there it's unchartered territory.


As @Juraj mentions, pin 4 is the CS pin for the SD card. That pin has a volage divider of 1kΩ + 2.2kΩ on it (a total of 3.2kΩ) to ground. So yes, you do have a pulldown on that pin. 3.2kΩ is about 1/10th of the value of the typical pullup resistor internal to the chip, so pulls the output low enough to be seen as LOW unless you manually override it.
You can't use that pin as an active low input on that board - choose another, or use it as active high.


the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

  if(s % 100 > 28 || s % 100 < 12)

I would use a few brackets to make it clear to the compiler what you want it to do.


When should you worry about interference affecting the analog input?

Noise reduction involving Analog to Digital Conversions can be done in many ways.  Common software solutions involve averaging multiple conversions.  Exponential smoothing is one such method.  One advantage of exponential smoothing is that it can be applied to an endless stream of conversions.


I'm not entirely sure from your question if you want just the module or a whole breakout board.  If the latter, try this from adafruit. It can very easily do his either as mouse or keyboard and is well documented and supported so I think this would be much easier to get running initially. http://www.adafruit.com/products/1535


Problem on multiple interrupts operation on Arduino Uno

You are being way way too convoluted with this. You're overthinking it.

The code should be as simple as (LED stuff omitted):

volatile bool running = false;
const uint8_t switch1 =3;
const uint8_t switch2 =2;

void setup() {
    pinMode(switch1, INPUT_PULLUP);
    pinMode(switch2, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(switch1), turnOn, FALLING);
    attachInterrupt(digitalPinToInterrupt(switch2), turnOff, FALLING);
}

void loop() {
    if (running) {
        // Do something
    } else {
        // Do something else
    }
}

void turnOn() {
    running = true;
}

void turnOff() {
    running = false;
}

Note that what goes in loop() should be non-blocking, or at least have a reasonably short duration, so that it is able to pick up the changed running variable.

However, for something like this, interrupts are pretty pointless.


You need to add the following line of code in the setup() function:

    dht.begin();


Why is my transistor switched output so low?

The problem is that you are using an NPN transistor as a high side switch.
The voltage at the emitter of the transistor will always be about 0.7V below the voltage at the base.  The "high" output from the Arduino is 5V.  The emitter will be at about 4.3V.
Have a look at the Wikipedia "emitter follower" page.  The emitter follower is also called a common collector circuit. That explains the "problem" in more detail.  It is only a problem in so far as it is not the correct solution for your task.
You need to use a "common emitter" circuit.
This usage is commonly called a "low side switch."
That would look like this:

simulate this circuit – Schematic created using CircuitLab
If your black box really needs its input pulled up to 12V, then you would do something like this:

simulate this circuit
The resistor values and transistor part numbers are place holders.  The values of resistors you will need depends on the transistors you use.  The transistor selection will depend on how much current you need to deliver to the black box.
I see in a comment that your black box only needs a few milliamperes.  In that case, the shown transistors should work just fine.  The resistor values may be a little too high, but I think they'll be OK.

A couple of additional points:

The Arduino has PWM outputs, not PCM.
The output voltage for your black box will be pulsing if you use any PWM value lower than 255.  Your black box probably won't like that, and your voltmeter won't read a correct voltage.

You should use D2 as a digital output rather than PWM.  Just turn it on or off rather than fiddling with the PWM duty cycle.  Use "digitalWrite" instead of "analogWrite" on pin D2.


Is there a way to disable modules like ADC without a sleep mode?

Certainly there is.

  // disable ADC
  ADCSRA = 0;

You can disable lots of internal modules like this:

  power_all_disable();  // turn off all modules

See my page about power saving.

Majenko commented that turning off the ADC, while leaving the processor running was pointless. The real way to save battery power is to sleep, and it is possible to do that and still keep track of the time.

On my page about timers there is code to use a 32.768 kHz clock crystal to sleep and wake every second, which you could then use to alter the display on your watch.

Code from that page:

#include <avr/sleep.h>
#include <avr/power.h>

const byte tick = 3;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

void setup()
 {
  pinMode (tick, OUTPUT);

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 32 * 1024  (32768)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  31;              // count to 32 (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_adc_disable ();
  power_spi_disable();
  power_twi_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_usart0_disable();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

  }  // end of setup

void loop()
  {

  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);

  // sleep, finally!
  sleep_cpu ();

  // we awoke! pulse the clock hand
  digitalWrite (tick, ! digitalRead (tick));

  }  // end of loop

Whilst asleep, the processor uses very little power. In the example sketch I measured 1.46 µA current consumption, when the output was LOW, if running from 5V power supply, and 1.1 µA if running from 3.3V power supply.

Example setup:

I have two decoupling capacitors (the blue ones). A pull-up resistor on Reset.
A 32.768 kHz crystal between pins 9 and 10. A 22 pF capacitor between each leg of the crystal and ground.

A current-limiting resistor and a LED. It works, and toggles at 1 Hz. When asleep (LED not on) it draws 1.46 µA as mentioned above.


The Arduino API for ESP32 does not support your desired configuration.

The ESP32 is capable, but there is no easy "Arduino" interface to configure it.

Instead you will have to directly interface with the ESP32 SDK and configure things manually.  That won't be easy.

This example code shows you how it can be done - however that code is not designed to run in the Arduino environment, so you will first need to understand exactly what it is doing and then adapt it to suit.


I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.

const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}


Controlling image display on LED matrix by buttons

OK. Figured out a solution which is working for me. Upon reading a forum on Arduino.cc. That stated a nice analogy to handle this issue.

You have something to heat up on stove while also waiting for an important email which you have to respond to immediately. (You only have a PC in the farthest corner of house at which you have to monitor your outlook :D) How will you do both tasks simultaneously? Run the stove for 10seconds, go to PC to check email, return to stove, run it again for 10 seconds, then again go to PC to check email. Do this until you get the email or your food gets hot enough.

To implement this in our program. I read the states of 2 buttons at start of the main loop. Store their values in 2 variables. Then check the values to check if some button is pressed. if value A is 1 and B is 0, call function A, if A is 0 and B is 1 call function B. The called function comprises of the scan routine. So when called, it performs 1 scan and comes back to the main loop. If no button was pressed meanwhile, the variables have same values, so the same function is called again and it performs the 2nd scan. if a button was pressed meanwhile, then 2nd function is called instead of the 1st one. The speed of all this is enough so that the user does not experience any delays, neither Arduino misses a button pressed while executing the scan.

The LEDs started to flicker when I implemented this code. So I further reduced the delay in the scan routine (time for which each LED is lit before turning it off and lighting the next one) from 300 microsecond to 100 and all went fine. My matrix of 64 LEDs is working fine however I assume that if matrix goes beyond some 100 LEDs then problems like delay or flickering or reduced brightness may arise.

Here is the complete code

byte img1[] = {
    B01100110,
    B11111111,
    B11111111,
    B11111111,
    B01111110,
    B00111100,
    B00011000,
    B00000000
};

byte img2[] = {
    B00000000,
    B01100110,
    B01100110,
    B00000000,
    B00011000,
    B10000001,
    B01000010,
    B00111100
};

const int rowPins[] = {13,12,11,10,9,8,7,6};
const int columnPins[] = {5,4,3,2,14,15,16,17};

const int but1 = 18;
const int but2 = 19;

int but1State = 0;
int but2State = 0;
int but1Now;
int but2Now;

int value1;
int value2;

void setup() {

    for (int i = 0; i<8; i++){
        pinMode(rowPins[i], OUTPUT);
        pinMode(columnPins[i], OUTPUT);
        digitalWrite(columnPins[i], HIGH);
    }

    pinMode(but1, INPUT);
    pinMode(but2, INPUT);

    but1State = digitalRead(but1);
    but2State = digitalRead(but2);
}

void loop() {

    but1Now = digitalRead(but1);
    delay(5);
    int but1Now1 = digitalRead(but1);

    if(but1Now == but1Now1)
    {
        if(but1Now != but1State)
        {
            value1 = 1;
            value2 = 0;
            //show(img2);
        }

        but1State = but1Now;
    }

    but2Now = digitalRead(but2);
    delay(5);
    int but2Now1 = digitalRead(but2);

    if(but2Now == but2Now1)
    {
        if(but2Now != but2State)
        {
            value1 = 0;
            value2 = 1;
            //show(img2);
        }

        but2State = but2Now;
    }

    if(value1 == 1)
    {
        show(img1);
    }

    if(value2 == 1)
    {
        show(img2);
    }
}

void show(byte*image) {

    for(int row = 0; row<8; row++)
    {
        digitalWrite(rowPins[row], HIGH);

        for(int col=0; col<8; col++)
        {
            boolean pixel = bitRead(image[row],col);

            if(pixel == 1)
            {
                digitalWrite(columnPins[col], LOW);
            }

            delayMicroseconds(150);
            digitalWrite(columnPins[col], HIGH);
        }

        digitalWrite(rowPins[row], LOW);
    }
}


Nextion Display not getting updated data

recvRetCommandFinished err means something is wrong with the serial communication between the Arduino and the Nextion display; it is what recvRetCommandFinished() prints when there is an error.
Check if you are using the right pins (TX1 and RX1 for Serial1) for the serial connection to the display, the actual connections you made (RX1 to TX, TX1 to RX), the baud rate, and the cable.


The ADS7805 is old but still a pretty good ADC. I could imagine that you just have a few lying around that you want to use. I would simply wire it to two parallel in / serial out chips like the 74HC589 or CD4021 as used in this example:
http://www.arduino.cc/en/Tutorial/ShiftIn

Start the conversion as described in Duncan C's answer and then simply clock in all 16 bits. I think you could then probably get away with 4 or 5 control lines.


how to use capacitive touch keypad without using CapacitiveSensor.h Library

Here's one: Microchip mtch6102, though it might be a little more complex than you're looking for.  All the others I found with a quick search were surface mount or single button controllers.  You might be able to multiplex a single button controller like the Atmel AT42QT1011, but I don't know what the settling or reset times are.  It may take to long to change pads, reset the chip, then wait for settling/calibration time (if any).


Spilt string and convert to float to compare

Okk very simple approach :-

Suppose this is your string variable inStr = "Temperature: 28.22C"

String inStr = "Temperature: 28.22C";
int indexOfSpace = inStr.indexOf(' ');
//this stores the address of the space character in the string.
int indexOfC = inStr.indexOf('C');

String Temp = inStr.substring(indexOfScace+1,indexOfC);
//as the parameter for the function is supposed to be the starting point of the string to
 be extracted and one more than its ending point.

//Now to convert to float

float TempFlo = Temp.toFloat();


Yes. As long as you take into account that the outputs of the Arduino will be 5V so you may need to reduce that to 3.3V for the 3.3V sensor (if it has any connection to an output).


[SOLVED]SIM7600 Module Power up by Arduino Uno doesn't work

The GSM module requires a 5V 2A source and my Arduino Uno cant draw for it, my solution is to use a power bank that can draw 5V 2A for powering the GSM module and jump PWR pin to GND (manual said) the NET led start flashing and module can working but TX, RX pin still there for comm.


Can I have backup power for an Arduino device?

you could set up a relay to work in reverse with the mains power,

have your backup battery connected to the gate contacts of the relay, and then use the mains power running your project to open the relay and keep it open as long as there is power. if the mains turns off, then the relay closes and the battery is connected.

you might want to put something in line with the power to the arduino to make sure you don't get any spikes when things switch.

hope this helps as i love kittens


Arduino board as USB/serial for a Nano with broken USB

As explained in comments by Chris Stratton, both the Mega16U2 on the Uno and the USB/serial chip on the Nano are competing for the signal level. Removing the resistors on the RX/TX lines between the USB/serial chip and the ATMega on the Nano board will prevent it from interfering with the signals exchanged with the Uno.


General Question about fast Serial Communication and Arduino

You are sending data at ~70kbps. Provided you use serial rate greater than this (115.2 kbps or faster on the Arduino) there should be no problem, assuming you samples are processed quickly enough. This seems to be the case.

Your problem seems to be on the Mac. With a quad core CPU on a fast multitasking machine this should not be an issue. If you are having problems this would be in how you are processing the data. I am not familiar with Processing but you could do this in any language. You need to separate the data logging from the processing and display task. This could be as simple as running a logger and piping the data into a display program.

This is not an Arduino issue (or even a Mac issue), you should ask on https://stackoverflow.com/. NOTE if you want help there you will need to give more detail of the code you are running in the Mac.


How do I program an LCD screen and do I need an Arduino

OLED screen is really good looking for both indoor and outdoor and I think you have made a good choice.
You need the following things to complete your project easily.

Display (which you have already found one
Arduino (why? easy to program, lots of libraries available, and also tutorials)
RTC - Real-time clock - This is another IC (DS1307, for example)

Arduino need not be UNO. You can use ATTiny85 MCU. the programming will be the same as how you program a UNO. ATtiny85 has no builtin I2C, but the libraries are there to emulate I2C to be connected to OLED displays.
If you want to avoid the third option, go with internal timekeeping alone. But, over a week, you will see the time difference (the internal clocks of the MCU are not accurate, so the time will lead or lag over a period of time)
have you thought about a keypad or a single button to give the option to the user to set the time?


You need to adjust the value of Rc, the collector current limiting resistor. When replacing the single LED with a strip of N LEDs of the same kind, you have increased N times the current required (that's why you need to use a BJT, because the Arduino I/O pins won't supply that much current). So, you need a new value for that resistor, let's call it Rc', much lower: Rc' = Rc/N. Otherwise, the old value may limit the current far below of what the LEDs need to light up.

But that's not all. You also need to add 2 resistors:

Rb: a current limiting resistor between D3 and the BJT base. Its value should be in the range 330 - 2200 Ohm. The higher the current draw of the LED strip, the lower the value of Rb should be.
Rpd: a pull-down resistor between the BJT base and ground to avoid it floating while D3 is not initialised as OUTPUT. Make it at least 20x the value of Rb.

All this should be enough to make it work.


Where to connect shield in USB power supply for Arduino?

If the supply for the Shield is 5V, then you can use one of the 5V lines on the Arduino to power the Shield, plus a common ground of course.


I'm pretty certain that your code is the problem.  You are relying on timing rather than events.  Using delays is OK when you are just interfacing to one sensor but when you start mixing them you end up with issues like this.

You are reading the vibration sensor once every second if the distance is 4.  So any vibration needs to occur for more than one second, or at exactly the right time.  I think you need to look at a better way of coding the solution without using the big delay statements, maybe look at interrupts.


Why does my code or Serial Monitor hang with analogRead?

Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.

I suppose, that analogVals[] is declared as int and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome 48 bytes for all your others variables (including int i in the for cycle and Serial outside it) and stack for calling functions (like analogRead and sq) and all theirs variables and functions and arguments.

So int i = 2B, Serial = 2B, sumOfSquares = 2B, "Sum of squares: " = 17B of what I see takes anothe 23 bytes of those 48 bytes leaving us with only 25 bytes for all else.

I bet, that you try to use more REAM, than you have and so your stack overflows and

destroys some variable content on the vay
is overwriten by assigning to some variables, which then leads to all sort of problems.


Why doesn't millis() use 1 µsec or 1 msec interrupt?

One microsecond is only 16 CPU cycles.

The CPU needs 4 cycles to prepare itself for servicing the interrupt
(save the program counter, load the interrupt vector and clear the I bit
in SREG). The interrupt vector itself is a jmp instruction that takes
2 cycles. When the ISR is done, it executes the reti instruction
(return from interrupt) that takes 4 cycles. This means you have only 6
CPU cycles left for:

saving the context, i.e. pushing to the stack any register your ISR
may modify (2 cycles per push)
doing the actual ISR work
restoring the context (2 cycles per pop)
doing also some useful work in the main program.

There is no way you can do half of this in only 6 cycles.

Edit: I did a couple of experiments to gain more insight on the cost
of running an interrupt too often.

In the first experiment, I used your initializeTimer0CTC_Mode()
function to interrupt every microsecond the following program:

// This ISR consists of a sigle `reti' instruction.
EMPTY_INTERRUPT(TIMER0_COMPA_vect);

#include <util/delay.h>

int main(void)
{
    initializeTimer0CTC_Mode();
    DDRD |= _BV(PD2);       // PD2 = digital 2 as output
    sei();
    for (;;) {
        PIND |= _BV(PD2);   // toggle PD2
        _delay_us(499.75);  // 0.5 ms - 4 cycles
    }
}

The program is meant to generate a 1 kHz signal on pin 2, and
that's exactly what it does if the sei(); statement is commented out.
With the sei(); statement, the frequency drops to 375 Hz. This
shows that processing an empty interrupt (an ISR consisting solely of
the reti instruction) costs 62.5% of the CPU power, leaving 37.5% to
the main program. 62.5% is exactly 10 out of every 16 CPU cycles,
which confirms the cycle count of the first part of this answer.

The second experiment was to compile and disassemble your ISR. Here is
what I got:

__vector_14:
    push r1
    push r0
    in   r0, 0x3f  ; 1 cycle
    push r0
    eor  r1, r1    ; 1 cycle
    push r18
    push r20
    push r21
    push r22
    push r23
    push r24
    push r25
    push r26
    push r27
; static uint32_t prevMicro;
; oneMicroCounter++;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0104, r24
    sts  0x0105, r25
    sts  0x0106, r26
    sts  0x0107, r27
; if (oneMicroCounter - prevMicro >= 1000)   {
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    lds  r20, 0x0100
    lds  r21, 0x0101
    lds  r22, 0x0102
    lds  r23, 0x0103
    sub  r24, r20   ; 1 cycle
    sbc  r25, r21   ; 1 cycle
    sbc  r26, r22   ; 1 cycle
    sbc  r27, r23   ; 1 cycle
    cpi  r24, 0xE8  ; 1 cycle
    sbci r25, 0x03  ; 1 cycle
    cpc  r26, r1    ; 1 cycle
    cpc  r27, r1    ; 1 cycle
    brcs 0f  ; 1 cycle if the if() condition is true, 2 otherwise
;   prevMicro = oneMicroCounter;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    sts  0x0100, r24
    sts  0x0101, r25
    sts  0x0102, r26
    sts  0x0103, r27
;   oneMilliCounter++;
    lds  r24, 0x0108
    lds  r25, 0x0109
    lds  r26, 0x010A
    lds  r27, 0x010B
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0108, r24
    sts  0x0109, r25
    sts  0x010A, r26
    sts  0x010B, r27
; } }
0:
    pop  r27
    pop  r26
    pop  r25
    pop  r24
    pop  r23
    pop  r22
    pop  r21
    pop  r20
    pop  r18
    pop  r0
    out  0x3f, r0  ; 1 cycle
    pop  r0
    pop  r1
    reti           ; 4 cycles

Unless otherwise noted in comments, every instruction of this listing
takes 2 cycles to execute. Note the large number of CPU registers saved
(push) and restored (pop), and the large number of SRAM accesses
(lds and sts): three 4-byte variables read and written back.
Counting the total number of cycles taken by this ISR is left as an
“exercise to the reader”.


The best and easiest solution I've found is to use the Bluefruit EZ-Link from Adafruit.  They have a module you plug into the Serial/Power/reset pins (link here) or a shield for the uno (link here).  They've also got a great description and how-to guide (link here) that is pretty good.  It basically appears as a serial bluetooth link in the arduino IDE and you program it like normal.  It has the added benefit of being of use not only for programming, but also for sending and receiving data.


ESP - Nodemcu amica - attachInterrupt crash program

thanks @Juraj.

Ok, so all you need is rewrite all your interrupt function.
For example:

void getStatusFromMaster()

to

void ICACHE_RAM_ATTR getStatusFromMaster()


How to chose softserial library use on Arduino project?

I think your problem is that you need 4 serial ports.

With software serial that's just not going to happen:

SoftwareSerial can only receive on one serial port at any given time.
AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.


Difference between Wire.setClock() method and TWBR method for changing I2C Frequency

Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.

There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

  Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

  Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.

Cheers!


Measuring frequency of 3-wire 12V fan on Arduino Uno

The pulseIn measures the duration of a high pulse on the pin.  The reference page explains it as well as I ever could.  If there is a specific thing you don't understand from it, please ask.  However, I don't think it will achieve what you want.

The circuitry in the fan connects the third (yellow?) wire to ground twice per revolution of the fan.  To make this into a "pulse" you need to pull the pin high.  Twice per revolution, the fan will pull it low.

What you now have is a signal which, for every revolution of the fan, goes HIGH, LOW, HIGH, LOW.  We want to measure the time from one rising edge to the next.  This is the time for half a rotation of the fan.

Here's some untested code:

// Wait for signal to go low
while (HIGH==digitalRead(pin)) { /* Do nothing */ }

// Start timing
unsigned long start_time = micros();

// Wait for signal to go high and low again
while (LOW==digitalRead(pin)) { /* Do nothing */ }
while (HIGH==digitalRead(pin)) { /* Do nothing */ }

// Stop timing
unsigned long end_time = micros();

// How long did that take?
unsigned long duration  = end_time - start_time;

That code can be improved in various ways but I hope it will let you understand what's going on.

That tells us how LONG half a cycle takes.  You can easily find how long a whole cycle would take -- double it.  If you want the frequency in revolutions-per-minute, you need to work out how many whole cycles you can get in a minute, which is the same as the number of half-cycles in half a minute:

unsigned long rpm = 30000000L / duration;


Question about number of sensors for Arduino Mega

It depends on what you want the Arduino to do with them. There is no (not much) penalty for having many sensors connected. Where it begins to matter is when you need to read at rates which, collectively, tax the speed of the processor to meet the total demand. Your project specs will really determine how many sensors make sense. The other place that sensor count might matter is if your project is to be battery powered, and the sensors draw some amount of current even when they're not being used. In a battery powered project, you'll want to be able to power-down everything that isn't being used at a given time, to maximize the system's overall run-time on battery.

The Mega, and I'm assuming you mean Mega 2560, has 50-some odd I/O pins available, so you have a lot of potential connectivity, and I think it's safe to say, the designers intended for them to be used.


You have multiple options:

According to jsotola's remark: the easiest is to multiply your value by 2, store it, and after reading, divide it by 2. In one byte you can store a value from 0 to 127.5 (255 / 2), or if you use signed from -64.0 to +63.5. Of course you also can use an offset in case you know the value cannot be less than e.g. -20.
If you need a higher range, you can still multiply it by 2, but store it in two bytes. Split the value in a 'high value' (value % 256) / 256, and a 'low value' (value % 256).
If you want to store the value completely, than use sizeof(float) to find the length, and a for loop to write each byte, starting from the first byte of the float until the last one.


It's hard to tell without further testing. Do the following:

Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.
Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)
Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.
Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?

Report your findings by updating your question.


Your 2nd for loop should look something like this:

int fromLocation = 0;
int toLocation=0;

for (int i = 0; i <10 ; i++)
{                 /////// LINE 80

    toLocation += tempArray[i].toInt();

    tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
    Serial.print("From Number = :");
    Serial.println(fromLocation);
    Serial.print("To number : ");
    Serial.println(toLocation);
    Serial.print("I just translated :");
    Serial.println(tempArray2[i]);
    fromLocation += tempArray[i].toInt();
  }
}

On the first pass through the loop, fromLocation is 0. toLocation starts at 0 and gets the value in tempArray2[0] added to it.

After extracting a string, you add the current array value to fromLocation to advance the pointer to the beginning of the next string.

Note that String objects are very inefficient way to save 2 digit numbers. It would be better use an array of ints, and write code that extracts 2 characters at a time into int values.

With only 20 String objects it's not a huge deal, but bear in mind that String objects take a lot of memory overhead on a memory-starved platform like an Arduino. Better to learn how to use C strings.


Would someone provide an example of extracting data from a char array?

When working with Arduino, cplusplus.com is your friend. Scroll down and look on the left side under (string.h). Lot's of great char functions there. Other useful functions such as iota() - cplusplus.com.
Here's one way to accomplish the parsing of the input data.
// Sketch uses 2064 bytes (6%) of program storage space.
// Global variables use 323 bytes (15%) of dynamic memory.
// Arduino IDE 1.8.9.
char line[] = "04-23-2020,James";
char Name[100];
unsigned int Month, Day, Year;

// Make an attempt to validate the input data.
byte Counter = 0;

void setup(){

  Serial.begin(9600);

  char * pch = strtok(line, "-,");

  while(pch != NULL){
    if(Counter == 0){Month = atoi(pch);}
    else if(Counter == 1){Day = atoi(pch);}
    else if(Counter == 2){Year = atoi(pch);}
    else if(Counter == 3){strcpy(Name, pch);}
    pch = strtok(NULL, "-,");
    Counter += 1;
  }

  // Print out the data.
  if(Counter == 4){
    Serial.println(Month);
    Serial.println(Day);
    Serial.println(Year);
    Serial.println(Name);
  }
  else{
    Serial.println("Error");
  }

}

void loop(){}


I want to stream audio from an Arduino to a device on the wifi

An Arduino can do this, but this is a very advanced problem on an Arduino. It sounds like perhaps you need something more plug-and-play. In that case, buy a Raspberry Pi 4 starter kit and a USB microphone, and start working on the problem from there. The Raspberry Pi 4 is a Linux computer, so everything you do will be writing scripts or programs (in any language: it's just a regular computer, so use Python, C, C++, Java, bash, whatever you want) to run on its Raspberry Pi OS (formerly called Raspbian) Linux operating system.
If you go this route, you'll want to ask your questions on the Raspberry Pi Stack Exchange as well.
Keep in mind the question you asked is too broad. You are generally expected to do your own background research and then ask more specific questions, demonstrating what you've already tried.
Getting an Arduino to send out microphone data is, like I said, a very advanced subject and project (think: professional level / expert hobby level) unless you can Google and find pre-made libraries and how-tos on the subject.
Essentially, for the Arduino Uno route you'd need to do some fancy high-rate ADC sampling with a modified ADC clock rate in a special ADC mode which takes repeated samples and then interrupts your code when a sample is ready, rather than just doing normal analogRead() since that is both blocking/polling-based which wastes clock cycles and creates sample jitter which causes audio distortion, and then you'd need to send this data via some Wifi shield (add-on board) or an ESP8266 or something, or via some other technology (wired or wireless) to a computer to pass it on to the internet. This may involve binary packetization/bit-packing, error checking, buffering, etc., all of which is its own special skill to acquire.
Some of my projects have taken me 3+ years to complete them, since I began complicated projects as a beginner. This is one of those multi-year type projects for a beginner for sure.
(Heck, if you give me two LEDs and two resistors and an Arduino Nano, with those items alone, I can send you on your way to work 8 hrs a day for 3 months straight on projects. It's easy to under-estimate the complexity of something until you're neck-deep in it.)
Update: if you want to go the Arduino route, here's some tips to get you on a search route more likely to get you to a solution faster. Again, no doubt an Arduino Uno can do this. It for sure can. But, a faster Arduino can do it easier and better. So:

Google search for projects on Adafruit which may do this. Ex: Google search for "adafruit stream audio". Their tutorials are 2nd to none--the best in the world--and their products top-notch.
Search for projects on Sparkfun which may do this. Ex: Google search for "sparkfun stream audio". They also are excellent and have world-class tutorials.
Search for projects which do this with a Teensy, Zero, Due, or other high-speed 32-bit microcontroller, instead of an Uno. Audio processing is more difficult for a slower 8-bit Uno than for any of those 3 Arduino/Arduino-compatible devices.
Also look on Instructables.com for tutorials and help.
One more thought: Google search for "atmega328 stream audio to wifi" (an Uno uses the ATmega328 microcontroller, so that's a good search term to use)

Update: also take a look at this tutorial by GreatScott (who is also super awesome) (https://www.instructables.com/id/Make-Your-Own-Spy-Bug-Arduino-Voice-Recorder/), which uses this AVR-based (for ATmega328: Arduino Uno, Nano, Pro Mini, etc., or ATmega2560: Mega) advanced audio library for both recording and playing back audio. See:

https://github.com/TMRh20/TMRpcm

Recording Audio
Audio streaming over NRF24L01+ radio link


It's your responsibility to format the time properly, not the library. The library just gives you a number. If you want a leading zero then it's up to you to provide that leading zero.

For example:

if (now.seconds() < 10) {
    lcd.print("0");
}
lcd.print(now.seconds());

Or:

char timestr[9];
snprintf(timestr, 9, "%02d:%02d:%02d", now.hours(), now.seconds(), now.minutes());
lcd.print(timestr);


Routing Matrix with a large number of I/O

I would use a port expander that uses I2C for communications. One example is the PCA9555. You can add up to eight by setting the address bits (A0-A2). This will give you up to 64 outputs to control the selection bits of the 4051s.

While this is all intelectionally possible, from a logic perspective, I have concerns about how this can be practically implemented. I think you need to go into more detail on what you plan to do. What the purpose is.

Also, there are larger chip for do analog matrix switching. AD75019 is one example. https://www.analog.com/en/products/ad75019.html

They are more expensive but cost should not be the primary factor. Getting a design to work is more important.

Do a search for "Crosspoint Switch Array" for more chips like this.


How is a local variable address retrieved/returned inside the CPU of Arduino?

Just as an experiment, I tried the following:

void bar(int *);

void foo()
{
    int x = 5;
    int *p;
    p = &x;
    bar(p);
}

And here is what gcc translated that into (comments mine):

__SP_H__ = 0x3e
__SP_L__ = 0x3d
__tmp_reg__ = 0
foo:
    push r28            ; save r28
    push r29            ; save r29
    rcall .             ; make room on the stack
    in   r28, __SP_L__  ; copy SP into r29:r28 = Y: LSB...
    in   r29, __SP_H__  ; ... and MSB
    ldi  r24, lo8(5)    ; store x in a register: LSB...
    ldi  r25, 0         ; ... and MSB
    std  Y+2, r25       ; copy x into the stack: MSB
    std  Y+1, r24       ; ... and LSB
    movw r24, r28       ; r25:r24 = Y
    adiw r24, 1         ; r25:r24 = Y+1 = &x
    call bar            ; call bar(&x);
    pop  __tmp_reg__    ; release the two bytes...
    pop  __tmp_reg__    ; ... of stack space
    pop  r29            ; restore r29
    pop  r28            ; restore r28
    ret                 ; return

Expanded comments:

The instruction rcall is normally used to call another function. Here
it's calling the following instruction, so it doesn't affect the program
flow. It's only a trick: as rcall saves the return address into the
stack, it makes the stack grow by two bytes, and is used here as an
optimized way of reserving to bytes of stack space for storing x.

Next you see the stack pointer being copied into the r29:r28 register
pair, also known as “Y pointer”. The stack pointer is a CPU register
holding the address of the top of the stack, namely of the first free
slot. As the stack grows towards the bottom of the RAM, at this point
it looks like this:

address | SP = Y | Y+1 | Y+2  | Y+3 | Y+4 | Y+5  |  Y+6  |...
--------------------------------------------------------------
data    | (free) | room for x |  saved Y  | return addr. | ...

Next you see the value of x being placed first in a register pair
(r25:r24), then on the stack at the addresses Y+1 and Y+2.

The instruction mowv copies a register pair, so now you have a copy of
the stack pointer in the pair r25:r24. The instruction adiw adds an
immediate value (here, 1) to a register pair, so that now r25:r24 holds
the address of x. Finally, the function bar() is called: per the
calling convention, the argument is to be passed in the r25:r24 pair.

A few final remarks:

I passed the pointer to another function just to make gcc believe that
I am actually using that pointer, otherwise it would optimize out
the whole code into a function that does noting but return.
You don't need to create a pointer variable to hold the address of
x: calling just bar(&x) compiles into the very same assembly.
Most local variables are assigned to CPU registers. Only because I am
using the address of x did this variable get stored in the stack.
The compiler output is very sensitive to the surrounding code, the
compiler version, the optimization options, and so on. So you should
consider all this as only an example.
If you do not completely understand what each instruction is doing,
you should now take a look at the AVR Instruction Set Manual


How to remove any previous program from Arduino?

Just upload a new one. I frequently "blank" an arduino when I'm done with it by uploading "Blink.ino" from the examples included with the IDE. (The only reason I've had to remove old code is to avoid an issue where I might later wire up the Arduino in a way that is dangerously incompatible with the old code running on it.)


How do I know if bootloader flash was successful?

See my page about burning bootloaders.
The sketch there has a "verify" option so you can check if the bootloader was burned.
See my post What happens when code is uploaded using the bootloader?.
With Optiboot installed you expect to see three flashes:

As for your other problems, see Have I bricked my Arduino Uno? Problems with uploading to board.
You may well not have set the fuses correctly.


If you can't do anything about the hardware you're using (lower powered USB interface, etc) then the top thing you can do is run the wifi radio as little as possible. The radio uses a lot of power, so the less time it's on for and the less network traffic you send, the less power you'll use.

When the board comes out of deep sleep and reconnects on wifi again, it performs a DHCP exchange to find out its IP address. Configuring a static IP address, network mask and router address will avoid this and let the radio stay on for less time.

The ESP8266 SDK also automatically saves wifi credentials to flash every time you call WiFi.begin(). This is probably not what you want. Disabling this will also help save power.

The new wifi connect code would look something like this:

IPAddress ip( 192, 168, 0, 1 );
IPAddress gateway( 192, 168, 0, 254 );
IPAddress subnet( 255, 255, 255, 0 );

WiFi.forceSleepWake();
delay( 1 );
WiFi.persistent( false );
WiFi.mode( WIFI_STA );
WiFi.config( ip, gateway, subnet );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

You'd need to replace the specific IP address, gateway (router) address and subnet mask with ones that work for your network. And you'll need to allocate a static IP address either from a range that your router sets aside, or you'll need to configure your router to permanently allocate the address - how you do this totally depends on the router you're using.

The other way to save wifi-related power is to use as lightweight a protocol as possible and do as little work while wifi is on as possible.

For instance, suppose you need to compute a complicated piece of data that you're transmitting over wifi. Maybe it's a chunk of XML or a JSON string. Or you need to read a slow sensor. Do all that work before you enable wifi, and have the data ready to transmit.

Or if you're receiving data, if at all possible, finish receiving the data and turn off wifi before you do any work with the data.

If you have any choice in the matter, use as simple a protocol to transmit the data as possible. UDP is ideal - you can transmit a single packet (but you won't know if it's been received). TCP requires several packets of handshake at connection startup and shutdown. If you use a secure (SSL) connection over TCP that's even more data and computation.

If your very top priority is battery life, UDP is ideal though it's not reliable and not secure.

There's a great series of articles on power saving at

https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-1/

https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-2/

https://www.bakke.online/index.php/2017/05/22/reducing-wifi-power-consumption-on-esp8266-part-3/

Part 1 is about measuring power use; part 2 is about switching the wifi radio on and off and part 3 gets partly into the stuff I talked about above.


why sound appears between VCC and GND pins in esp8266 module?

It's called "noise" and is to be expected. Wi-Fi devices are generally very electrically noisy - and the ESP8266 is no exception.


For I2C you can try http://www.linear.com/product/LTC4312

This will allow you to make two I2C networks to address all the nodes.

However, the wiring for I2C will be a nightmare, but it might be necessary if you want the nodes to be independent.


Why does Serial.print print only a value for 0-84 for a 100 integer array?

It's because you're using exit(0).  That turns off interrupts and goes into an infinite loop. However, serial printing is first placed into a buffer, and each character is then removed from that buffer in turn and sent out through the serial port.

That's all fine, up until the end when you use exit(0);, and what is left in the serial buffer to send never gets sent because interrupts are disabled.

There is never really any cause to use exit() on a microcontroller - after all, where can it "exit" to? There's no OS to exit to. So it does the next best thing which is as close to doing nothing as reasonably possible.

Instead, if you want to "stop" your program you should use a simple while(1); which will allow interrupts to still trigger.

Alternatively, if you really want to use exit(), you should flush the serial first:

Serial.flush();

That function will block until the transmit buffer has been fully emptied by the interrupt and the last byte has left the UART's TX shift register.


Relay starts trigger about 6 times when connecting arduino to laptop

The markings on your relay suggest the coil is for 5VDC. But you have the coil supply wired to 3V3. Move the coil supply to 5V, and try again.


Connecting TFT Display MI0283QT-9A to ESP32

It sounds like you want a 4-wire 8-bit serial SPI compatible interface.  To get that you have to set the IMx pins to the right state to enable that interface.  That means:

IM0 = LOW
IM1 = HIGH
IM2 = HIGH
IM3 = HIGH

You can hard-wire those to GND for LOW and +3.3V for HIGH.

That will then configure it to work in the right mode for you, where it gives you access to the following pins:

| Display  | ESP32   | Function                    |
|----------|---------|-----------------------------|
| SCL (RS) | SCK     | Serial clock                |
| SDI      | MOSI    | Serial data Master -> Slave |
| SDO      | MISO    | Serial data Slave -> Master |
| D/CX (WR)| DC      | Data / Command register sel |
| CSX      | CS      | Chip Select (Active Low)    |
| RST      | RST     | Reset                       |


Reading an output analog pin with an input analog pin

Can someone please let me know what I'm not doing correctly?

the analog (output) pins on those chips are not exactly analog: they are pwm output pins. as such, their output is either 0 or 1, nothing in between, with the chance of being 1 equal the duty cycle.

that kind of output can be a steady "analog" if you run it through a low pass filter - the simplest would be an rc filter where the r is in serial with the c.

so if you hook th epwm pin up to a rc filter and adc the output of that rc filter, you will get a real "analog".


Just sanity-checking a concept... poor man's self-monitored alarm system

NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.

You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.

You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.


Implementing sending from N and recieving from N with FreeRtos and RF24 radio module

Solved it by simply repeating

gpio_enable(SCL, GPIO_OUTPUT);
gpio_enable(CS_NRF, GPIO_OUTPUT);

// radio configuration
radio.begin();
radio.setChannel(channel);
radio.setAutoAck(false);

before opening a new writing pipe.


How to arrange my code block to make it work smooth and correct

I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec).
Although there's nothing wrong in placing the

if(moistureOneSensorValue >= ...)
...
...

codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the void loop() itself and then place a switch case in the doSomething() function.

You can also use the data from the RTC to check moisture and do something:

void setup(){
...
time = DS3231.time(); //Time at the beginning
}

void loop(){

timeElapsed = now() - DS3231.time();//seconds elapsed

if (timeElapsed >= DELAYNI){
    moisture1 = analogRead(MOISTURE1); // Read ADC value
    moisture2 = analogRead(MOISTURE2); // Read ADC value
    updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
    switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
time = DS3231.time(); // Update the time

    }

}


EasyEDA is not designed for diy prototypes like TinkerCAD is.  EasyEDA's purpose is to simulate electronic circuits and design circuit boards for those circuit designs.  Because of this they don't have a breadboard object because there would be no point in having one, since you can just connect virtual wires in the schematic mode and wire traces in the board design mode.
Furthermore, it doesn't support simulating a full Arduino board with code.


Every time through your loop, the LED is being set to HIGH voltage. This may or may not be followed by setting it to LOW voltage, but since the loop runs again immediately, it's immediately set back to high voltage. This happens so fast that the LED essentially "feels" half voltage and it will dim. Your code needs to be more like this...

void loop() {
  if(digitalRead(10) == LOW) {
    digitalWrite(13, LOW);
  } else {
    digitalWrite(13, HIGH);
  }
}

OR... even like this...

void loop() {
  digitalWrite(13, digitalRead(10));
}


Direct 5V current based on analog signal

If you have 4 pins available, you could use charlieplexing to selectively light up 12 led.

Alternatively you could use some IC. You could use the one Greg suggested.

Or you could use a shift-register. This requires only 2 or 3 pins, an will enable you to light up any one or more leds at the same time. Most have 8 outputs, but you can connect one to the other (daisychain), so with 2 shift-registers you can individually turn on/off 16 leds. You can easily control these using arduino's shiftOut command.

You could also use a port-expander using I2C to talk to it. More complicated, and a bit more expansive. But also more powerful. It will require only 2 pins (A4, and A5).


Need to turn on project twice in order for screen to work!

Adding a 100ms delay before calling oled.init(0x3c); oled.clear(); oled.startScreen(); made this problem go away.


Question regarding powering Arduino through the USB Port

Yes, the ATMEGA328 processor will work without any problem, in fact if you go in the power informations section on the datasheet, you will find that the processor can run from a little less of 3V to a maximum of 5.5V.

Just be careful, because the processor works at that power, but the board will need from 5 to 5.5V.


Maybe the 5v regulator? Hard to say without the symptoms.


Build error on a phantom file that is not in my sketch, but somehow created in AppData/Local/Temp\build

I found the offending file in a sub directory of the C:\Software sketch directory.  I had a subdirectory called trash, and the Arduino build found it from there, and put it in AppData then referenced the error from there.


Homemade soil moisture analog value reading jumping from 0 to max

You are constantly running .5mA through 2 nails in wet earth. What are they made of, that won't undergo some electrolysis in 1/2 hour? Gerben appears to have hit the, er, nail on the head in one, above.

You can avoid this to an extent by using a.c. drive to the probes, which reverses the effect so they only tarnish at about the normal rate for metal X in soil.


With that specific board, yes you can.  According to this review:

  Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.


By sheer luck your lock solenoid looks very similar to this one (similar spec too "Draws 650mA at 12V") and they have a working circuit for it over here so look at that and see what they used to drive it. Apparently it's a TIP120, so the peak/draw current is probably higher than that ballpark figure, which I suspect is for the hold.

Overengineering the transistor by an order of magnitude or so (for a poorly spec'd solenoid part) ensures it doesn't go pop so easily. Also, a Darlington like TIP120 is very easy to drive from the arduino or some other microcontroller.

A similar project using the same solenoid lock used an IRLB8721 (power MOSFET) instead, which is even more beefy in terms of load current it can handle.


How to find the pin map for the LCD 1602 I2C adapter module?

The ￼tronixstuff page about PCF8574-based backpacks for LCD modules and Arduino (with material that also appears in an instructable) includes a sketch that most likely will work with that backpack.

Once you've identified which I2C library to use, and the appropriate object instantiation, most of the general API description (that is, “the commands to deal with this module”) as shown at arduino.cc's LCDi2c Library page and at arduino.cc's LCD API 1.0 page will apply.

The I2C library-include and the appropriate object instantiation for the backpack shown in your link probably will look much like:

#include <LiquidCrystal_I2C.h>
...
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);

For documentation of what the numbers mean, see lines 82 to 90 of LiquidCrystal_I2C.h:

@param      lcd_Addr[in] I2C address of the IO expansion module. [...]
@param      En[in] LCD En (Enable) pin connected to the IO extender module
@param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
@param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
@param      d4[in] LCD data 0 pin map on IO extender module
@param      d5[in] LCD data 1 pin map on IO extender module
@param      d6[in] LCD data 2 pin map on IO extender module
@param      d7[in] LCD data 3 pin map on IO extender module

Briefly, 0x27 is the I2C address of the PCF8574 chip on the backpack.  Note, if your backpack has a PCF8574A, its address is 0x3F.

The other seven numbers describe which PCF8574 output pin is connected for each designated purpose.  Most PCF8574/PCF8574A I2C backpacks are wired the same and numbers 2,1,0,4,5,6,7 are appropriate.

Edit 1: If you write an LCD-with-backpack library of your own and expect to publish it, it is reasonable to comply with the LCD API mentioned earlier.  By using standard interface functions, you will make it possible for users to plug in your library in place of others with the same interface.  In addition, the availability of sketches using the LCD API provides you with a range of test material to verify your drivers.

In writing an LCD-with-backpack library, start by solidifying your understanding of each of the parts – LCD and backpack – separately.

LCD:  Get some HD44780-based LCD units; hook one up using direct wiring or a shield rather than a backpack; install a known-good library and sketch; run tests to verify the wiring.  With the wiring known to work, develop an LCD control library.  This may require detailed study of the Hitachi HD44780U data sheet or other HD44780 data sheets.  The necessary timing for LCD control is picky enough that it would be a fool's errand to not verify the wiring using known-good software before writing your own.

Backpack:  Plug the 16 pins of a backpack into a breadboard, and attach LED cathodes to all the breadboard pins that connect to PCF8574 output pins.  Use appropriate resistors to V+ on the anode sides of the LEDs.  Connect the backpack's SDA, SCL, V+, and ground to that of your Arduino.  Write simple test software using Wire.h calls to send data to the PCF8574, verifying proper operation using the LEDs.  This may require detailed study of the Texas Instruments PCF8574 Remote 8-Bit I/O Expander for I2C Bus data sheet.  Write your PCF8574 control library.  Adapt your LCD control software to send data via the PCF8574 library instead of via direct wiring.


MQTT Library for SIM800 GSM Modem is available at ElementzTechBlog, ElementzGithubRepository
Functionalities:
Auto connect
   Automatically connect to TCP and to MQTT server.

connect function
   This function can be used to connect your client to MQTT broker.
   Use only if you do not use Auto connect functionality.
   Optionally  you can use username, password, WILL topic and WILL Message.

OnConnect CallBack function
   This call back function is called when MQTT connection is established.
   You can call subscription and publish functions inside it (according to your need).

publish function
   This function can be used to publish messages to different topics.
   You can select  QoS levels and RETAIN flag according to your need.

subscribe function
   This function can be used to subscribe messages from different topics.

OnMessage CallBack function
   This callback function is called when messages are received from  subscribed topics
   Topic, TopicLength, Message, MessageLength are the arguments of  OnMessage callback function.
   Inside this, you can write your custom code.

unsubscribe function
   This function can be used to unsubscribe from a previously subscribed topic.

disconnect function
   This function can be used to disconnect your client from MQTT broker.

Keep Alive
   You can specify your KeepAlive duration while initializing.
   Ping requests are sent and received automatically.

Update
Nowadays the easiest solution is to use SIM7600 4G/3G/2G modem. It supports MQTT using AT commands !. For more details the following link can be useful to get started.
https://www.elementzonline.com/blog/using-mqtt-at-commands-with-sim7600-and-arduino-for-gsm-iot-projects


The baud rate shift occurs because of a mismatch between the speed your program thinks the chip is running at and the speed the chip is actually running at.

You may also have noticed that delay(500) is too fast and actually lasts as long as delay(250) would.

By the numbers involved it looks like the board is running twice as fast (115200 / 57600 = 2) as your board definition says it is - maybe you're using an 8MHz definition for a 16MHz board, or a 1MHz definition for a 2MHz board, etc.

Make sure you have the right board definition selected in the IDE for your board.


HC-SR04 quits pinging when distance < 0 || distance < MAXDISTANCE

The HC-SR04's range is 2cm to 300 cm, if you exceed this range or come below this range, which is exactly what you are doing, the utrasonic sensor will not receive any echo and hence there will be no data on the output.
If you bring it too close and since both the transmitter and receiver located close to each other, the receiver will not receive any ultrasonic.
Put a function that checks if the ultrasonic comes down to 2-3. If it becomes true beep a buzzer that tells you that you are too close. Don't let it reach 0.


Use large variables without using much memory

The data structure will take 64 bytes as sizeof bool is 1 byte not a bit. The first option is to pack each line (or column) in a byte (or bytes). The prefix 0b is for binary constant value (in gcc).

uint8_t Char_B[8] = {
0b01111000,
...
0b01111000
};

The second option is to move the data structure to program memory.

const uint8_t Char_B[8] PROGMEM = { ... };

This will require reading each line with a special function.

for (int line = 0; line < sizeof(Char_B); line++) {
  uint8_t pixels = (uint8_t) pgm_read_byte(Char_B + line);
  ...
}


Passing a NeoPixel object reference to a custom library

You call _neoPixel.begin() and _neoPixel.show() in the constructor of your class. This constructor runs before the Arduino is initialized. This is why   begin() functions are used. Add a begin() function to your class and call cycle.begin() in setup().

void YaNeoPixelCycle::begin() {
  _neoPixel.begin();
  _neoPixel.show();
}

Of course remove the _neoPixel.begin() and _neoPixel.show() from the constructor.


How to remove Adafruit Pro Trinket bootloader flashing startup sequence

You could take the Pro Trinket bootloader source code and tweak it to your needs, burn it, and make sure you have patience and debugging skills.

From the author's (Frank Zhao) source code, it seems that this is the 10 seconds loop you are referring to, located in main.c, line #456:

if ( ((usbHasRxed != 0) && (timeout > USBBOOTLOADER_TIMEOUT)

The USBBOOTLOADER_TIMEOUT variable which is defined to 10 at the top of that file, line #70:

#define USBBOOTLOADER_TIMEOUT 10

and is progressed after 'roughly' 1 second, at line #496:

// roughly 1 second
#if (F_CPU == 12000000)
    if (t1ovf > 183) {
    #elif (F_CPU == 16000000)
    if (t1ovf > 244) {
    #endif
        t1ovf = 0;
        timeout++;
    }


Camera switch with ov7670 to output standard A/V signal - composite

An arduino uno is way too slow to output composite video. If you want to generate a PAL video signal you can see here the signal specification.

Most important, one line is output in 52us. If the line is 720px long (720x576 is the common resolution), then you will have to generate one pixel in 72ns. This means that

you will need a very fast DAC (a flash one)
you will need a VERY fast microcontroller. If you have a 160MHz uC you will have to send one output byte every 11 clock cycles, which means that you will barely be able to do any more processing.

Result: it is practically unfeasable. I suggest you, if you want to use it, to look for hardware encoders. But... Probably you will need some faster processing units: maybe a raspberry PI, which already have an hardware encoder...


error: class 'TriangleButton' does not have any field named '_tft'

This should be self-explanatory. When you write in the constructor

_tft(tft)

It means “initialize the property _tft of this object with the
parameter tft.
It is not very clear what you mean by “object composition”. In the usual
sense, it means that object A either is or has an object B. In your
case, it seems like you want your TriangleButton to hold a reference
to an Adafruit_TFTLCD. This is not really composition, as your class
neither is nor has an LCD.
As an immediate solution, just add an appropriate data member to the
class:
Adafruit_TFTLCD &_ftf;

Assuming that holding a reference to the LCD is really what you want for
your class, this should be enough to solve your issue.

Edit: To answer the edited question.
“Redefinition” means you are defining again something that has already
been defined before. In this case, the constructor is defined inline in
the header file:
TriangleButton(Adafruit_TFTLCD &tft,
        int16_t coordX, int16_t coordY,
        int16_t orientation, uint16_t size, uint16_t color)
    : _tft(tft){}

(yes, that's a complete definition with an empty body).
And then you try to define it again in the cpp file. This is an error,
every method should be defined only once. At your choosing, it can be
either inline in the header or in the .cpp, but not both.


Serial.write displaying repeating output from Xbee communication

Code is correct and it does what it is asked to. The receiver code reads the RX pin of arduino which is connected to the Xbee. The same pin is used by the FT232 interface IC to send data to your computer through USB.

The "hello world" you send is received by the Xbee and is send to microcontroller and FT232 at same time as that pin is shared between them. Thus the "hello world" will be seen in serial monitor, first time from Xbee and second time, from Serial.write(Serial.read()) of the program.

Also check whether the settings are correct from this tutorial, as Xbee will not be configured as P2P.


If you search for information about C types on the internet, there will be much help to find, but effectively you are correct. One format of integer types in C take the form:
uint / int: Signed or unsigned integer. Unsigned integers are stored in simple binary representation, and signed integers are stored in two's complement form.
8 / 16 / 32 / 64: The number of bits to store the value. This means the number of possible values is 2x where x is the number of bits.
_t: Simply a suffix to indicate that it is a type name, not a variable.

Colour storage
Colours are generally stored as three components: red, green and blue (or sometimes four, adding alpha, the degree of transparency).
If each component is given an unsigned byte to be stored (so it has a value from 0–255), then the total colour size is 24 bits. However, 24 bit integers are not a standard size, so the next bigger size is selected, 32-bit. This also allows room for an alpha component if necessary, but otherwise the spare 8 bits are unused.
For example:
| 00000000 | 00000000 | 00000000 | 00000000  | = 32 bits
| red      | green    | blue     |alpha/empty|


U8glib Code Help - Simple text display with new line

First, u8glib is no longer maintained. It has moved to u8g2.  There is a u8x8 mode that is much like the u8glib code, in that it is text-only, and uses fonts that fit in an 8x8-pixel box, though there are multiple fonts to choose from.

Second, u8g2 does not have an automatic scrolling mode, so the Console example you mention keeps a buffer (an array of strings, with one element per possible text-row on the display) of the "history". Each time it adds a line to the console, this example copies every line to the one closer to the top of the display, and then copies the new line to the last row (the bottom of the display.)

Go and do likewise. If you show your coding attempt, you will get better answers.


While the led is fading in and out (which takes 5 seconds), the state of the button is never checked. So you'd need to have the button released for at least 5 seconds (so old_val becomes LOW), and then pressed exactly we the led is faded out (again, 5 seconds later). So try keeping the button pressed for at least 5 seconds.

You probably want to rewrite your code, so the button is more 'responsive'. Below I added an example of how to do this.

const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;
int old_val = LOW;

bool fadeLed = false;
int brightness = 0;//current pwm value
int direction = 1;// 1 is brightness is increasing, -1 if brightness is decreasing

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop()
{

  /* check the button */
  val = digitalRead(BUTTON);
  if ((val == HIGH) && (old_val==LOW))
  {
    // button pressed ( called only once per press )
    fadeLed = !fadeLed;// invert boolean
  }
  old_val = val;

  /* update the leds brightness */
  if( fadeLed )
  {
    // fade led in and out
    if( brightness==0 )
      direction = 1;//change direction is minimum value reached
    if( brightness==255 )
      direction = -1;//change direction is maximum value reached
    brightness += direction;// increase/decrease brightness
  }
  else
  {
    // fadeLed is disabled, so only decrease brightness till it reaches zero
    if( brightness>0 )
      brightness--;
  }

  analogWrite(LED, brightness); // set the LED brightness
  delay(10);           // Wait 10ms because analogWrite
                       // is instantaneous and we would
                       // not see any change

}

Any questions about the code; just let me know.


This seems to be a general problem of the Arduino IDE: It only recognizes libraries that are included in the (primary) .ino file.
If you look at the invocation of the compiler, the path to any given library is only added if this library's header file is included in the .ino file.
I tested this with the EEPROM library. If this library is included in the .ino file, the compiler is called with
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs -I/usr/share/arduino/libraries/EEPROM /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where the important part is the -I/usr/share/arduino/libraries/EEPROM.
If I now remove #include <EEPROM.h> (but still have it in another header file which in turn is included in the .ino as in your case), the compiler call changes to
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where now the include path to the library is missing.
TL;DR
If you need to use a library, just (also) add an include to the .ino file. It doesn't cost you anything and will solve your problem ;)

#include <file> vs. #include "file"
From the gcc documentation:

#include <file> is used for system header files. It searches for a file named file in a standard list of system directories. [...]
#include "file" is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. [...]


OK.  I figured out it needs to run as administrator.

Thanks for your consideration though.


The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.

Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you think you have built.


Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?

You don't need the motor shield at all. The motor you link to has its own driver built in.

According to the connection table on the page you link to:

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

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


How to improve date-time control from RTC?

Is there a simple way to convert to date-time object?

Not with this library. But you can find other
libraries supporting the DS3232 which work with the Arduino
Time library[]. This time library provides both the date and time in a
single object, either:

a time_t, which is just the number of seconds elapsed since a
standard “epoch”
a tmElements_t struct, which has the date and time broken into
separate elements (year, month, day, hour...).

  Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more
accurate ones are also the more complex.

  #include <SoftI2C.h>

Doesn't your Arduino have a hardware I2C port? That would be more
efficient than software emulation.

  Serial.flush(); //needed before sleepy

It's only needed if you are actually using the serial port.

Edit: I saw on your other question that you have been bitten by
an incompatibility between the Arduino Time library and the file
time.h from avr-libc. Now I just noticed that avr-libc includes the
functions sun_rise() and sun_set() that you may find
handy. Not sure they will play well with the Arduino time libraries
though. One possible incompatibility is the fact that they use different
epochs for defining time_t (year 1970 v.s. 2000).


trying to switch input on my speakers via infrared using web browser but i have issue getting it working


Atmega328 component library for Protel 99 SE

All arduino design schematics are available from the Arduino website, e.g. for the Uno. However, these are in EAGLE format, I don't know if it's possible to convert.


Sending wav file on ESP32 to flask server

You need to do socket programming here for sending chunks of data to a socket server(Python end). Here is the link that can help you. Try establishing a connection between esp and python using socket programming and then you can send small chunks of audio.


I think you need a delay(1); after your call to write().

There is/was a bug where the underlying buffer files up and can't get time to clear.  It looks like it will require a change to the ESP8266 firmware from the manufacturers before it will get fixed properly.

See what you think:

https://github.com/esp8266/Arduino/issues/1696

https://github.com/esp8266/Arduino/issues/2285


Trouble while using Arduino DUE as programmer

There error you have is from avrdude failing to get a communication link established to the 'programmer' (which manipulates the target.)

Here is a link that may help with the connection

Stk500 error

Here is another relative link that may help

Arduino ISP on DUE

Best of luck.


class subject {
public:
  char subjectname[];
  char classroom[];

};

This creates a class subject which has two char arrays of unspecified size as its members. This will attempt to create an array of size 0 (see here). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then strncpy() your new string inside the buffer.

This would look like

class subject {
public:
  char subjectname[32];  //32 bytes buffer
  char classroom[32];
};

And later

subject math;
strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
Serial.print("Classroom is: ");
Serial.println(math.classroom)

Or, just use the Arduino String class.  For example

#include <Arduino.h>
class subject {
public:
  String subjectname;
  String classroom;
};

Then your first usage code can be used unmodified.

Example

#include <Arduino.h>

class subject {
public:
  String subjectname;
  String classroom;
};

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

    subject math;
    math.classroom = "A1";

    Serial.print("Classroom is: ");
    Serial.println(math.classroom);
}

void loop() { }


Updating Server using ESp8266 with Direction Button Pressed IN

I changed the code so that the button function runs with "/" and took out the server.on("/", handleRoot) line, thanks to @Juraj. Sigh


How do I program a non-Atmel chip with the Arduino IDE?

The question is actually very broad as there are many possible embedded processor to choose from.  Any answer would have to be presented using general terms.

As stated by @Majenko, your 1st step is to use a popular programming language that has been ported to many embedded processors (or the processor of interest).

The next step is not so clear.  When programming in the Arduino paradigm you have been using supporting C++ source code (which "Sketch" writers are calling "Libraries") that normally interact directly with the Arduino's hardware.

It is important to say this is an Arduino paradigm which has already been ported to a number of different processor.  Perhaps it is worth your time to discover which processors this paradigm has already extended to.

In the world outside of the Arduino paradigm, many embedded processor manufactures support sales of their hardware by supplying developers with tools.  Normally this includes a compiler and some software to abstract the hardware making it easier to use the more generic features.  If the processor comes on an "evaluation board" and the supporting software takes advantage of this the supporting software can be referred to a Board Support Package or BSP.

However, most will find the difference between Arduino Libraries and BSPs as vast.  Why?  Because most will write Arduino Libraries to mimic highly abstracted programming language features but in a very specific / inflexible way.  For example, a Sketch writer only has about a dozen ways to print something out.  Where as in real C, the print statement is very complex and flexible. Outside the Arduino paradigm (where the vast majority of embedded processors are used), the BSP approach is preferred as it exposes all the benefits the processor's hardware has to offer.

Where does this leave you?

The easiest approach is to find an Arduino platform which meets your needs.  Where someone has already done the work of porting all, most or some of the Arduino Libraries.

The next easiest approach would be to learn C++ and port the Arduino Library (which are really C++ classes) you are using in your program for the platform you are targeting.  Note that, in this case, it is suggested that creating an ordinary C / C++ program (abandoning the Arduino Sketch / Library paradigm) and using the supplied BSP (or other supporting software) would be easier than porting the entire Arduino Paradigm to the new platform.

The hardest approach (but the community would likely appreciate your efforts) is to port the entire Arduino paradigm to the new platform.


Nesting loops - if statement in a while loop

I guess you want the while loop to exit, when the switch goes to HIGH. (You didn't explain this in your question)

Currently the variable switchS cannot ever change while the code is in the while loop. The variable var only changes, when switchS is HIGH. So, if switchS is LOW at the start of the while loop, you have an infinite loop.

Instead, you can actually read the switch state inside the while loop, not outside of it. The variable switchS will not automatically track the state of the switch. You have to explicitly read it. Like this variant of your code:

int switchS = 0;
int var = 1;

void setup() {
    pinMode(1,INPUT);
    pinMode(7,OUTPUT);
    digitalWrite(7,LOW);
}

void loop() {
    while(var == 1)
    {
        digitalWrite(7,HIGH);
        delay(100);
        digitalWrite(7,LOW);
        delay(100);
        switchS = digitalRead(1);  // I moved this line in the while loop, to read the switch on every loop iteration
        if(switchS == HIGH)
        {
            var = 0;
        }
    }
    delay(5000);
    var = 1;
}

Note: You are using pin 1 as input pin. On the Uno this is a Serial (UART) pin, which is used to communicate with the PC. If you have enough pins, that are free, you should not use pins 0 and 1, so that you don't block the serial communication, unless you really need it and know, what you are doing.


Implementing hysteresis turns out to be quite straight-forward:

float pressure = read_pressure();
if (pressure < x)
    turn_relay_on();
else if (pressure >= y)
    turn_relay_off();


Arduino YUN server crashes after few hours!

Updating your YUN might solve this problem. It is recommended to update it after you buy it because they usually come with old firmware. Make sure its up to date.
Here a link on how to do this

Another thing to try is to add delay(50); at the end of the loop() function. It prevents the processor from doing lots of work.


Can you make it so, when your phone connects to the Hc-05 on a Arduino, a variable changes?

Detecting successful connection with HC-05

The HC-05 can be configured to do what you are after.

Search for "POLAR" in the AT set documentation.

AT+POLAR=0,1

should be what you need as per their examples.
Hook up PI09 to your arduino and wait for it to go HIGH.
You may even want to wake up your arduino with an hardware interrupt using that signal.

Depending on your package, this may require soldering to the HC-05 module.
The datasheet features a pinout in that case. Be sure to checkout the manual of your breakout board first.


Understanding Nikon modified version of SPI

It is simply a way of splitting a single-pin read/write function between two pins. It's easier to visualise with schematics:

simulate this circuit – Schematic created using CircuitLab

Under idle conditions the resistor pulls the data signal high. When the lens wants to transmit the open-collector output (represented by a transistor here) either pulls the data line low (for a 0) or releases it to be pulled up by the resistor (for a 1).

The Arduino reads that data in through the data in pin.

When the Arduino wants to transmit it does the same thing, but the "open collector" is external in the form of the transistor. It drives the transistor using the data output pin to get it to pull the data line low for a 0, or release it to be pulled up by the resistor for a 1.

This is exactly the same way (on an electrical level) that I2C works and studying that protocol can help you to understand what is going on here.


You can unit test your code by creating stubs of the functions you are calling, like replacing a couple of includes with their dumb counterparts.
My friend Jan Beayens did something very valuable on that front and he is also the main author of a good replacement for the Arduino IDE when you start needing some more advanced capabilities: Sloeber is the product name and it also contains an improved version of the serial monitor with clear and scroll lock capabilities.

Go check it out.

Disclaimer : I'm a contributor of the project


Arduino continually resets when connected to external power supply, but not USB

Most likely lack of current - lack of current able to be provided by the Mini. The audio is powered from the onboard regulator on the Mini, which has limited current capacity.

If too much current is drawn it will either get too hot and go into thermal shutdown until it cools down enough, or it will drop the output voltage, making things reset and crash.

Power the audio system from an external 5V regulator.


Bridge and Serial both use the same pins. You cannot use them both.

Bridge runs at a much higher baud rate (230400 IIRC) than Serial, which is why it all messes up.


One possibility that has not been mentioned yet: the issue may be
the calibration of your ADC converter. Your code carries the implicit
assumption that the voltage you measure is

V = Vref × RawADC ÷ 1023

The correct formula is

V = Vref × (RawADC + offset) ÷ scale

where offset is ideally 0 and scale is ideally 1024 (and not 1023,
as you are assuming). Since you are looking at relatively small
discrepancies, the “ideal ADC” assumption may not be a good enough. I
have calibrated 3 Arduino ADCs and found offsets between 2.2 and
2.4, and scale factors between 1026.1 and 1026.3. Thus, if you have an
accuracy issue, I recommend you calibrate your own ADC.

As a side note, you could expect slightly better accuracy if the
thermistor and the resistor are closer in resistance. Right now you have
a factor 3, which is not that bad, but you could use a 2.2 kΩ
resistor, which is a very standard value.


if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }

You cannot have another comparison in an else statement. You might have meant else if in the last clause.

Clarification if you're not well familiar with C/C++: If you have an if statement, it can be followed by arbitrary many else if clauses and at maximum one else clause which will execute when all other conditions fail. For example:

 int a = 10;
 if( a == 9 ) {
       //Executed if a = 9
 } else if( a < 20 ) {
   //If above not executed, this will be executed if a < 20
 } else {
   //This is executed if none of the conditions above hold.
   //A pure "else" does not have a condition and only one may
   //exist in an `if` statement.
 }


The getKey() Funktion returns the define NO_KEY if no key was pressed, which is set in Keys.h as the NULL char (char with the value 0). In every loop cycle you are adding one character with value 0 to your string. But all functions, that handle strings, will stop, when they find a character with value 0 (it is the delimiter of C strings). Also a string with many NULL chars in it will not be matched to a string only consisting oft digits.

So you should check the return value of getKey for the NO_KEY define:

if(keyPressed != NO_KEY){
  enteredCode += String(keyPressed);
}

This avoids adding NULL chars to your string.


How to subtract the current analog value from previous one

I think you need something like the following :

int lastTime;

void loop(){
  int thisTime = analogRead(A1);
  int diff = thisTime - lastTime;
  lastTime = thisTime;
  Serial.println(diff);
}


Not Pascal, but Ada, which is much less restrictive than Pascal while enjoying the same advantages over low-level programming, and much more actively supported with language revisions as recently as 2012 and the formally provable SPARK language, for when you need your code to work.

Any processor which gcc supports can potentially support Ada, whose Gnat compiler is fully part of gcc.

That's not the whole story because you also need run-time system support for Ada's facilities, but for the Arduino's AVR processor there is a well established environment in the form of the AVR-Ada project.

It generates nice tight little executables, you'll be amazed how much less space simple Gnat executables take compared to Arduino ones - unless you've already made the same comparison between Arduino and C ... which after all uses the same gcc compiler.

For ARM-based Arduinos (Arduino Due at least) the same is possible, though the support is newer and possibly less well established, see the Cortex-GNAT project.

Leaving the Arduino, Ada has also been demonstrated on the MSP430 processor - my own project, sadly neglected at the moment.


Why does my Arduino IDE hang/crash so often?

Just report it to Arduino.

You don't really have any other option. I've been waiting to answer this question until I was sure that no one here knew the answer. You don't really have any other option.

This seems like a bug. We're not Arduino developers or a bug tracking site. We can only do so much here. Even if it was confirmed a bug and we fixed it, there's only so much that can be done without submitting a report.

BEFORE YOU SUBMIT A REPORT:

I'd try copying out the libraries from Arduino. So many libraries
might make Arduino IDE somewhat heavier. I don't know if it'll really
affect the sluggishness but it's worth a shot.
The only other thing that I can think of, besides RAM (which you
already said wasn't an issue) and the libraries, is some sort of
cache/temporary file. Try reinstalling Arduino, even if you haven't,
and also I'd try using the beta 1.5.6-r2
version. It has to be pretty
stable for it to be the only version that supports the YUN and DUE.
Both have been out for a considerable amount of time with this
software, so I'd imagine that it's pretty stable minus a few issues.

  Many things are said to have been improved compared to the previous 1.0.5-r2 version.

It'd be stupid not to try the newer version.


Is there a better way to combine if statement with an ISR?

Your code is not blocked, but ON or OFF are called each loop so your change are to the "common" components are overwritten quite fast.

Do not track the state within the IRQ. You could do something like:

volatile byte alarm = 1;
byte alarm_state = 1;

void ISR_Alarm () {
    alarm = 1;
}

void loop() {
    if (alarm){
        alarm = 0;

        if (alarm_state) {
            alarm_state = 0;
            alarm_Off();
        } else {
            alarm_state = 1;
            alarm_On();
        }
    }

    // other code
}