Restart sequence of NeoPixel stick with a push button at any time I am really happy with my new Arduino stuff and playing around with all those pixels :).

I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.

My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.

I know that delay(); will stop the code completely and wait till the time passes, but I wrote some code without the use of delay(); and used millis(); instead.

So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the while(); part in my code works kinda like a delay(); and that would prevent it from restarting until a full cycle. I used some millis(); code from a different sample so it's not like the ones from Blink Without Delay.

I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.

#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}

Thanks in advance for you help.

Firstly, good for you trying to avoid delay().

However your while loop pretty much does exactly what delay() does anyway.

Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".

Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light just one more LED.  Once you have lit all 16 you can then restart your sequence.

And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.

For example loop() might look something like this (untested):

void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}

The key there is that the variable lednum contains the number of LEDs that you want to display. Once per second, controlled by millis(), the LEDs are updated to display that number of LEDs.


Vibration pattern matching I would like to generate vibration patterns using the SW-420 or something similar that is able to reproduce the same pattern on similar vibrations. So if a 10p coin was dropped on a table from 1m at a 90 degree angle then I would expect the second time it dropped to make the same vibration pattern.

The objective is for the software on the Arduino to keep a small database of recorded vibration patterns and alert the user when a similar pattern has been detected.

What you want might be way more complex, than you think, depending on your exact requirements.

The vibration sensor activates with any small vibration. It is not capable of distinguish different sources of the vibrations. The only pattern, that you might be able to look for with it, is a special pattern of multiple activations, as the coin jumps over the surface (depending on the max activation frequency of the sensor). Obviously this error prone.

Using a microphone to record the direct sound can give you more information about what happens. But that can get very complex very fast:

You need to measure the voltage from the microphone (which needs a suitable amplifier) with a sufficient samplerate (at least 2 times as fast as the highest frequency, that you want to measure). A high quality microphone might also need a better ADC (Analog Digital Converter), than the Arduino has build in.
The pattern recognition is another problem. Basically you have 2 ways:

You can look at the target sound signal and look for a few special properties of that signal, for which you can test the signal (for example a specific pattern of peaks above a threshold. Then you can test with some if statements for these properties, which is relatively easy. Though this is still very error prone.
You can train an AI to recognize the coin sound pattern. Though this is not a job for an Arduino, especially not for the Uno. You should use a special AI board for that. Though this is off topic here.

Which way you want to use depends on your exact requirements. When the recognition with the vibration sensor is sufficient, just use it. But we cannot say, if that is the case, because we don't know the actual pattern, that you want to recognize, nor do we know your exact requirements. You will need to test that yourself.


Send numbers to arduino via serial port using python I have a file with numbers called fginputs.txt. For example it could be something like this:
4958
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4958

I want python to send each number to arduino via serial port. After each number is received, arduino should print back an acknowledgment number, indicating that it got a valid number, and then store that number in a dynamic array, because I could create larger files. When there are no more numbers left, send a '-1' to finish transmission.
Here's my arduino code:
// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);
 //counter for how many numbers I've received starts at 0
 cont = 0;
 //This is true when there are no more numbers to receive, meanwhile false
 inputsReady = false;
 setupInputList();
 }

/* If there's not enough space, resize the array by one unit and store the number
   */
void growAndInsert(int currentSize, int newInt){
    if(currentSize > SIZE)
        inputList = (uint16_t *)realloc(inputList, (currentSize + 1)*sizeof(uint16_t));
    inputList[currentSize] = newInt;
}
/**
  init inputList with 100 blocks
 */
void setupInputList(){
  SIZE = 10;
  inputList = (uint16_t *)malloc(sizeof(uint16_t) * SIZE);
}

void clearBuffer(){
while(Serial.available() > 0)
    Serial.read();
}

/**
Listens in serial port for an integer that represents a new input and returns it.
If it doesn't get anything useful from serial, return 0
*/
  int getNewInputFromSerial(){
   if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

    if(cmd == 4958)
        Serial.write("4");
    else if(cmd == 4154)
        Serial.write("5");
    else
        Serial.write("0");
    return cmd;
   }
  return 0;

}

void loop()
{
     if(!inputsReady){
        int newInput = getNewInputFromSerial();
        if(newInput == 0)
            return;
        if(newInput != -1)
            growAndInsert(cont++, newInput);
        else{
            inputsReady = true;
            //initTimer();
        }
    }

}

and the python script:
global arduino
PORT = '/dev/ttyACM0'
FILENAME = "fginputs.txt"
#Read file with inputs
with open(FILENAME) as f:
        content = f.readlines()
#init serial port
arduino = serial.Serial(PORT, 9600, timeout=1);
time.sleep(2);

#write
for input in content:
    arduino.flush()
    arduino.write(input)
    time.sleep(.1);
    resp = arduino.read();
    print "i got " + resp

#Finish transmission with -1
arduino.flush()
arduino.write("-1")
#done
arduino.close();

The fist time I execute the script I get this:
i got 4
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 4

Which is great. But if I run it a second time I get this:
i got 0
i got 4
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0

Which is terribly wrong because the file hasn't changed. I don't know what is going on here. If I unplug and plug back in the USB cable, transmission works flawlessly again.

// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);

You are freeing a NULL pointer which is an undefined operation not necessary here, since it was never allocated.

  if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

This is going to just throw data away, I'm not surprised stuff goes missing.

Read this: How to process incoming serial data without blocking - you need to get rid of the delay, and the clearBuffer() for a start.

Example code for reading from Serial without blocking and without using delay:

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

In process_data in my example is where you would call atoi to convert the incoming string into an int (or atol if it is going to be longer).


Combined code and nothing works. Head scratcher for sure I have spent a little over 2 hours trying to debug this code. All I did was combine a section of code to write to the SD card. Both of the codes work fine on their own. I can't figure this one out. I am hoping fresh eyes can spot the error. I am using a Arduino Nano with a Robot-Deek data logger board. Pin 10 is used for the data logger. I was using a DTH11 but switched to a LM35, both codes worked with LM35.

#include "RTClib.h"
#include <SD.h>
#include <SPI.h>
#define sample 500
#define current_ms millis()
RTC_DS1307 rtc;
File myFile;
int inPin = 0;   //analog in
float val;       //where to store info from inPin reading
int pinRed = A3;  //output of red led
float tempin = A5;  //input of temp sensor
float tempf;     // variable to hold temp in Fahrenheit
float vout;      // variable to hold voltage from sensor
int array1[sample];  //creates an array with number of elements equal to "sample"
unsigned long averaging;  //the program uses this variable to store the sum of each array it makes
int pinCS = 10;   // write to SD card
float last_dht11_reading_ms = 1;
DateTime now = rtc.now();
#define DHT11_SAMPLE_DELAY 500

void setup() {

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  SD.begin();
  pinMode(pinCS, OUTPUT);
  pinMode(tempin, INPUT);
  Serial.println("Volt and Temperature\n\n");
Serial.println("middle the setup loop");
 // SD Card Initialization
  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
    File myFile = SD.open("Datalog.csv",FILE_WRITE);
    if (myFile) {
      myFile.println("Time, Temp, Volt");
      myFile.close();
    }
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}//end "setup()"

void loop() {

  for (int i = 0; i < sample; i++) {         //this code tells the program to fill each element in the array we made with
    array1[i] = analogRead(inPin);           //information from the antenna wire coming out of the Arduino
    averaging += array1[i];                  //more information about for loops http://arduino.cc/en/Reference/For
  }                                          //the averaging line is simply saying: add averaging to whatever is in array position i
                                             //averaging += array[i] is the same as averaging = averaging + array[i]

  val = averaging / sample;                  //here the program takes the sum of all numbers in array1, and divides by the number of elements "sample"
  val = constrain(val, 0, 100);              //this constrains the variable value to between two numbers 0 and 100
  val = map(val, 0, 100, 0, 255);           //for more information about constrain http://arduino.cc/en/Reference/Constrain
  analogWrite(pinRed, val*20);                  //the map statement tells the program to map out 0-100 to 0-255
  averaging = 0;                                 //this line of code sets averaging back to zero so it can be used again
Serial.println("past the emf loop");

  if ( (current_ms - last_dht11_reading_ms) > DHT11_SAMPLE_DELAY ) {
    vout = analogRead(tempin);                //read LM35 output
    float mv = (vout/1024)*5000;              // conversion to mV
    float celc = mv/10;                       // convert to C
    float tempf = ((celc*9)/5 + 32)/10;       // convert to F
    myFile = SD.open("Datalog.csv", FILE_WRITE);      //open datalog file on SD card

  if (myFile) {                              //write to the SD card time, tempf and val
    myFile.print(now.hour());
    myFile.print(":");
    myFile.print(now.minute());
    myFile.print(":");
    myFile.print(now.second());
    myFile.print(",");
    myFile.print(tempf);
    myFile.print(",");
    myFile.println(val);
    myFile.close(); // close the file;    // close the file
    last_dht11_reading_ms = current_ms;
  }
Serial.println("past the logger loop");
  //delay(1000);//Wait 1 seconds before accessing sensor again.

}
}
// end loop()

DateTime now = rtc.now();
Does not belong above void setup()
4hours to troubleshoot this little mistake.


Creating a library for attiny85 out of working program Apologies if this is the wrong sub-forum, the involvement of ATTiny and arduino places this into a strange category. Please correct me if I should post elsewhere.

It is important for this to be a library as small kids will be using this program and hardware for their own projects. Its kind of a rip on the LOLshield but it involves a lot more steps to integrate more lessons all at once.

My whole program takes 8 bytes of information and converts it to data for a shift register driving two multiplexers all driving an 8x8 LED matrix. It can also use multiple of these packets to make a slide show. I have it in a working state right now and would like to turn it into a library for easy use. I am a bit lost in this step as I had to create an interrupt timer and this makes it more complicated than the tutorial on the arduino website covers.

Also if someone could point me to a library for ATTiny85 that makes calling a timer interrupt easy then the rest of this project will likewise become easier.

Any help would be great! I will be continuing to look on online resources and will update should I figure it out.

I had to create an interrupt timer ...

Be warned that there are things you should not do in interrupts, like delays, serial printing, etc.

Code

In the interests of answering the question though, this works:

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

ISR (TIMER1_COMPA_vect)
  {
  digitalWrite (4, ! digitalRead (4));  //toggle D4 (pin 3 on chip)
  }

void setup()
 {
  pinMode (4, OUTPUT);  // chip pin 3

  // Timer 1
  TCCR1 = bit (CTC1);   // Clear Timer/Counter on Compare Match
  TCCR1 |= bit (CS10) | bit (CS13);  // prescaler of 256
  OCR1C = 123;          // what to count to (zero-relative)
  TIMSK = bit (OCIE1A); // interrupt on compare

  }  // end of setup

void loop()
  {
  // other code here
  }

You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.

Prescaler values

From the datasheet:

In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.

The delay is then:

125 ns * 256 * 124 = 3.968 ms

Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.

Flashing more slowly

If you put an LED on pin 3 and want to see the flashing, you need it much slower. For example:

TCCR1 |= bit (CS10) | bit (CS11) | bit (CS12) | bit (CS13);  // prescaler: 16384

That toggles the pin every 254 ms, which is visible.

Warning

On this chip Timer 1 is an 8-bit timer, so you cannot put more than 255 into OCR1C.

More information

Timers
Interrupts


Problem uploading to board avrdude: stk500_getsyn(): not in sync_resp=0*00
avrdude: stk500_disable: protocol error, expect=0*14,resp=0*51

These are the errors occurring when I am trying to upload to the board.
I've tried all the suggestions that suggested in this. When I am trying to burn the bootloader the same error is showing.

I don't know if I got the exact error (maybe another sync error), but what helped in my case (in this order, try again every time):

Reinsert the USB cable
Use a different (shorter) USB cable
Put the USB cable in another USB port
Restart the Arduino IDE
Restart the computer
Reinstall the Arduino IDE
Go to device drivers (control panel), check for COM ports, remove Arduino and reinstall


Use of Resistor in PinWheel Exercise I'm working on project 9 of the Arduino starter kit - the motorized pinwheel.

Here is the schematic:

(if img not showing: https://goo.gl/tqZmKD)

My question is, why is the 10k resistor needed after the switch? Why can't it just go straight to ground? The switch's output just connects to a digital pin, it doesn't care how much voltage there is, correct?

Thank you!

EDIT**: Additional help from the arduino forums:
The resistor is needed so when the switch is closed you don't short the supply
to ground.  Switch open the resistor pulls the signal to ground and no current
flows, when the switch is closed it forms a resistive divider with the 10k
(switch contacts might have 0.01 to 0.1 ohms resistance or so), thus pulling
the signal to Vcc, but with only 0.5mA flowing through the 10k resistor.

Replace the 10k with a wire and you'd simply overload the supply completely and
perhaps weld the switch contacts shut.
Arduino Forums

It's a pull-down resistor.

A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).

With the switch open and no resistor present, the Arduino pin is neither high nor low. It will probably read as low if you tried digitalRead(), but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.

However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) until you press the switch, at which point the Arduino pin switches state.

If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?

Think about it...

One side of the switch connected to Vdd.

The other side is connected to the Arduino and GND.

Close the switch, I dare you.

Vdd is now connected to GND


Caluclate lux value from LDR I am using an LDR (Iduino SE012) to measure light. It returns a 10-bit value of the incoming voltage and I don't know how to convert this into lux, lumen candela or any other light-intensity unit. I was googling for datasheets but nothing useful came up. So is there any way how I can extrapolate a light intensity from the voltage?

I mean one idea that I would have is to measure some things where I know the lux output, but since I don't have such things or a luxmeter I'm pretty stuck. It also returns 1024 pretty quick if you hold it into the sun (Altough the sun is very strong today and it has 36°C). Is there maybe a "minimal value" at wich it returns the full voltage? From that point I could calculate it for all the other values.

Here are some datasheets I found:

https://www.manualshelf.com/manual/iduino/se012/datasheet-english.html
https://wakamatsu.co.jp/waka/SE012.pdf

You can't.

The LDR has a spectral sensitivity which is very different from the
human eye's. The definition of the lux, or any photometric unit for
that matter, pretty much requires that your sensor is filtered in such
a way as to have the human eye's spectral sensitivity.


arduino --verify / --upload not working (command line) I installed Arduino IDE version 2.1 on Ubuntu via apt-get. Then I typed the following command in terminal to see if the Arduino IDE compiles my sketch.

 arduino --verify xx.ino

However, this command launches the GUI IDE. Is the CLI not supported anymore, or is the cause in apt-get the package?

It's quite possible that this "version 2.1" doesn't support command line processes. I've never heard of an Arduino IDE version 2.1. My understanding is the version you get from apt-get install arduino is something like 2:1.0.5+dfsg2 so maybe you interpreted that as 2.1. That version is based on Arduino IDE 1.0.5, though apparently it has some non-standard modifications. Command line operation was first added in Arduino IDE 1.5.2, though some additional functionalities were added in newer versions.

You should always install the official Arduino IDE downloaded from:
https://www.arduino.cc/en/Main/Software


Code Optimization: Interrupt when a value reaches 0 I have this working program that I wish to improve efficiency as much as possible.
It will blink slow, then faster and faster until it restarts.
It works, but my main concern is, currently, I am using a if statement in the void loop(), and I am certain that, using an interrupt when a specific variable has reached 0, would improve efficiency.
byte amp = 0;
void setup() {pinMode(13, OUTPUT);
              reset();
}
void loop() {            //The following
  digitalWrite(13,HIGH); //code is for the sake of example
  delay(amp*100);        //Simplified to focus on the loop
  digitalWrite(13,LOW);
  delay(amp*100);
  amp--;
  if(!amp){reset();}     //<-This right here
}
void reset() {amp = 10;}

My understanding is, the if statement is called every time the loop restarts.

Is it possible to set up an Interrupt for when a certain variable reaches 0?
Which option would require less computing power, a continually called if loop, or an interrupt?

Thanks!

You did not specify the kind of Arduino you are using but, based on
another recent question of yours, I will assume it is an AVR-based
Arduino.
You cannot have an interrupt automatically triggered by a variable
reaching zero. What you can do, instead, is trigger an interrupt by
software, by toggling a pin that is configured both as an output and as
an interrupt source:
const uint8_t int_pin = 2;  // pin used for interrupt

void setup() {
    digitalWrite(int_pin, LOW);
    pinMode(int_pin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(int_pin, reset, RISING));
}

static inline void trigger_interrupt() {
    digitalWrite(int_pin, HIGH);
    digitalWrite(int_pin, LOW);
}

// Within loop():
if (!amp) trigger_interrupt();

However, if you do that, you will discover that interrupts are slow.
Awfully slow compared with a simple if test:

digitalWrite() itself is awfully slow. This can be overcome by
using direct port access, but that is still two cycles for toggling
the pin in each direction.

You will loose an extra cycle in the pin synchronizer.

Once the IRQ is raised, the CPU needs four cycles to prepare itself
for servicing it.

The interrupt vector is a jmp instruction, which takes 3 cycles.

The ISR then has to save every single register it is going to use,
including the status register. That takes two cycles per register.
And there are quite a lot of registers to save...

This ISR, which is provided by the Arduino core, will then look for
the interrupt handler you provided with attachInterrupt(). This
also involves checking that the pointer to the handler is not zero
(the kind of test you seem to be worried about). It then has to
call (4 cycles) your handler, which will have to return
(4 cycles) to the ISR. You could avoid this indirection by defining
the ISR yourself instead of relying on attachInterrupt().

Once the job is done, all the saved registers have to be restored
(2 cycles times many register), and the reti instruction (4 cycles)
is issued in order to restore control to the interrupted program.

Last but not least, since amp will be modified in interrupt
context, you will have to qualify it as volatile. This keyword
prevents the compiler to perform optimizations that are unsafe in
this situation, and you will loose a lot of time to these missed
optimization opportunities.

In contrast, this line:
if (--amp == 0) amp = 10;

would be translated by the compiler into something like this:
   dec  amp     ; --amp, as amp is likely already in a register
   brne 1f      ; if (amp != 0) skip the following
   ldi  amp, 10 ; amp = 10
1:

The whole sequence takes 3 cycles, irrespective of whether the if
condition was true or false. That is at least one order of magnitude
faster than the interrupt-based solution.


How can I implement double buffering with an Arduino UNO? I am creating a tiny game on my Arduino UNO with an Adafruit ST7735 1.8" TFT / SD breakout. I am performing screen operations using the built-in TFT-library.

The problem is screen flickering. Even though I take care to prepare data and minimize the time between clearing the screen and writing the new stuff to it, the screen "refresh()" is significant. I heard someone mention something called double buffering, so I read a bit up on it, but I am frankly clueless on how to implement it on an Arduino UNO.

Is it possible to implement double buffering on an Arduino UNO to prevent screen flickering, and if so, how?

Libraries used:

#include <TFT.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

The screen is "cleared" like this:

screen.background(0,0,0);  // Clear it
screen.text(buf, 10, 25);  // Write new stuff

If you're already preparing the next screen's-worth of data before you clear the screen, then double buffering won't help. In that case, the time taken to re-write the screen data is what causes the flicker, and the only way to improve it is to write the screen faster. If the software is to blame, it will be in screen.text(). If the software is already driving the hardware as fast as the hardware will go, then that's the best you can do.

Double-buffering would let you prepare the next screen while the currently-prepared one is loading (and will require interrupt-driven I/O to do it). The result would be more screen refreshes per unit time, but it doesn't sound like that is your problem.

One easy experiment to try is to not clear the screen before you re-write it, if that is possible to do. Then your next screen will overlay the current screen with (we hope...) no blanking period. That might prevent the blinking.


Voltage Regulator getting too hot I have an Arduino mega that is being used to control relays and ultrasonic sensors.  The relays that I am using is a 4 DPDT Signal Relay Module Model: D-256 Series and the other is a 4 channel Single pole Relay for Arduino. I am only using 3 channels of each relay. At any given time I only output to 2 channels from each relay at a time. I tested the relay to ensure they worked with the Arduino and they ran fine.

Once I connected the Ultrasonic sensors to the board as well, the board would not power and the voltage regulator got extremely hot. I would assume the total current draw was too high from the outputs and VCC of the Arduino.

I think that if I take my 9V battery and run it through a voltage regulator 7805 then I can run the VCC power of the relays with the battery instead of the VCC from the Arduino. This would result in me only running a VCC to the 4 ultrasonic sensors, the triggers for the ultrasonics from the Arduino, and the output signals fora maximum of 2 channels per relay board resulting in 4 relays. Most of the time it is only 2 relays.

Would I be able to power the relay boards VCC with the 9V running through a 5v regulator instead of the arduino so that I can reduce the current running through the Arduino?

It sounds like a power-to-ground short circuit, either a fault in the Ultrasonic sensor or in the connection to the Arduino.

Check your connections, and if you have an Ohm-meter, check the resistance between the sensor's power and ground pins.

Current consumption is a function of the device being powered, not of the power-supply, unless the supply lacks the capacity to provide as much current as the device needs.

Note that 9v batteries (the small brick aka a "transistor battery") is not well suited to supplying much current and probably will not power your Mega, or not for long, anyway. They are much better suited for long-term powering of very low current devices, such as a smoke detector.


Several ESP8266 in wifi network should share information I am currently working on a project for my home where several ESP8266 (each with a relay) control lights. I have developed an android for this where I find the ESP8266s via mdns but the problem is that sometimes one or two won't be found ever (depends on the position where I am trying it). So my idea was to make them talk to each other so everyone knows like an list of ip addresses from the others. This would give me the possibility to find every ESP as soon as i have found one.

I guess you are asking if it is feasible: if this is the case, I would say yes, without too many troubles. Each ESP can launch MDNS discovery, so they can discover each other.


avrdude: verification error, first mismatch at byte 0x0000 : 0x00 != 0x16 using USBasp I'm having this strange error, which pops up around 90% of the time. I am trying to program my attiny25 using USBasp and the Arduino IDE / library. Sometimes it works, most times it doesn't.. This error occurs on large sketches as well as new sketches, with just the empty setup() and loop() functions. The error looks quite random to me, because my program just uploaded after trying around 10 times. Compiling goes fine. The error always occurs at byte 0x0000, and always in the format 0x00 != 0x _ _. I have six wires (correctly) connected from the USBasp to the attiny25. I do not use any resistors, capacitors etc.

Could anyone tell me what could possibly cause this error, and what to do to fix it?

The cause is most likely the fact that you "... do not use any resistors, capacitors etc."

Connect a 100nF capacitor between Vcc and GND.  Connect a 10KΩ resistor between RESET and Vcc.


24LC1025 Arduino - Data Writing Problem I have a very big problem by writing a list of strings to an eeprom (24LC1025) Your help with my problem highly appericiated.

I have a data matrix, PageData[111][96] and I want to write all them at once, line by line to the eeprom. I am using arduino for coding.

the code is :

{

#include <Wire.h>

#define EEPROM_ADDR 0xA0;

void setup()
{

  Wire.begin();

  Serial.begin(9600);
int PageData[111][96]={ my data is here ... }

 for (t=0; t<111; t++){
  for (unsigned long i=0; i<96; i++){
    m=i*2;
    value[m] = highByte(PageData[t][i]);
    value[m+1] = lowByte(PageData[t][i]);   }

  at=((t*192));

 for (unsigned long i=0; i< 192; i++) {
    i2c_eeprom_write_byte(EEPROM_ADDR,(at+i),value[i]);
    delay(5);                             }
      }

void i2c_eeprom_write_byte( int deviceaddress, unsigned long eeaddress, byte data )
{
if( eeaddress > 65535 )
    deviceaddress = deviceaddress | B00001000;

    deviceaddress = deviceaddress >> 1;

  byte rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));    // Address High Byte
  Wire.write((int)(eeaddress & 0xFF));  // Address Low Byte
  Wire.write(rdata);
  Wire.endTransmission();
}

My problem in this code: when I want to read the eeprom for the checking the strings, I realize, it does not write the eeprom the whole 111 line. It just writes randomly sometimes half of this sometimes less than this amount.

I tried several ways to solve the problem. but now I am desperate , please check this and tell me where i miss a point. Please let me know, if any information you need for the answer.

Writing a single byte is really bad. You are causing a page write with each bye, and each page has a limited lifetime (100,000 - 1,000,000 cycles) so use block instead.

  When writing any amount of data, including a single byte using this
  function,   the EEPROM will refresh the entire page (128 bytes) of
  data.   EEPROMs have a limited write endurance (often 1 million cycles
  per page).   Therefore, if you write one byte at a time, instead of
  writing a full block   at once, you are wasting the chip's lifetime
  (doing so is also MUCH slower).   ONLY use this if you really only
  need to write ONE byte, and avoid it   when you can.   Using a block
  write (below), you can write 128 bytes and only use a single   page
  write (or at most two, if the write is not aligned to a page
  boundary).

This library should do the trick for you:
https://github.com/exscape/electronics/tree/master/Arduino/Libraries/EEPROM/EEPROM_24XX1025


Is it possible to measure the velocity of a Unmanned Aerial Vehicle using only accelerometer? Our project is about dropping a payload from a UAV on the specified area. We are using an accelerometer (connected to the Arduino board) to measure the velocity of the plane (assuming the initial velocity to be zero). Is it possible to accurately measure the velocity of a plane moving in the air for a time t? Will this method be feasible?

Not with any measure of accuracy, no.

You're basically asking about Dead Reckoning which is problematical at best - and when doing it with just a low-grade accelerometer it can't be anything more than a rough "It's moving quick" or "it's moving slower now" accuracy.


How to write a library that support both HW and SW Serial communication and allow user to chose which one to use? I'm working on a library for Arduino/ESP8266/Teensy that use serial to send AT commands. I want to make it as customizable as possible, so I avoided to hardcode the serial and I ask for a reference in the startup method:

void MyClass::init(HardwareSerial* hwSerialPtr)
{
   _serialPtr = hwSerialPtr;
   ...
}

On some devices, it will be useful to use SoftwareSerial instead of the HW one, due to only one serial is available and so keep it for debugging purposes or other features.

So my question is: how can I accept both types? I read both HW and SW serial have Stream as base-clase, but it does not have methods like begin() etc.

A possible solution I though is so have two pointers (one for HWSerial and one for SWSerial) then wrap some methods like begin(), println(), ... in my class and, ond the base of which pointer has been set, use one or the other.

Something like this:

class MyClass{
   public:
      void init(HardwareSerial* hwSerialPtr);
      void init(SoftwareSerial* swSerialPtr);

   private:
      HardwareSerial* _hwSerialPtr;
      SoftwareSerial* _swSerialPtr;

      void begin(long baud);
      void println(const String &s)
};

then

void MyClass::begin(long baud)
{
   if( _hwSerialPtr != null ){ _hwSerialPtr->begin(baudrate); }
   else if( _swSerialPtr != null ){ _swSerialPtr->begin(baudrate); }
}

...etc...

but this solution seems to me very tricky and not optimized.

Any better ideas?

The trick here is to go "up a level".  Both HardwareSerial and SoftwareSerial inherit from the Stream class.  It is that class that provides the majority of the interface that you actually use.

So you can provide a constructor with a Stream object alone and use that:

class Foo {
    private:
        Stream *_dev;

    public:
        foo(Stream *dev) : _dev(dev) {}
        foo(Stream &dev) : _dev(&dev) {}

        void begin() {
            _dev->println("I am ready");
        }
};

Foo myFoo(Serial1);
SoftareSerial btSerial(11,12);
Foo myOtherFoo(btSerial);

What the Stream class doesn't provide, though, is .begin() for setting the baud rate. It has to be left to the user to configure the port before using it.

Serial1.begin(115200);
myFoo.begin(); // --> "I am ready" on Serial 1

or:

btSerial.begin(9600);
myOtherFoo.begin(); // --> "I am ready" on Software serial pins 11/12.

This is known as polymorphism, where an object is seen as one of the parent classes in the inheritance chain and is one of the most powerful aspects of object-oriented programming.

Not having begin in your library is no big deal really. It increases the flexibility (a user can more easily select their baud rate), and it means you don't force them to include SoftwareSerial if they don't need it.

There are other things that inherit Stream, as well, such as a networking Client. So instantly you class can be used with network connections as well as just serial.

So stick to using Stream. It's the accepted way of doing things, and perfectly normal. For example, it's how my ICSC library handles serial objects.  (I used to use the multiple pointer method, but it really really got messy when trying to support other platforms. I ended up with HardwareSerial, SoftwareSerial, USBSerial, Client... a real mess. So much simpler to just use Stream.)

BTW, before you ask, I have two constructors with very slight differences so that you can construct an object either by passing a Stream object by reference (as I do in the examples) or as a pointer (which can be great if you want to use this in another class which itself has a pointer to a Stream object).

Another option is to combine the Stream pointer with a dynamic_cast to try and identify the type of object being passed.

void Foo::begin(int baud) {
    if (HardwareSerial *hs = dynamic_cast<HardwareSerial *>(_dev)) {
        hs->begin(baud);
    } else if (SoftwareSerial *ss = dynamic_cast<SoftwareSerial *>(_dev)) {
        ss->begin(baud);
    } else {
        // We don't know what to do here
        // so do nothing?
    }
}

In this way dynamic_cast is being used like Java's instanceof operator to work out what kind of object it is that is being used.

Of course, that then means that you're really restricting the library to only working with those two types of object, but it is still possible to pass other class types as long as the user pre-configures them before calling your begin function. Which gets confusing - which type does the user need to .begin() and which types have .begin() called for you? It's just cleaner to always have it as the user must call .begin() themselves - there's no ambiguity then.


How can Arduino control with a servo with only one wire? I was playing with getting my servos to be on dedicated power, separate form the Arduino entirely, but obviously controlled by the Arduino. I originally had the ground of the Arduino joined with the - of the battery, but to my surprise my Arduino continued to control the servos when I remove the ground wire entirely from the Arduino.

I was under the impression that all electricity must form a complete circuit, and be a closed loop. But my Arduino can obviously send a signal to a component that has no return path to itself.

I feel like I'm missing something fundamental about a electricity. So my question is:

Why does this work?

The return signal is probably the other wire's servo. This only works when the control pulses to both servos are not in sync. Pull one signal wire off the breadboard and both servos will stop working.

You need to interconnect grounds or you will get strange effects sooner or later.


SD card fails to initialize I know this question has be asked before on this site. However it was never really answered. I have an Arduino Uno. I am trying to get it to read a 2 GB SDHC Micro SD card. The problem is, the SD card never intializes. I am not sure if there is something wrong with the wiring (which I think is NOT the issue) or the SD card/shield. I have formatted the SD card, but perhaps I did use the wrong settings to do so. Additionally, this SD card is quite old, probably several years. It can still be managed on my PC however.

I bought the following Micro SD shield off Amazon. It has the pins VCC, GND, MISO, CS, MOSI, and SCK, for which I figured the following:

MISO = D0
CS = D1
MOSI = CLK
SCK = D3

I have the circuit wired in the following way:

SCK to Pin 10 on Arduino
CS to Pin 11 on Arduino
MISO to Pin 12 on Arduino
MOSI to Pin 13 on Arduino
VCC to 3.3V source on Arduino
GND to Arduino Ground

The image below is a compilation of the closeup of the shield and my wiring. Not that I am also using Pin 9 in the picture. However this is used for a different portion of the circuit.

The code that I am trying to run comes from the SdFat library. Though the Amazon page says the device can be used without this library, I prefer to have it. I am running the SdInfo.ino example located in SdFat/SdFat/examples/SdInfo/. I have changed the coding so that:

const uint8_t SD_CHIP_SELECT = 10;

I have also tried running the Basic.ino example in the TMRpcm library, located at: TMRpcm/examples/basic, but this doesn't work either. Below is the code:

#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>           //  also need to include this library...
#include <SPI.h>

TMRpcm tmrpcm;   // create an object for use in this sketch

void setup(){
  tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  tmrpcm.play("music"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){
  if(Serial.available()){
    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("music");
    }
  }
}

In short. My SD card does not initialize, and I cannot seem to figure out why.

The first thing to try is to use the 'proper' pins for the SPI:

SCK to Pin 10 on Arduino ---> Pin 13
CS to Pin 11 on Arduino ---> Pin 10
MISO to Pin 12 on Arduino ---> Pin 12
MOSI to Pin 13 on Arduino ---> Pin 11
VCC to 3.3V source on Arduino
GND to Arduino Ground

Try that first and see how you get on.

By the way, just thought I'd mention, probably worth just following the Adafruit example word for word as I'm guessing your board is pretty much a good fit for this tutorial:

https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial

good luck getting it rockin' ;)


Serial communication between python and arduino I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors.
The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens.
This is the arduino code:

#include <Servo.h>
int data;
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  myservo.attach(9);
  Serial.println("Hi!, I am Arduino");
}

void loop() {
while (Serial.available()){
 //to receive more than one character
 char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
 while (!Serial.available()); // Wait for characters
 Serial.readBytesUntil('n', buffer, 7);
 data = atoi(buffer);

}
myservo.write(data);
}

And here is the python code:

import serial
import time  # Required to use delay functions

arduinoSerialData = serial.Serial('com14', 9600)  # Create Serial port
object called arduinoSerialData
time.sleep(2)  # wait for 2 secounds for the communication to get
established

print arduinoSerialData.readline()  # read the serial data and print it as
line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

while 1:  # Do this forever

    var = raw_input()  # get input from user
    print "you entered", var  # print the intput for confirmation

    arduinoSerialData.write(var)

If the python Serial write function sends byte, then you should read it in Arduino with Serial.read().

void loop() {
  if (Serial.available()){
    byte data = Serial.read();
    myservo.write(data);
  }
}

If python sends the number as text, then you can read it with parseInt().

void loop() {
  if (Serial.available()){
    int data = Serial.parseInt();
    myservo.write(data);
  }
}

The parseInt is one of the blocking functions and will by default wait one second for next char after the last sent digit was received. But the number is sent at once from python so the delays between digits are small. Set in setup() Serial.setTimeout(10);


Connecting NodeMCU through internet I have a NodeMCU and a website (free website domain provided by http://www.hpage.com) and I have to send and receive some data (suppose a 8bit number) from the website to the NodeMCU via internet. The NodeMCU is connected to internet through WiFi hotspot of an Android phone.

Can anyone provide an example code? How can I address the NodeMCU from the website?
Does the NodeMCU need to be a server or just a client?

Thanks in advance for kind help.

How can I address the NodeMCU from the website?

You can't. The NodeMcu is behind the phone, behind a router, behind a gateway of the operator etc. It can access the Internet over the infrastructure routing it out, but is not visible from the Internet.

  Does the NodeMCU need to be a server or just a client?

The device should be a client and open the communication to the server by sending a request and renewing the connection if it times out. You can use WebSockets or MQTT or similar framework.


Will an Arduino UNO operating at 16mHz communicate with UART / I2C with an STM32 operating at a different frequency? I plan to connect Arduino UNO via I2C / UART with a controller based on STM32F334K8T6, whose frequency will be about 20mHz or higher.

Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?

The tire speed will be equal. (UART 115200 Baud / I2C 100kHz)

Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?

No it doesn't. Or not much any way. It may affect the accuracy of clock generation1, which may have an affect at very high asynchronous baud rates, but other than that, no.

For synchronous communication it's all synchronised to the communication protocol's clock, so processor clocks are irrelevant.

1: Baud rates are usually generated as an integer division of the system clock. Different system clocks give different results for baud rate divisor calculations, yielding marginally different baud rates. Different baud rates will have different error percentages on different system clocks. At low speeds this has no noticeable affect. At high speeds (millions of bits per second) it can cause errors to creep in.


I2C protocol doesn't work properly I am trying to make I2C Communication between NodeMCU and arduino Uno boards. However it is not working properly. It makes communication for once time when i uploaded code.
Master Device Code(NodeMCU 1.0)
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>

HTTPClient client;

StaticJsonDocument <200> doc;

const char* ssid = "MY_SSID";
const char* pass = "MY_PASSWORD";

void setup() {
  Serial.begin(9600);
  Wire.begin(D1,D2);
  WiFi.begin(ssid,pass);
  while(WiFi.status() != WL_CONNECTED) {;}
}

void loop() {

  const char* cd = getCode();
  if(cd==nullptr) {
    Serial.println("Problem Occurred.");
    delay(10000);
    return;
  }
  //Bad code is starting...
  //Basically, sending 24 bytes of data for a Wire Transmission

  int n = strlen(cd);
  int rem = n%24; //remainder
  int quo = (n-rem)/24; //quotient

  while(quo!=0) {
    char sel[24];

    for(int i =0;i<24;i++) {
      sel[i] = cd[((((n-rem)/24)-quo)*24)+i];
    }

    Wire.beginTransmission(8);
    Wire.write(sel);
    Wire.endTransmission();
    quo-=1;
  }

  char sel[rem];

  for(int i =0;i<rem;i++) {
    sel[i] = cd[n-rem+i];
  }

  if(rem>0) {
     Wire.beginTransmission(8);
     Wire.write(sel);
     Wire.endTransmission();
  }
  //Bad code finished!

  //this is also not working.
  Wire.requestFrom(8,3);

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

  delay(15000);
}

//get code from server.
const char* getCode() {
  client.begin("http://...");

  int res = client.GET();

  if(res<0) {
    return 0;
  }

  String root = client.getString();
  deserializeJson(doc,root);
  const char* code = doc["Liste"][0]["code"];
  return code;
}

Slave Device Code(Arduino Uno)
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(8);
  Wire.onReceive(received);
  Wire.onRequest(requested);
}

void loop() {delay(200);}

void received(int bytes) {

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

}

void requested() {
  Wire.write("abc");
}

Circuit:
D1-SDA
D2-SCL
GND-GND

You may need to do some additional research. I'm debugging some I2C problems myself at the moment. Happy to share what my research has turned up:
Guiding Ideas - What could break?

Physical Layer

Unintentionally switched connections (SDA<>SCL)
Incorrect Pins selected on Microcontroller
Pull-up Resistors

Too many

Devices often have pull-ups installed by default. Only one set is needed per bus. Rule of parallel resistors applies to calculate effective resistance.

Too big (too high resistance)
Too small (too low resistance)

Voltage Conversion / Mismatched  devices
Spikes or noise on SDA, SCL or Vcc
Parasitic Capacitance

wire / trace design
bus too long

Protocol Layer

Bus Addresses incorrect / collisions
No ACK received from slave  (ref. TI article "Troubleshooting I2C Bus Protocol" below)

Timing
Missing / Unexpected SCL pulses
Incomplete 8 bit block
Missing Bytes
False slave address
Unsuccessful address change

NACK signal meaning ambiguity
Clock speed mismatch (should be running at the speed of the slowest slave on the bus)
Blocked bus (i.e., a device has reset or dropped during transmission putting the bus into an invalid state. There is no timeout.)
Multimastering (too many masters on bus?) - if more than one all must support multi-master mode
Clock stretching (a slave is holding the clock low)
What part of the message is missing? Is the initial ACK from the slave received?

Code Layer

For boards with multiple I2C ports, correctly passing the desired port to the relevant library.
Use of interrupts causing timing problems
Use of blocking code structures causing timing problems

Testing Methods

Bus Pinging / Bus Scan (like Arduino Multi-speed scanner https://forum.arduino.cc/index.php?topic=197360)
Connect additional devices to the bus and see which combinations work to identify the failing item
Multimeter checks

Stable Vcc?
Common Ground?
(Open Drain) pull-up resistance from SDA & SCL to Vcc

Test devices like Bus Pirate
Oscilloscope Analysis / Decode (references below)
Sifting out which device is causing the problem. (See Hackaday article) Put different-value resistors on the output of all chips on the bus. The low voltage values will be slightly different for each chip, allowing you to see on a scope which chip is talking at any given time, and diagnose when they’re talking over each other.
install I2C multiplexor to seperate bus into a single connector for each device (i.e., from bus to star topology) (e.g., PCA9544A)

References
I2C General

For Arduino Programming Arduino Next Steps - Going Further with
Sketches Chapter 7
For ESP32
https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/

I2C Debug Advice

I2C Primer (I2C-bus.org) - a good reference for everything discussed here https://www.i2c-bus.org/i2c-primer/

Common Problems https://www.i2c-bus.org/i2c-primer/common-problems/
Obscure Problems https://www.i2c-bus.org/i2c-primer/obscure-problems/ Analysing Obscure Problems https://www.i2c-bus.org/i2c-primer/analysing-obscure-problems/

WHAT COULD GO WRONG? I2C EDITION (Hackaday) https://hackaday.com/2016/07/19/what-could-go-wrong-i2c-edition/
How to design and debug a custom I2C master-slave system? (Stack Exchange) How to design and debug a custom I2C master-slave system?
Troubleshooting I2C Bus Protocol  https://www.ti.com/lit/an/scaa106/scaa106.pdf

Oscilloscope Analysis of I2C

How to debug I2C through waveform analysis (Texas Instruments) https://www.ti.com/lit/an/slyt770/slyt770.pdf
Using an oscilloscope to debug the I2C protocol https://www.electronicproducts.com/using-an-oscilloscope-to-debug-the-i2c-protocol/


How can I control 2 servos without an external power supply? I've been trying to implement a project that's been in my head for a while, I want to wirelessly control my light and fan switches using an ESP32 and 2 servos (one for each switch) through an HTML page, and then later integrate it with Alexa
I have seen how one servo can be controlled by connecting the servo's power cable to the ESP32's Vin pin, but how can I control two? I want to avoid using an external power supply like a battery pack because I want it to be a completely automated process, and I don't want to have to keep switching out batteries often for the thing to work. I'll be using a 5V wall outlet to power the ESP32 using a USB.
Also, if anyone can provide a few more tips on how I can make my project more efficient or point out where I might be making a mistake, I'd be glad. I'm still new to the microcontroller world.
Thanks
EDIT :  I've attached a picture of the circuit diagram, just have a look and let me know if it is workable

The power wire is just needed, well, to power the servo. The control is done via the third wire (the other wire being Ground).
You can connect the second servo's power in parallel, only the control wire must be separated from the first servo's control wire.
Note: You need to make sure that the current consumption of both servos does not exceed the provided power.


Detecting which pin called the ISR Uno I need an answer fast.I want to make a keyboard class to handle a few buttons attached to my arduino. I want to use interrupts.The problem is I have to use the same interrupt function for all my buttons(it would beimpractical to create a routine for each button).So inside the routine I must know at least what pin fired the interrupt. How can I solve this?(I belive it can be solved by changing some registers but that would be too complicated).PS:there are only two buttons(pins 2 and 3 are enough)

Edit:
   Isn't possible to create/call an interrupt routine inside a class? (I know that the routine actually doesn't exist initially because the object of the class type wasn't created). Can this be done?

class Keyboard{
  private:
    struct btn{
      boolean pressed;
      uint32_t pressTime;
    };
    btn button1;

  public:
    void int_handler(){

    }
    Keyboard(){
      attachInterrupt(digitalPinToInterrupt(2),this->int_handler,RISING);
      attachInterrupt(digitalPinToInterrupt(3),this->int_handler,RISING);
    }
};

You only have two external interrupts on the Uno, so a simple solution would be to call an "intermediate" routine, which remembers the button number. eg.

  attachInterrupt(digitalPinToInterrupt(2),this->int_handler2,RISING);
  attachInterrupt(digitalPinToInterrupt(3),this->int_handler3,RISING);

Those two functions could then call your main function passing down 2 or 3 depending on which one was called.

eg.

void int_handler2 ()
  {
  int_handler (2);
  }

void int_handler3 ()
  {
  int_handler (3);
  }

If you have more switches than that you can use pin-change interrupts. The typical way of detecting which one fired is to see which bits are different this time, compared to last time.

See my page about interrupts.


DH11 and uno relay controle fridge I want to control my bar fridge with temp sensor and relay,
This is my first project with code, i copied this:
https://robojax.com/learn/arduino/?vid=robojax-DHT22_11_TM1637_relay
But
I want some extra code that will prevent the fridge (ie relay) from going on too often.
For my purposes I want the relay to close if the temp is above 4c, but only if the relay has been off for say 20min or more.  FYI this is because my power source does not like to start the compressor when it is hot, so i don't want it cycling if it was just on.

Cool question! ;-) Instead of a fixed timer, I would build in some (so-called) hysteresis, which means turning refrigeration on above a certain temperature (say 4 °C) but only turning off when the temperature has dropped again to a temperature well below that (say 3 °C). This ensures the temperature stays within set limits while at the same time preventing fast cycling. You don’t need any timers for this and it will work in any situation (even when it’s very hot or very cold outside of the fridge). This is how commercial thermostats work.
If you really need to ensure the compressor cools enough between cycles, you just need to start a timer when it turns off, and not turn on again before it expires. Look at examples like BlinkWithoutDelay for some coding ideas.


Replacing several pinMode() and digitalWrite() pins with an array I'd like to 'clean up' some code that involves several pinMode() and digitalWrite() lines by using a single line of an array. I'm very new to both arrays so I'm a bit confused. The following examples are sections from code that controls a 4 digit, 7 segment LED.

// Define display pins
// Digit pins (common cathode)
int digit1 = 13; //Display pin 1
int digit2 = 12; //Display pin 2
int digit3 = 11; //Display pin 6
int digit4 = 10; //Display pin 8
// Segment pins
int segA = 2; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = 6; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
  pinMode(segA, OUTPUT);
  pinMode(segB, OUTPUT);
  pinMode(segC, OUTPUT);
  pinMode(segD, OUTPUT);
  pinMode(segE, OUTPUT);
  pinMode(segF, OUTPUT);
  pinMode(segG, OUTPUT);

  pinMode(digit1, OUTPUT);
  pinMode(digit2, OUTPUT);
  pinMode(digit3, OUTPUT);
  pinMode(digit4, OUTPUT);
}

#define SEGMENT_ON  LOW
#define SEGMENT_OFF HIGH

  switch (numberToDisplay){

  case 0:
    digitalWrite(segA, SEGMENT_ON);
    digitalWrite(segB, SEGMENT_ON);
    digitalWrite(segC, SEGMENT_ON);
    digitalWrite(segD, SEGMENT_ON);
    digitalWrite(segE, SEGMENT_ON);
    digitalWrite(segF, SEGMENT_ON);
    digitalWrite(segG, SEGMENT_OFF);
    break;

Defining pins:

I'm pretty sure the code below is the correct way to store the pins as an array (but please correct me  if I'm wrong).

digitPins[] = {13 12 11 10};
segPins[] = {2 3 4 5 6 7 8};

pinMode():

I understand I could use a for loop to set the pin modes but is there an even simpler way? Would something like this work?

pinMode(digitPins[], OUTPUT);
pinMode(segPins[], OUTPUT);

digitalWrite():

I could access the appropriate pin from the array to use in digitalWrite() like the code below but that would result in the same number of lines of code (and be even more confusing). Is there another option?

digitalWrite(segPins[1], HIGH);

the correct way to store the pins as an array

Your array initializers are almost right; you just need to separate the values with commas:

digitPins[] = {13, 12, 11, 10};
segPins[] = {2, 3, 4, 5, 6, 7, 8};

You will need to call pinMode() in a loop; it doesn't accept arrays as arguments.

  How about for digitalWrite() where its a mix of HIGH and LOW?

There are (at least) two ways: Make arrays of HIGH and LOW values, matching the digitPins[] and segPins[] arrays one-for-one, respectively. Or for easier maintenance, declare a data structure (struct) of a pin # and a value; make an array of those. It's a bit more complex but also more useful. So, for example:

typedef struct {
    uint8_t pinNum;
    bool pinVal;
} pinInit_t;

pinInit_t digitPins[] {
    {13, HIGH},
    {12, LOW},
    {11, LOW},
    {10, HIGH}
};

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

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

struct is short for "data structure"; it lets you combine data of different types into a single named and addressable unit. typedef declares a new data type, and says "Don't allocate any memory just now; this (pinInit) is just a description. I'll use it later on." It makes pinInit a named data type, usable wherever you can use a native data type AND a multi-valued data type (such as an array) is permissible.

Thus, we can make an array of pinInits (pin-# / boolean-value pairs) just by using the name of the new type.

Then your initializing code might look like:

uint8_t i;
for( i = 0; i < sizeof(digitPins)/sizeof(pinInit_t); ++i ){
   pinMode(digitPins[i].pinNum, OUTPUT);
   digitalWrite(digitPins[i].pinNum, digitPins[i].pinVal);
}

The expression sizeof(digitPins)/sizeof(pinInit) evaluates to the number of initializers (# of bytes in the array / # of bytes in one array member).

The expression digitPins[i].pinNum means: "in the pinInit array digitPins, get the i-th element..." (remember, this is a pair of values), "... and take value of the member "pinNum". A little more complex, the first time we think about it, but look at how easily the array reads. And a hint about reading that expression: I read it backwards: "the pinNum member of the i-th element of the digitPins array."

Tomorrow, or next month, when we need another pin, no need to update 2 arrays (remembering of course, to keep them in sequence with each other!); just add another 2-valued element to the one digitPins[] array.


Why adding a LED between Pin 3 and Ground causes LCD display not to show text? For a project of mine I am programming an Arduino UNO to show information I get from some sensors on an LCD display.

As a first step I setup Arduino to show "Hello, world!" on the LCD, which worked.

For "decorative" reasons I wanted to add some LEDs between the resistors that I placed in series between PIN 3 (V0) of the LCD and ground (about 1.5K Ohm total resistance).

I first of all added one LED between the last resistor and ground. To my surprise this causes the LCD display not to show "Hello, world!" any more.
As you can see the current is flowing (the LED is lit), but I can't understand why the LCD does not show the text.

Can you help me understand what's going on? I know very little of electronics and I am learning it by doing, so I would appreciate an answer that is good for a beginner!

In a typical 1602 LCD pinout, pin 3 or V0 is the contrast setting for the display.  It usually is set to a voltage near ground, often by using a 10K pot with ends connected to Vdd and Vss with wiper to V0.

By putting an LED in series with your resistors (that apparently go to ground) you've either disconnected V0 from ground or have raised its voltage by the LED voltage.  This reduces contrast to the point that characters aren't visible even though they are on the display.

The LED backlight remains on and at the same brightness as before because it is driven via pins 15 and 16, independent of all other display settings.

Edit 1: I haven't duplicated your circuit to take measurements, so at the moment don't know for sure; but (in resistors-only case) V0 from pin 3 on the 1602 LCD board apparently sources some small current through your 1500 Ω to ground.  When you add an LED it can disconnect V0 from ground or can raise its voltage by the LED voltage, as follows:  firstly, if the LED cathode faces V0 and V0 is positive, no current will flow through the diode, thus disconnecting V0.  Secondly, if the LED anode faces V0 and V0 is positive, current will flow through the LED.  If the LED lights at all, most of its Vf characteristic voltage (typically between 3 and 4 volts for a green LED) will appear across it.  Thus, V0 sits at close to Vf plus whatever drops across the resistors.

*The same as for other diodes, LED forward current increases exponentially with voltage (Ref: wikipedia on LED physics) hence voltage change is tiny over large changes in current when an LED is emitting light.  In other words, if the LED is lighting up, its voltage will be close (ie within a few dozen millivolts) to its characteristic band gap voltage.  See petervis.com's led-resistor-calculator for a "Chart by Colour" that shows characteristic Vf forward voltages.


How to set cables to connect Cp2102 to Pro Mini? How to connect the cables in order to program the pro mini with the CP2102 usb interface ?
The TX RX and GND is easy, but I am not sure about the RST, DTR, DST, etc
I attached the images of both.

EDIT: When I try cables like this:

TX  ... RX
RX  ... TX
5V  ... VCC // my pro mini is 5V version
GND ... GND
RST ... RST

The board lits up and green starts blinking, this should be the default blinker program.
I click upload, I get this error, and I assume the cables are not properly connected:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x89
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x89

I know some people mentioned it works by adding some resistor and capacitor, but I was hoping that is an error and it should work without that complication.

RST to RST. Ignore the others, they are irrelevant.


OOP vs procedural programming on arduino It seems like the majority of Arduino applications are written without using classes / objects. Is there a reason for this? Does is slow down the Arduino or somehow present undesirable behavior?

Your assumption is quite wrong:

The majority of libraries use OOP.
The majority of in-built device drivers use OOP.
The core is filled with many OOP helper objects and classes.
99.99% of all sketches use those OOP objects.

The sketches themselves may not be written as a class or set of classes for a number of reasons:

There is no point
The programmer doesn't know how

When a sketch is just stitching together calls to objects defined through libraries and making a few decisions there is little point in making the sketch itself an object. It's just a waste of time.  In general if the sketch gets too complex to manage it gets broken down into smaller units - i.e., libraries - which are very often written as classes.

The moment you do Serial.begin(9600); you are using OOP.


Transistors to switch monitor inputs I am using the following setup on my Arduino UNO to measure cpu fan RPMs:

The code is set to bring the trigger pin for each transistor high when it is checking that fan's RPM and FreqMeasure.h is then used to check the frequency of the signal on pin 8 which is then translated to RPM and sent to the LCD display.

I am experiencing reading issues and suspect that the signal is remaining on the measuring bus during the subsequent reads, however before revamping my code I simply wonder:

Is my circuit logic sturdy? I am just getting my feet back under me with microprocessors and have always found transistors to be a tricky subject, thanks in advance for your help!

If you'd like to see more info all can be found on GitHub.

I have simulated your circuit and it seems sound enough to me.

It is a little confusing having the transistors there though.  I would prefer to convert the three open drain outputs to logic level outputs (each having its own pullup resistor) then use a digital 3:1 MUX (or discrete logic gates) to select the signal to sample.


Humidity sensor for wet environment I've had a bit of experience with DHT11/DHT22 sensors in a greenhouse environment, and believe that when they get wet they stop working altogether.

Are there any low cost humidity sensors that I can hook up to an Arduino that don't suffer from this problem, or is there a way to protect these sensors from damage when near water? (I'm not talking about immersing them in water - but do expect condensation to get sprayed with water and/or get condensation on them from time-to-time).

Am I correct that the SHTxx sensors are able to withstand this kind of abuse, and that these sensors are about 5-10 times the cost of DHT sensors?  (I did not want to spend that much, but if it's the only possibility I might consider it).

I'd consider using Bosch BME280 digital sensor. Although it's a bit expensive, it has very good sensitivity, precision and amazingly fast response for humidity changes (for ex. in my project it detects dry human hand lying in 2" away within a 1-2 seconds).

So its features make possible to put it into an enclosure to avoid direct water contact with water spays and it'll still be very responsive for greenhouse needs, I suppose.
Datasheet warns:

  Liquids shall not come into direct contact with the device.

Also, I'd use electronic-friendly protective acrylic lacquer (Plasticote 70 for instance) and put two layers to sensor's PCB, avoiding small black tiny vent hole on the chip itself:

UPD: Here's DHT11 with cover removed:

It might be the easiest and cheapest solution to cover all internal contacts and IC (avoiding humidity sensor's stripes) of DHT11 with Plasticote 70.


Upload a .hex file, using a standalone ISP, without overwriting bootloader Is it possible to flash a .hex file on an AVR MCU, which already contains the Arduino bootloader, using an AVRISP mkII, without overwriting the bootloader?

In my concrete situation, I have an Arduino Uno that I would like to program sometimes over an AVRISP mkII, and sometimes using the built-in programmer (i.e. by just connecting the Uno via USB to a computer).

For reference, given a compiled .hex file, this is what I use to upload it using the built-in programmer:

avrdude -c arduino -p atmega328p -P/dev/ttyACM0 -b115200 -D -Uflash:w:_build/image.hex:i

By default, this works as expected. I  can also use avrdude to upload it using the AVRISP:

avrdude -c avrisp2 -p atmega328p -U flash:w:_build/image.hex:i

This gets my image on the board as well; however, it also seems to overwrite the bootloader, i.e. after this, I can only use the AVRISP, and not the built-in one, to upload images. The only way back, at this point, is to re-flash the bootloader (via the AVRISP) on the Uno.

If I try to instruct avrdude to upload via the AVRISP without overwriting the bootloader:

avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex:i

then it fails in the verification phase:

avrdude: verification error; content mismatch

Based on @ChrisStratton's answer, I understand this means my problem actually starts before I even try to upload it, by the compiler emitting code which has addresses that should belong to the bootloader.

Here is the command I use to compile and link (I am not using the Arduino IDE at all)

avr-g++ -c -g -O3 -w -std=c++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -I.. -mmcu=atmega328p -DF_CPU=16000000L blinkPB5.cpp -o _build/blinkPB5.cpp.o -MMD -MF _build/blinkPB5.cpp.m
avr-g++ -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/blinkPB5.cpp.o
avr-objdump -S _build/image.elf
avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex

As explained above, I can use the same resulting .hex file both via the bootloader (by just uploading it via serial) and the AVRISP (by overwriting the bootloader).

To preserve the bootloader, you should use the -D option in the ISP command line just as it was used in the bootloader upload command line. This will disable usage of full-chip erase.

I expect you would end up with something like

avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex

However, it is important to add something which I overlooked when first posting this answer, which is that the ATmega series cannot do a partial flash erase via the ISP interface in the way that it can when the bootloader causes the chip to program itself.  This effectively means that you only get one shot at loading a program to an already blank area of the chip this way - after that, to load a different one to the same area you will have to do a mass erase of the entire chip and reload both the bootloader and the sketch, or else command the bootloader to erase the blocks where the sketch would reside.

Of course you will also need a hex file for your sketch with no contents that conflict with the bootloader, as while the bootloader would refuse to overwrite any of its own blocks when programming a sketch, the ISP is perfectly happy to try to write over the top of the bootloader, which would likely result in a logical AND of the bits of two different pieces of code, and cause the chip to boot to nonsense.  A typical Arduino board configuration reserves space for the expected bootloader, so if the one you are using matches the size reserved in the chosen configuration, you should not have a conflict.

Another option could be to combine the bootloader and sketch hex files, literally concatenating their contents one after the other into the same file.


How to insert into table in database after every 5 minutes using Real time clock module I have RTC module attached to arduino mega,

to calculate time difference of minutes I am getting minute from the RTC module

and checking if passed time is greater than 5 minutes  then insert to MySQL table in database.

  int mint = util::getMinute();

  if (util::getMinute() - mint >= 5)

  {
    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    delay(1000);

    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      delay(500);
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
    mint = util::getMinute();
  }

the full code is here

int mint = util::getMinute();

if (util::getMinute() - mint >= 5)

{

Well, if mint is util::getMinute() then surely util::getMinute() - mint will always be 0.

I think you meant mint to be static, or a variable in the global scope.


How can I set 4 Arduino Leonardo PWM-ports between 200Hz and 1kHz? I've noticed that I can set D9, D10, and D11 to around the timer 1 can be set to ~244Hz. However I need 4 ports that are between 200-1000Hz but I have been unable to figure out how to find the last one. I can't really touch timer 0 as they control millis etc.

The ATmega32U4 on the Leonardo has 4 timers, named Timer0, Timer1, Timer3 and Timer4. Timer0 would be used for millis().

Timers 1 and 3 are 16-bit timers, and Timer4 is a 10 bit timer.

You can get a wide range of frequencies by changing the prescalers and other factors. A bit would depend on whether you want them to all have the same frequency (but maybe with different duty cycles) or different frequencies. Each timer has two "ports" associated with it, so you can have different outputs - up to a point - for each timer. A given timer can only be in one mode at a time, which limits a bit what its two output ports can be doing at one time.

I have a page about timers which is for the Atmega328P, but the Leonardo timers have a lot in common with that. For more details see the ATmega32U4 datasheet.

You could get a more detailed answer if you clarified what the exact frequency you want is, what mode (eg. PWM, fast PWM or something else) and whether each output should be the same or different frequencies.

According to the Leonardo product page:

  PWM: 3, 5, 6, 9, 10, 11, and 13. Provide 8-bit PWM output with the analogWrite() function.

So even if you lose two to Timer 0, you should have 5 outputs left (it looks like the "B" side of Timer 1 and Timer 4 share the same pin).


Can't get values of max232 with loopback I didn't find answers which solves my problem with the max232 yet.
I connected it like this to my Arduino uno, so my Arduino provides the +5V VCC and the ground:
max232 connection

The only thing what is differences are that I do a loopback at the RS232 side and I use 1µF for every capacitor even for the bypass one. I did a loopback so I can see if the max232 works. I don't get anything out of it when I send some data to it.
I measure +8.7V on pin2 and -8.15V on pin 6.

My Arduino code:

/*
  Software serial multiple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.print(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

What did I do wrong or is my max232 broken?

EDIT

I think the serial monitor (same baudrate) doesn't write to the ports so I rewrite some code.

loop code:

int i = 0;
void loop() // run over and over
{
  if(i == 10)
    i = 0;

  mySerial.write(i);
  Serial.print(mySerial.read());
  i++;
  delay(3000);
}

In serial monitor I get strange values back for a cascade counter.

Values:
-1 45 49 52 53 52 57 53 ...

These numbers aren't ascii code for ectual numbers I think.

EDIT 2

Now the loopback works thanks to the answer below.
Now I replaced the loopback with the module FUM DCF-U.
The loop code has changed to this:

void loop() // run over and over
{
  if(Serial.available())
    Serial.println(Serial.read());
}

The problem is that the result is '000000000000000000000000000000000...' in a fast rate and not every second.

The module gets its 3.3V and is connected to the same GND as the MAX232.

Pin connections:

Arduino - MAX232

11 - 11

0 - 12

MAX232 - FUM DCF-U

14 - 3

13 - 4

Thanks in advance

SoftwareSerial cannot both send and receive at the same time, as it does receiving inside an ISR, and turns interrupts off when sending. Thus this will never work properly.

I suggest you switch to HardwareSerial. Or, if you want to see the results, send using SoftwareSerial and receive using HardwareSerial. For example:

#include <SoftwareSerial.h>
SoftwareSerial mySerial (10, 11); // RX, TX

void setup ()
  {
  Serial.begin (115200);
  mySerial.begin (115200);
  }  // end of setup

unsigned long lastSend;
char c = ' ';
void loop ()
  {
  // time for another test send?
  if (millis () - lastSend >= 500)
    {
    mySerial.print (c++);
    if (c > 'z')
      {
      c = ' ';
      Serial.println ();
      }
    lastSend = millis ();
    }

  // check for response
  if (Serial.available ())
    Serial.print (char (Serial.read ()));
  }  // end of loop

I tested that as a simple loopback and it worked fine. Connect pin 11 (Tx) to pin 0 (Rx). Disconnect the wire to pin 0 whilst uploading.


L298N regulated output is greated than 5V A few months ago I used a L298N module (actually the Velleman VMA409) and I managed to make my motors working fine.
However now that I want to reuse it for another project something seems off: The regulated 5V output is always equal to the 16V VMS input.
To give more details:

I'm powering the board with 4x 3.7V 18650 batteries in series for an input of about 16V. This should be OK since according to the specs the range for VMS is 5V-35V
I'm reading the output value on the two pins I marked with an arrow in the following picture (using both of the GND pins) and in all cases I get about the same value as what I have on VMS.
This is when I have the 5V_EN jumper in place, if I remove it I get no output at all (Which I think is normal, since that disable the internal regulator)
For now I haven't connected my arduino because I want to understand what's going on before, so the Inx and EnX pins are connected to nothing.

So my questions are:

Is it indicating that I somehow fried my driver board?
Can I get back this 5V regulated output?

You are making an incorrect assumption, the L298N is an "H" bridge driver for small motors, not a 5V power supply. The 5 volt output is provided by a separate 78L05 regulator on the module.  This regulator cannot supply much power. Take a look at the schematic link given to you by ocrdu. Be sure all the grounds are connected.


Problems with (somewhat) large boolean arrays I am writing a simple Conway's Game of Life implementation just to get to grips with the "Nokia 3310" LCD and I am having problems with boolean arrays. I am using an (unofficial) Arduino Pro Micro 5V/16MHz

Here's the code that is causing me trouble:

boolean buffer[84][48];

void setup(){
  for(int i = 0; i < 84; i++){
    for(int j = 0; j < 48; j++){
      buffer[i][j] = true;
    }
  }
}

void loop(){}

When I upload this to the Arduino, it seemingly freezes up with the RX led on and its COM port stops working. If I want to upload any other sketch, I have to manually pull the RST pin LOW (since the Pro Micro doesn't have a reset button).

I've been playing around with the code and found out that the source of problems is this line:

buffer[i][j] = true;

It also doesn't matter if I use true or false.

I have tried debugging with Serial to the computer, but the Serial communication doesn't work at all, so I tried using an LED to find out where the problem is. I don't have any "regular" LEDs on me, so I had to try with an Adafruit NeoPixel. The outcome was quite interesting. When I comment out the problematic line, everything runs just fine, the led goes red for 500ms then it blinks white every time the problematic line would run and then it goes green and stays that way. With the problematic line in place, the LED won't do anything, even turn red, which I put much earlier in the code than the source of the problem.

Does anybody have any insights that might be useful? (Also, I really hope it is not some stupid typo, I swear I read it through about twenty times)

According to http://arduino.cc/en/pmwiki.php?n=Reference/BooleanVariables, "Each boolean variable occupies one byte of memory." Meaning you are trying to use 4032 Bytes of RAM with your array which I assume you do not have (whatever this unofficial Arduino is -- it's likely to be less than that: the ATmega328 of the Arduino Mini has 2 kB of SRAM, the ATmega32u4 of the Micro has 2.5 kB).

You could try with a quarter of the field size for a start and see if that makes your problems go away.


Arduino UNO with integrated ESP2866 wifi not working correctly I bought this "knockoff" Arduino UNO with an integrated ESP 2866 wifi module. But I can't make it work. I've followed this tutorial because it's the same product as I have, but I can't make it work anyway - even blinking with LED doesn't work. Does anyone have experience with this exact (or similar) board with integrated ESP2866? I would be really glad for any help. link to the product. If you need to know anything else, I'll try my best to answer it.
My problem:
The board normally loads into IDE and i can send code to it. But after I do that, I get this:
Executable segment sizes:
IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)
DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 257316 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 2c:f4:32:44:1f:0b
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Erasing flash (this may take a while)...
Chip erase completed successfully in 8.7s
Compressed 261472 bytes to 193136...
Wrote 261472 bytes (193136 compressed) at 0x00000000 in 17.0 seconds (effective 122.9 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

But the LED doesn't blink.

You are obviously currently programming the ESP8266, not the Atmega328p. The board seems to have DIP switches on it. With those you can control, which chip is connected to which. The product description has the following table
Connection  DIP
1   2   3   4   5   6   7
ATmega328<->ESP8266     ON  ON  OFF     OFF     OFF     OFF     OFF
USB <->ATmega328    OFF     OFF     ON  ON  OFF     OFF     OFF
USB<->ESP8266 (Update firmware or sketch)   OFF     OFF     OFF     OFF     ON  ON  ON
USB<->ESP8266 (communication)   OFF     OFF     OFF     OFF     ON  ON  OFF
All independent     OFF     OFF     OFF     OFF

If you want to program the Atmega328p on it, you need set the DIP switches to the combination "USB <-> Atmega328". Currently you most likely have the combination "USB<->ESP8266 (Update firmware or sketch)", which means, that the ESP is connected to the USB chip (and thus to the PC) for programming. For blinking the Arduinos buildin LED you need to program the Atmega328p.

About the blink sketch: In the tutorial video he programs the ESP. But in the blink example he changes the delay time to 5000, which would mean on and off times of 5s. The LED, that he is pointing to, is blinking much faster, though he doesn't address this. I think he actually has the standard blink sketch on the Atmega and only pretends (or just didn't notice) that this happened due tp his programming. As you don't see a blink with the ESP, but with the Atmega, I would guess, that the LED marked with L is connected only to the Atmega (like on a normal Uno) and the ESP doesn't have any LED to blink connected. So everything is actually working as expected, the tutorial was just bad at that point.


Where can I find the code for Arduino's "attachInterrupt"? Where can I find the code for Arduino's attachInterrupt function?

A search on the Arduino's Github repo yielded nothing.

I suspect it might be a wrapper for some avr-libc function but nothing in the avr-libc docs stands out to me...

It's in the core in WInterrupts.c

On my install it's at:

arduino-1.8.5/hardware/arduino/avr/cores/arduino/WInterrupts.c


Can a DHT11+ESP8266 be powered by a Adafruit USB LiPo charger directly? I have rigged up a small DHT11+ESP8266 combo which I'm currently powering from the 3.3v from an Ardruino. I've ordered a 3.7v LiPo battery and have a Adafruit usb micro LiPo charger, however, the battery will take two weeks to come.

Can I plug the usb charger directly into the DH11 while my battery arrives?

No, you can't.

The charger circuit will only operate properly with a battery attached.

It is not designed to provide power to a system. It is designed for charging the battery and nothing else.  You are supposed to remove the battery from the charger and then attach it to your circuit.  Even with a battery attached you can't use it to power your circuit - the voltage will be too high, and your target circuit will confuse the charger and it will fail to charge the battery properly (or it may end up over-charging the battery).

To do what it sounds like you want to do you need:

A LiPo charge circuit
A 3.3V regulator (ideally a Buck/Boost combined regulator)
Bypass circuitry to power the 3.3V regulator directly from the incoming power when present or from the battery when no external power is present.


5v relay module and suitable bulb adapter I have 5v relay module . I want to use it to connect e27 bulb adapter but i cant choose any suitable adapter . Pls help me sir. I to find exactly the same as the picture

There is no such thing as a "suitable" bulb holder.

Bulb holders are bulb holders. They hold a bulb. They have wires connected to them. They come in different shapes and styles, and that shape and style has nothing at all to do with how they work or how you connect them.

You pick a bulb holder that is the right kind for your project - be that a ceiling rose + pendant combination, a wall mount angled, a table lamp, a standard lamp, a chandelier from Ikea...

If you are looking for something that is identical to that drawing then you may be sadly disappointed. That's a drawing. A representation. The actual device you choose to use is whatever device you deem is the right one for your design.


Nano-like Board - Programmer Not Responding I am trying to upload a basic sketch to my unofficial Nano-like board and keep getting this error. I understand that it is a generic connection error between the Arduino and my PC, but can't figure out why it is having this problem.

Semi-compatible nano-like board
Drivers
Arduino IDE 1.8.3 freshly installed
Windows 10 64-bit
Also tried on Mac OSX with the same result

I've looked up the drivers from the manufacturer's website and installed them, and the Arduino Nano shows up just fine under my Device Manager. The green power light comes on, it is recognized by my PC, and blue flashing 'L' light blinks, making me think that the manufacturer had uploaded the Blink sketch to test it. However, when I try to upload a sketch from the IDE I get this error:

avrdude: stk500_recv(): programmer is not responding

Under 'Tools" I have the board set to 'Arduino Nano', the processor set to 'ATmega168' and the port the same COM port as what it's listed as in Device Manager. Assuming that all of those are correct, I have tried a few things with no luck:

Reinstalling the IDE, drivers and restarting my computer.
Letting Windows find its own driver.
Pressing the 'reset' button just before hitting 'upload' in the IDE
Using different micro USB cables and USB ports on my computer.

Any other ideas or is the unit possibly just faulty?

Please note that I have already at similar questions and tried a bunch of their suggestions with no luck.

That is a Chinese NANO clone, using the notorious CH340G chip.

macOS does NOT have a driver, and it is difficult, if not impossible to get a driver which 1. macOS will let you install, and 2. Actually works.

I do not know the state with current Windows.

In my experience, in addition to poor support the chips are unreliable and fail to respond.

You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.


Plugged in shield off by one, now all analogues read high I have a prototyping shield for an Arduino Uno. I accidentally plugged the shield into my arduino so that the pins were all "off by one". I didn't think this was possible, but it turns out that the extra pin just slips between the gaps in the pin headers:

I powered it on not realising. The arduino didn't show any LEDs, so I powered it down, saw my mistake, and plugged it all in again.

Now though A0-A5 are all reading high values (~900-1000 when I do analogRead(A0)), even when I have pulldown resistors on them, and they still read like that when I unplug my shield all together.

The digital writes all work perfectly.

I'm thinking that I've broken the Arduino. Is that possible, or could it be something else?

There is not (yet) enough information to be certain, but it seems likely that you have damaged the Arduino.

If damage has occurred it's more likely to have been caused by what happened on the other side of the board, where pins carry power supply voltages. You do not say what your power source is or where it is connected (USB, 5V in, Vin, ...) but I'd guesstimate that the connection of UNO 5V to Shield 3V3 allowed back feed into the UNO by any of a number of possible paths. UNO Vin connects to shield ground and a second UNO ground connects to a second UNO ground - so if the UNO was powered via Vin you'd expect the power supply to have been shorted. This might damage some power supplies but usually not.

Can you please advise what voltage was connected and to what pin. And do shield pins all offset by 1 on the other side, as I've shown?


What is the most efficient voltage divider for Arduino? I need to make voltage divider, so I could read a battery voltage up to 14.4 V. Could I use very high resistance resistors for that, so the current would be very low (to not to discharge battery)?
On the Internet there are examples with 500 - 2000 ohm resistors, but could I use hundreds of thousands to reduce the current to minimum? Would Arduino's analog input still read the value?

The most efficient is not to have a voltage divider at all. Or at least to only have a voltage divider when you actually need one.
My preferred schematic is this:

simulate this circuit – Schematic created using CircuitLab
With this M1 is normally kept turned off by R3. When you want to take a measurement you turn on M2 by setting D3 HIGH (or whatever pin you attached it to) which pulls down the gate of M1 turning it on. This then connects the batter to the voltage divider R1/R2 and allows you to read the voltage at A0.
The voltage divider of 20k / 10k allows you to read up to 15V on the battery, and gives you an output impedance of 6.67kΩ which is within the recommended maximum of 10kΩ for the ATMega's ADC.
During "idle" times when M1 and M2 are both off the only current flowing is the minuscule leakage current through M2 tempered by the large 100kΩ resistor R3 (which itself pales into insignificance compared to the "off" resistance of M2 anyway).
Selecting M1 so that the ON resistance is very small (<0.1Ω) allows you to essentially ignore it in your calculations since that will be swamped by the tolerance of R1 and R2 anyway.  M2 needs to be selected so that it is "logic level" (i.e, with a gate threshold V_GS well below 5V).
This double-FET arrangement should be used rather than just using an N-channel FET in the ground connection of the divider because when that simpler arrangement is turned off the Arduino will be seeing 12V directly connected to A0 which really is not good - you will kill the Arduino - so it is important that you switch the "high" side of the network not the "low" side, and to do that requires two FETs.


RFduino communication capabilities Is there any way to connect RFduino's via radio frequency? Or any capability to transmit information between RFduino's for distances up to 200 feet?

I would like to purchase a dev kit (for RF duino) but i'm not sure what parts I will need to transmit info longish (200 feet) distances.

https://blog.adafruit.com/2010/06/11/aprs-radio-shield-for-arduino/
Be warned you need a license to transmit on amateur frequencies at least in the US, you will also need to hook up a transmitter for this shield.

GSMShield would also be great and is something I'm thinking about using for my project, the way the Arduino IDE is setup and the libraries already in place I'm sure it would be easy to turn text messages into commands or readable and usable data between the sender and receiver.

Here are two ways one using a long range radio frequency or the GSM network. We would need to know more exact data of your project on how to implement these two solutions to accomplish what you would like to do.

The first option is most likely going to be the lesser option if you don't have a license to transmit long range frequencies and do not have experience.

The second option is easy and all you would have to do is make sure both sender and receiver are within a GSM network.

Good luck and I'm excited to see what other solutions others may post since I'm in the same boat.