Interruption triggered twice when set to FALLING I have a simple sketch with a button that triggers an interruption set to happen when the button pin goes from HIGH to LOW. It has debouncing so no repetitions happen when the button is pressed, but sometimes when releasing the button the interruption also fires. Why would that be? Shouldn't the debouncing take care of any micro-rising during the release of the button?

volatile int contador = 0;
int n = contador;

long t = 0;
void setup() {

    pinMode(2, INPUT_PULLUP);
    attachInterrupt( 0, incrementaContador, FALLING);
}

void loop() {
    if (n != contador) {
        n = contador;
    }
}

void incrementaContador() {

    if ( millis() > (t + 50) ) {
        contador++ ;
        t = millis();
    }
}

This same code works correctly when set to LOW instead of FALLING.

but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.

Example:


Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor? I am trying to use an ESP32s controller connected to an RC car DC motor. I found that when using my Arduino this is easily accomplished, and I can see that my output pin produces 5v for the motor to spin. My ESP32, however, only produces 3.3v, so of course the motor does not spin. Do I need to use a motor driver board, transistors, or will the ESP32 simply not work in this scenario?

Thanks in advance.

You should not power a motor from a micro-controller, period, regardless if that is an ATmega or an ESP32.

Instead, you need to use a motor driver circuit - this isn't really so much about voltage amplification, as it is about current amplification. The actual I/O output voltage of your ESP32 is likely very close to 3.3v. If you are measuring 1.8v, that is only because you motor is loading the pin so heavily (and improperly) that the voltage sags.

Without the specs of your motor, it's not really possible to provide any specific advice. But you should seek an FET-based solution, not one based on bipolar transistors.  The old bipolar L293D, L298, etc parts are horribly lossy and extremely unsuited to low voltages motors. In some low-voltage, low-current cases, the FET-based TB6612FNG can be a good solution - but again, this depends entirely on the unstated requirements of your motor. Typically only very lightweight or weak "RC cars" could use such drive, for more serious ones you should look at hobby-grade Electronic Speed Controller (ESC) modules, or their equivalent circuitry.

These motor driver chips will have two supply inputs. One supplies the logic and would typically share the microcontroller's supply voltage. The other supplies the motors - it might in light duty cases be whatever is supply the microcontroller's regulator, but in more power-hungry cases would often be a unique supply. Both grounds should be connected together and connected to the microcontroller's ground, but in such a way that the ground current for the motors flows directly from the power supply, and never through the microcontroller board.


Teensy not pulling down despite digitalWrite(x,LOW) I'm trying to switch a ATX PSU on and off by serial command. My code is as follows:

#include <Arduino.h>
#define PIN_LOW_FOR_POWER PIN_F0

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

void loop() {
  String sCode = Serial.readStringUntil('\n');
  if (sCode == "M80"){
    digitalWrite(PIN_LOW_FOR_POWER, LOW);
  }
  else if (sCode == "M81"){
    digitalWrite(PIN_LOW_FOR_POWER, HIGH);
  }
  else{
    Serial.println("Unknown command");
    return;
  }
  Serial.println("OK");
}

I'm getting "OK" back, and the power switches. After sending M81 I read 5V across the pin and ground, but after sending M80 for some reason I read 2.37V and not 0V. If I switch to "F1" (keep the wire connected to F0) I do read 0V.

The ATX PSU needs F0 to be pulled down in order to turn on. I soldered the ground of the ATX PSU to the Teensy ground, and the wire to be pulled down (green) to F0. I supply the 5V to the Teensy through USB, so the VCC pin is left unconnected.

The PSU does turn on if I manually create a short between F0 and ground.

Why doesn't the Teensy pull F0 down, and how do I resolve this? (All I could come up with is something of internal resistance within the Teensy being too high, which seems unlikely to me. (If the resistance within the PSU and wires between "green" and ground is equal to the resistance within the Teensy this would happen, right?))

PS: It turns out I bought a fake Teensy from China, if it's related. Ordered a new one for a different project, but still had this one laying around.

You forgot to set the IO pin to OUTPUT. Unless you do so all you are doing (if the Teensy core follows the Arduino API to the letter) is controlling the internal pullup.

pinMode(PIN_LOW_FOR_POWER, OUTPUT);


FFT (or similar) library for the Arduino I'd like to build a "low fidelity" spectrum analyzer to run on an Adafruit Trinket Pro. My primary goal is to intrigue my seven year-old niece with something that can be hacked. The plan is to pick up sound from a violin with a mic and use a set of 5 or 6 NeoPixels to represent octaves and use color for amplitude.

My first pass at this used Amanda Ghassaei's frequency detection code. It kind of worked, but seemed to be having problems with complex waveforms. After doing some more reading and looking at simple spectrum analyzers it seems that I'd do better using something like a FFT to collect the frequency information. It also seems that that might be stretching the capability of an Arduino…

Are there any FFT libraries that run well on the Arduino (over a range of about 200 to 4000 Hz)? Or are there other approaches that might work better?

I havent used any of the libraries to make the FFT for my personal project, due to complexity. Instead I bought a spectrum chip, which returns 7 frequencies: MSGEQ7  ( 63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and
16kHz ).

Otherwise if you are very keen on using a library, this one is very famous and fast for Arduino processors.

But again, if you dont need to have a precise band and the MSGEQ7 is good enough to detect what you want, go for it.


Override #define statements in libraries I'm using a library that, by default, wants to use Serial2 as the interface to a display, however, I'm working with an UNO which only has one serial interface, so the compile fails. I'm trying to use a SoftwareSerial instead, but I can't figure out how to override the #define statement in the library without editing the library.

I'm guessing since the software serial port isn't generated at compile time, I can't.

#include <SoftwareSerial.h>
#define nexSerial HMI
#include <Nextion.h>

SoftwareSerial HMI(8,9);

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

}

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

}

I haven't started writing code yet, can't get past the attempt to redirect the serial interface to a software serial.

You're allowed to modify the header file.  The version I looked at says

#define USE_SOFTWARE_SERIAL //Comment this line for use  HardwareSerial

...but I think he meant "comment this line out to use HardwareSerial".  Or conversely, "uncomment this line to use SoftwareSerial."

Then you just pass your SoftwareSerial instance into the Nextion constructor:

SoftwareSerial HMI( 8,9 );
Nextion nextion( HMI );

void setup()
{
   HMI.begin( 9600 ); // or whatever speed...

However, because you are using pins 8 & 9, I would strongly recommend using AltSoftSerial instead.  It is much more reliable and efficient.  MUCH.

You would have to modify the Nextion files to either (1) search and replace all occurrences of SoftwareSerial with AltSoftSerial, or (2) add a third choice to the author's #ifdef/#endif sections.  For example:

#define USE_SOFTWARE_SERIAL // uncomment this line to use SoftwareSerial
#define USE_ALTSOFT_SERIAL  // uncomment this line to use AltSoftSerial
                            // comment both above  to use HardwareSerial

#if defined(USE_SOFTWARE_SERIAL)
#include <SoftwareSerial.h>
#elsif definied(USE_ALT_SOFTSERIAL)
#include <AltSoftSerial.h>
#endif

class Nextion{
 private:
  void flushSerial();
#if defined(USE_SOFTWARE_SERIAL)
  SoftwareSerial *nextion;
#elsif defined(USE_ALTSOFT_SERIAL)
  AltSoftSerial *nextion;
#else
  HardwareSerial *nextion;
#endif

Do either one of those things in all files that refer to the Nextion serial member; Nextion.CPP certainly needs it.


Reading bitswise for 'FALSE' In the sketch I'm working on, I'm storing several 1-bit values representing different boolean states in a single byte, trying to save precious RAM.
(example for 5 boolean states: dec10 = b00001010, the five states are 0, 1, 0, 1, 0)

I'm then using an if statement to determine if the relevant bit is TRUE or FALSE:
if ((options>>3) & 1 == 1)

The above will evaluate true when the relevant bit is 1, so if I want to carry out something in that case, great, no problem!

However, if I want my if statement to evaluate TRUE in the event that the relevant bit is 0, I can't work out what code I need.

I thought the problem might be that the other 'non-relevant' bits were interfering, so I tried bit shifting the LSB all the way to MSB position and then shifting back to LSB:
if ((options<<4>>7) & 1 == 0)
but this still isn't doing what I'm trying to achieve (and seems like a lot of work for the processor).

It also feels like I've tried just about every combination of ~&0, !&0, ==0, !=0, ~&1, !&1, ==1, !=1 there is, but I must have missed something...

Can anyone tell me how I get an if statement to evaluate true in the event that the bit is a zero?

The simplest thing is just to mask an individual bit, not do any shifting:

if (options & 0x04) {
    // Do something if true
} else {
    // Do something if false
}

Or, to invert it:

if (!(options & 0x04)) {
    // Do something if false
} else {
    // Do something if true.
}

The thing with C is that 0 is false, and anything else is true.  So if your options variable contains 0b00001010 and you AND it with 0x04 (which is HEX for 0b00001000) you end up with 0b00001000.  That is 0x04, which is something other than 0, so it's true.

If options contains 0b00000010 and you AND it with 0x04, you get 0b00000000, which is 0. Since 0 is false the result is false.

You don't care what the actual number is - you only care if it's 0.


Debugging my Stepper Motor Driver circuit I'm using the Pololu DRV8825 Stepper Motor Driver to control a NEMA 17 Steppermotor with an Arduino Uno.  According to the Pololu website, the circuit should be wired as follows:

I did, however, deviate from this exact sketch a little bit:

The Arduino (microcontroller) is powered by a USB cable connected to the computer
I connected the 5V pin on the arduino to the + rail on a breadboard.  I then connected two wires on this rail to the RESET and SLEEP pins on the driver.
I'm using a 9V battery to power the motor.
I've connected the DIR and STEP pins to Arduino Uno pins 12 & 13, respectively.

Consequently, I coded and uploaded the following sketch:

int stp = 13;  //connect pin 13 to step
int dir = 12;  // connect pin 12 to dir
int a = 0;     //  gen counter

void setup()
{
  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
}

void loop()
{
  if (a <  200)  //sweep 200 step in dir 1
   {
    a++;
    digitalWrite(stp, HIGH);
    delay(10);
    digitalWrite(stp, LOW);
    delay(10);
   }
  else
   {
    digitalWrite(dir, HIGH);
    a++;
    digitalWrite(stp, HIGH);
    delay(10);
    digitalWrite(stp, LOW);
    delay(10);

    if (a>400)    //sweep 200 in dir 2
     {
      a = 0;
      digitalWrite(dir, LOW);
     }
    }
}

RESULT
The stepper motor does not turn.  Instead, it just hisses at a high pitch.  After a short while, the driver gets very hot.

THINGS I'VE TRIED

I double checked to make sure that connected stepper wires pairs are properly connected to the "A" pins and "B" pins on the driver.
I tried reversing the A1-A2 pair and B1-B2 pair in all possible combinations.  All combinations produce the same result as above.
I tried increasing the motor power supply to 12V (8 alkaline AA batteries).  The same result occurs.
I double checked to make sure the 100microF radial electrolytic capacitor is connected with the long end to the positive motor supply and short end to the negative motor supply (on a different breadboard rail than the logic power supply, of course).
I tried using the 3.3V pin instead of the 5V pin to connect to SLEEP and RESET on the driver.  Again, the same result occurs.

I'm not really sure what to try next to debug my circuit.

My Hunch:

I do, however, have one suspicion based on a little warning box on the pololu website which reads:

  Caution: Installing the header pins so that the silkscreen side is up
  and the components are down can limit the range of motion of the
  trimpot used to set the current limit. If you plan on installing the
  header pins in this orientation, please set the current limit before
  soldering in the pins.

The way I soldered the headers onto the driver looks like the bottom left corner of the picture below:

My Question:
Given that my stepper motor requires 1.7A current, is there anything I can do to improve this circuit to make it work?  Did I make any mistakes?  Is there anything else I should try or check?  Did I solder the header in the wrong way?

I had this same issue when setting up this circuit with this code and driver on an Arduino Uno. All else was fine, but the current for the motor was set WAY too high on the driver from the factory. The VREF was 1.7 volts, and it needed to be around .5 for the motor I was using. As I set the VREF to the appropriate voltage, the motor started to spin as it should and stopped hissing.

I know this post is old, but I hope that this helps someone else. Pololu has a great video (and documentation in general) for setting the appropriate voltage on most of their drivers on the product page here: DRV8825 Stepper Motor Driver Carrier, High Current.


Why does my lcd screen work fine and then display random characters? It works as expected for a few seconds and then random letters appear on the second row. The wiring and the programming should be correct. I wired it according to an Arduino Starter Kit Book and coded it myself.

Code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=23;
int minutes=0;
String none="00";
unsigned long timer;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("23:00");
}

void loop() {
timer=millis();
if(timer%600==0){
   minutes++;
  if(minutes==60){
      minutes=0;
      hours++;
      }
   if(hours==24){
      hours=0;
   }
  lcd.clear();
  lcd.setCursor(6, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 1);
  if(minutes<10){
    if(hours<10){
      lcd.print(String("0")+hours+":"+"0"+minutes);
    }
    else{
      lcd.print(hours+String(":")+"0"+minutes);
    }
  }
  else{
    if(hours<10){
       lcd.print(String("0")+hours+":"+minutes);
    }
    else{
       lcd.print(hours+":"+minutes);
    }

  }
  delay(200);
  }
}

I was able to narrow down the problem. I was testing what happens when it hits 24 hours so I set hours to 23 in the beginning and made the time 600 ms. Once it hits 10 seconds, the characters appear. If the hour is a 2 digit number, the issue happens. I made the hours 9, and the issue disappeared. What can I do?

The problem was that I was adding ":" to the printed string on the lcd without making it a String object. That only occurred if I had double digit hours and minutes.

Incorrect way:

lcd.print(hours+":"+minutes);

Correct way:

lcd.print(hours+String(":")+minutes);


Writing and reading multiple values through serial I am currently busy with a project that requires me to use an Arduino and 3 potentiometers (to change background in RGB format) to write values through the serial port and read and separate them in processing.

What I want to do is to be able to use my Arduino to write multiple values to a processing program. I am quite new to coding and its been a while since I worked with my Arduino. I know how to read and write one value, but not multiple values.

Also is there a way to write 20 values?

Thanks in advance!

The simplest way is to just print them as a single line and separate them with "something". That "something" could be as simple as a space.

Serial.print(val1);
Serial.print(" ");
Serial.print(val2);
...
Serial.print(" ");
Serial.println(val20);

743 234 34 599 2 ... 427 1013 48 2 409

Then in processing you just read the entire line into a String and split it on the spaces into an array.


Arduino + 4051 -> noise on certain 4051 pins I am trying to use two 4051 ICs with an Arduino Micro right now. The idea was to have an 16-sensor demo station (8 sensors per 4051) wherein each 4051 pin selection is controlled by a potentiometer as input. I am new to using MUX's, so I mocked the following up as a quick demo based on this help document via Arduino (it's basically the same), which only uses one 4051 and does not use a potentiometer as selector input. So, I should be able to set the variable which to whatever number (0 - 7) to change the sensor selection that shows up at A2 on the Arduino.

Setting which to 0 is fine, but when I have more than two sensors plugged into 4051 and set the selector pin to any other number than 0 there is a strong likelihood that the output that shows up in the Serial Monitor is both unresponsive to the selected sensor change and appears to be simply noise (random numbers around 200 or so). I have been trying to isolate where this noise is coming from and am totally stumped. Has anyone had this issue and, if so, any suggestions on how to further diagnose what is happening? I am currently powering everything off of the Arduino 5V, which I am under the impression should be okay, though I have tried this with external power supplies (12V at 2A, for example) and gotten the same results (so I am fairly certain power is not the issue here).

Measuring voltage on pins 2, 3, and 4, I am seeing 1mV on pin 2, 1mV on pin 3, and 0.9mV on pin 4 following the initial spike during upload. When comparing against the Arduino 4051 doc I linked to above, I see that in that file pins 2, 3, and 4 show a Voltage of 2.5V following the initial spike during upload. Any idea what I am doing incorrectly?

/*
Sensor Station via MUX

 * code example for useing a 4051 * analog multiplexer / demultiplexer
 * by david c. and tomek n.* for k3 / malmï¿½ hï¿½gskola
 *
 * edited by Ross R.
 */

int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}

void loop () {

  which = (0);

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);
}

I have a post about that chip at 74HC4051 multiplexer / demultiplexer.

I made up the circuit shown on my page above with modifications as described below:

I moved the A/B/C and O/I pins to match your code.

A is the low-order bit so pin 11 on the 74HC4051 should go to D2 on the Arduino.

74HC4051  Arduino   Meaning
    11       D2        A
    10       D3        B
     9       D4        C
     3       A2        O/I

I put a pot on I/O0 (pin 13 on the 74HC4051) and randomly set the other pins to +5 V or Gnd, as shown.

In setup() I added:

Serial.begin (115200);

I also modified it to automatically sequence through all 8 possible ports, and then stop after 1000 iterations to stop flooding the USB port on my computer. Code is:

int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  Serial.begin (115200);
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}  // end of setup

unsigned long counter;

void loop () {

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);

  if (++which > 7)
    which = 0;

  if (++counter >= 1000)
    {
    Serial.flush ();
    exit (1);
    }
}  // end of loop

The output from your sketch was as expected:

sensor number 0 val is 781
sensor number 1 val is 0
sensor number 2 val is 1023
sensor number 3 val is 1023
sensor number 4 val is 0
sensor number 5 val is 0
sensor number 6 val is 0
sensor number 7 val is 1023

I suggest you check that your wiring agrees with mine.


HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3 I have recently purchased a ESP-8266 HUZZAH by adafruit. I'm kind of new to the whole arduino concept. I would like to know how I would be able to utilise this breakout board with my Arduino to do anything. I have searched on the internet and I know about flashing the board. However, I have no idea how to flash this device. Some help would be appreciated.

I also have no idea where to put my pins. I know that there are RX and TX pins on the UNO, but those are at 0 and 1. Most online guides are using something like 11/12 or 2/3.

Here is the link to the product website

Thanks,
Vraj

Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.

Arduino | HUZZAH ESP8266
RX | RX (In the front)
TX | TX (In the front)
5V | V+ (In the front)
GND | GND (In the front)

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. This is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.

To use NODEMCU LUA which it comes preloaded with, you need to refer to this guide.

The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github (this one).

The next step was to get the pin layout (from here). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page (here) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.


Pro Mini atmega168 voltage woes I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?

I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?

Bypass the regulator, and connect the battery directly to the VCC pin. However, running at 16Mhz requires at least 3.8 Volts, according to the datasheet. Lower voltages may work, but aren't guarantied.


digitalRead keeps giving 1 I am new to arduino programming and I have bought arduino UNO a few days ago.

I am trying to read the value of pin 4 using digitalRead with pinMode INPUT_PULLUP but it keeps giving me 1 even when the pin 4 is not connected to anything.

Here is the code:

void setup() {
  pinMode(2,OUTPUT);
  pinMode(4,INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
}

void loop() {
  Serial.print(digitalRead(4));
  Serial.print('\n');
  delay(150);
}

Pin 2 is connected to one side of the button and Pin 4 is connected to other side of the button.
According to condition, when the button should be off , the value should be 0 and when the button  should be on , the value should be 1 , but the value is 1 even when I press the button is off or on.

On the other way , if I replace INPUT_PULLUP with INPUT then the value is floating.

Why the value with INPUT_PULLUP is 1?

You have set Pin 2 to HIGH, which is 5V. You have set Pin 4 to INPUT_PULLUP, which means if no signal is driving it, it will be HIGH.

You have connected a button between Pins 2 and 4. So, if you don't press the button, the input is pulled HIGH. And if you do press the button, Pin 2 is driving it HIGH.


Using a relay to control a lamp Okay, so I'm using an Arduino Uno R3 and I wanted to start of my own home automation project. I have a 4 channel 12V relay board and I normally connect it to a 12V 500mA adapter. What is the maximum wattage bulb (or CFL) that I can power with this configuration?

Unless you feel like starting a fire, none. Find a 220V 2A relay with a 5V coil and use that instead, switching the hot wire and not the neutral.


Function Millis() Arduino I would like to make a countdown with arduino.
To do this I'm using the millis () function, but I have a problem, I can not reset this.
Reading on the internet I read that it is not possible to do this.
So how can I find an alternative for this?
In practice, when I pressed the button I started the countdown, while if I put it back, I went into the pause mode.

void inizio(){
  Serial.println("INIZIO");

  currentMillis1_general = millis();
  total_1 = currentMillis1_general - currentMillis_general;
  Serial.println(total_1);

  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    step_funzione = 1;
    delay(200);
  }
}

void countdown(){
  Serial.println("COUNTDOWN");

  display.setBrightness(7);

  currentMillis_general = millis();
  total_general = currentMillis_general - total_1;

  if(total_general - previousMillis_general >= interval_general){
    previousMillis_general += interval_general;
    //previousMillis_general = currentMillis_general;
    m = new_tempo/60;
    s = new_tempo%60;
    new_tempo--;
  }

  display.showNumberDec(m, true,2,0);
  display.showNumberDec(s, true,2,2);

  Serial.println(total_general);

  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    step_funzione = 0;
    delay(200);
  }
}

A way to accomplish "Reset" is to set your starting value equal to millis() again. To do the equivalent of "Pause", you need a pause counter. When you begin a pause, save millis() to pauseTime. When you resume running again, add millis() - pauseTime to your pauseCounter. Then your interval should not expire until millis() - pauseCounter > Interval).


SD Card and Lora module arduino uno Background: When working on the 2 modules separately they were working perfectly.

Problem: In the code attached we tried integrating them but Lora wouldn't receive any data unless we commented out parts of the SDC function. Is there a fix to this?

This is where the problem occurs:

Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){

No matter how much we feed it with TRUE data from another Lora with these codes it simply shows blank and false.

Please Help this poor lamb. This for our school project. Hopefully, you can spare me some of your time. Thank you so much in advance.

for the CS pins:
Lora: pin 10,  SD: pin 5

other SPI pins follow the standard pins.

PS: In the code, we have commented out some of the lines within the SDC function as based on our observation:

myFile = SD.open("HG.txt", FILE_WRITE);
   myFile.close();

These 2 lines are the ones causing our Lora to not display the data it is receiving in the (String receive variable).

Thank you, good sir/ma'am, once again hopefully you can assist me.

Here is the complete code:

#include <SPI.h>
#include <SD.h>
#include <RH_RF95.h>
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 2
#define RF95_FREQ 868.0
RH_RF95 rf95(RFM95_CS, RFM95_INT);
unsigned long millisecs;
int cnt;
float valu;
String jh;
int code=1;
String received;

File myFile;

void setup(){
 Serial.begin(115200);
 if (!SD.begin(5)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  else{
  Serial.println("card initialized.");
  }

  delay(100);

 pinMode(RFM95_RST, OUTPUT);
 digitalWrite(RFM95_RST, HIGH);
 while (!Serial);
 Serial.println("Arduino LoRa RX Test!");
 digitalWrite(RFM95_RST, LOW);
 delay(10);
 digitalWrite(RFM95_RST, HIGH);
 delay(10);
 while (!rf95.init()) {
 Serial.println("LoRa radio init failed");
 while (1);
 }
 Serial.println("LoRa radio init OK!");
 if (!rf95.setFrequency(RF95_FREQ)) {
 Serial.println("setFrequency failed");
 while (1);
 }
 Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
 rf95.setTxPower(23, false);
}

void lorA(){
  while(code==1){
if (rf95.waitAvailableTimeout(1000)){
 Serial.println("dayun ");
 uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
 uint8_t len = sizeof(buf);
 if (rf95.recv(buf, &len)){
 cnt++;
 Serial.print("Data number: ");
 Serial.println(cnt);
 received=(char*)buf;
 Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){
 uint8_t data[] = "And hello back to you";
 rf95.send(data, sizeof(data));
 rf95.waitPacketSent();
 Serial.println("Sent a reply");
 code=0;
 }
 }
 else{
 Serial.println("Receive failed");
 }
 }
 }
 }

void SDC(){
  while(code==0){
  Serial.println("SDC");
//  File dataFile = SD.open("HG.txt", FILE_WRITE);
//  String dataString="Hans";
//  if (dataFile) {
//  dataFile.println(dataString);
//  dataFile.close();
//    Serial.println("closed");
//    Serial.println(dataString);
    code=1;
//  }
//  else {
//    Serial.println("error opening datalog.txt");
//  }

  }
  }

void loop(){
  Serial.println("loop");
  lorA();
  Serial.println("mid");
  SDC();
}

all of your problem can be solved through a simple trick ... Just follow it...

Use Sdfat library insted of SD
just follow SPI datasheet..

follow below code ... it works with LORA AND SD both together

...

#include <SdFat.h>
#include <SPI.h>
#include <RHReliableDatagram.h>
#include <RH_RF95.h>

SdFat sd;
SdFile myFile;

#define chipSelect 4

#define RFM95_CS 10 //
#define RFM95_RST 9
#define RFM95_INT 2

// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS,RFM95_INT);
//RH_RF95 driver(5, 2); // Rocket Scream Mini Ultra Pro with the RFM95W

// Class to manage message delivery and receipt, using the driver declared above
RHReliableDatagram manager(rf95, 2);

void setup() {

  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonardo

  delay(100);

  // Initialize SdFat or print a detailed error message and halt
  // Use half speed like the native library.
  // change to SPI_FULL_SPEED for more performance.
  pinMode(RFM95_CS, OUTPUT);
  digitalWrite(RFM95_CS, HIGH);
  digitalWrite(4, LOW);

  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

/*

/*
 * //Open file and write  ...
 *
  // open the file for write at end like the Native SD library
  if (!myFile.open("mrinmoy.txt", O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening test.txt for write failed");
  }

  // if the file opened okay, write to it:
  Serial.print("Writing to test.txt...");
  myFile.println("testing 1, 2, 3.");

  // close the file:
  myFile.close();
  Serial.println("done.");
  */

  /*
  // open the file for reading....

  if (!myFile.open("mrinmoy.txt", O_READ))
  {
    sd.errorHalt("opening test.txt for read failed");
  }

  Serial.println("mrinmoy.txt:");

  // read from the file until there's nothing else in it:
  int data;

  while ((data = myFile.read()) >= 0) Serial.write(data);
  // close the file:
  myFile.close();
  */

  // manual reset
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);

  digitalWrite(RFM95_CS, LOW);
  digitalWrite(4,HIGH);

  while (!manager.init()) {
    Serial.println("LoRa radio init failed");
    while (1);
  }
  Serial.println("LoRa radio init OK!");

 // digitalWrite(RFM95_CS, LOW);

}

void loop()
{
   uint8_t data[] = " Hi.. This is node 1.";
 //   unsigned char sd_data[50];
// Dont put this on the stack:
 // uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
   uint8_t buf[50];
  // nothing happens after setup

  //LoRa.setPins( LoRa_CS, LoRa_RST, DI0 );
  digitalWrite(4,HIGH);    //  deselet SD Card SPI
  digitalWrite(RFM95_CS, LOW);    //  SELECT (low) LoRa SPI
  SPI.begin();

  // Send a message to manager_client
  if (manager.sendtoWait((uint8_t*)data,sizeof(data),1))
  {
    Serial.print("successfully sent to: ");
    Serial.println(1);
  }
  else
  {
    Serial.println("send failed");
  }

  // receiver ....

   // Now wait for a reply from the server
   uint8_t len = sizeof(buf);
   uint8_t from;

   if (manager.recvfromAckTimeout(buf, &len, 2000, &from))
    {
      Serial.print("Got Response From : 0x");
      Serial.print(from, HEX);
      Serial.print(": ");
      Serial.println((char*)buf);
    }
    else
    {

    }
 //   digitalWrite(4, LOW);
   SPI.end();

   digitalWrite(4, LOW);    //  deselet SD Card SPI
   digitalWrite(RFM95_CS,HIGH);    //  SELECT (low) LoRa SPI
   SPI.begin();

 if (!myFile.open("mrinmoy.txt", O_READ))
  {
    sd.errorHalt("opening test.txt for read failed");
  }

  Serial.println("mrinmoy.txt:");
  char ch;
  String str;
  int i=0;
  uint8_t sd_data[50];

  while (myFile.available()>0)
  {
    ch= myFile.read();
    str+=ch;
  }

  String str2=str;
  Serial.println(str2);
  Serial.println(str2.length());

  myFile.close();
  SPI.end();

  delay(500);
}

use this trick ... your system will work perfectly ...


Controlling JX PDI-6221MG Digital Servo with Arduino So, I naively bought two of these JX PDI-6221MG Digital Servos thought they would work with the Arduino straight out of the box, just like MG996R did, for instance, but it seems they won't. However, I hear some clicking noise when the motor is connected, tho.

These are the Servo specs:

Dead band: 2μs
Working frequence: 1520μs / 330hz
Operating Speed (4.8V): 0.18 sec/60°
Operating Speed (6V): 0.16 sec/60°
Stall Torque (4.8V): 17.25 kg/cm
Stall Torque (6V):  20.32 kg/cm
Dimensions: 40.5X20.2X38mm
Weight:  62 g
Connector Wire Length: JR  265 mm
Bearing: 2BB

Manufacturer site: http://www.jx-servo.com/English/Product/49513727.html

Additionally, I used 5V 2.4A power input alongside with the Arduino Nano running just some sample code:

#include <Servo.h>

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() {
  myservo.attach(3);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Wiring:

I tested the same configuration with MG996R and SG90 and it worked. So what am I missing here?

I managed to get servos running with 6 V and 3 A powered from lab power supply (GOPHERT CPS-1620 0-16V 0-20A). I guess, at the end, it was power supply which was crucial.


Integrating Java program with arduino mega is it possible? I have just written a java algorithm to get a chess move when a chess move is inputted in SAN notation the algorithm used : Monte Carlo. Is it possible to integrate this program with an Arduino mega and How?

My mega will be getting inputs from a sensory board and I want to send these inputs to the java program without using any additional board.

Note:
By integrate I mean that the Java program should run in the Arduino mega itself

Can anyone suggest a solution?

There is a project called uJ by Dmitry Grinberg that enables you to do that, somehow. It has been tested on AVR devices too, not your particular one however. Knowing AVRs, that shouldn't be a stopper at all.

That said, I don't think it's a very good idea. The overhead of the JVM may only let you handle some 'slow' signals, unless you heavily rely on peripherals and wit to do stuff. Though in your particular application, that shouldn't be that much of an issue.

Instead of having the trouble of running a JVM and such, you may just as well rewrite the code in C/C++ or whatever, even for increased efficiency. There may also be some Java to C transpilers, I haven't looked, wary of the dragons.

However, if you eventually decide against that and instead choose to talk to the microcontroller over serial or something else, there is the dreadful excellent RxTx library for Java that works pretty fine after all, or the Firmata library.


Programming an AVR using ISP I am trying to program an atmega with arduino sketch using ISP only (mac user).
So I know how to burn a boot loader, and then to program the chip using the TX, RX. But I would like to program it directly using ISP, without a boot loader.
So I am using the UNO as a ISP programmer, and trying without success to program a chip on a PCB:

I upload to the UNO the ArduinoISP sketch
Connect the lines to the target board (target board have atmega328, crystal, capacitors, LED)
Choose the board "Arduino pro or pro mini" in the Arduino IDE.
Choose the programmer- "Arduino as ISP"
At the beginning I tried to upload a boot loader, to see if its going well, it DID boot loaded the chip,so I know the connections are good, and I am set to go.

Now, I am trying to just upload a sketch using the SAME ISP connection, I didn't touch anything(!) , so I opened the blinking example, hit the upload button, and it's just not working (not in sync).

Again, the goal is now to program a chip with ISP directly, without a boot loader. The reason I boot loaded it is to see it's all connected well.

I can't imagine how the exact same configuration can bootload the chip,and later can't upload a sketch directly using the ISP.

What am I missing here? Can't you use the Arduino IDE to upload a sketch directly as an ISP programmer?

You probably used a direct upload button that uses default Arduino programming using RX TX, not the programmer you had selected.
All wirings are perfect that's why you were able to burn the bootloader.
Now you just need to go under Sketch -> Upload Using Programmer.


Speed of reading I2C How long does it take to read I2C?

I'm reading data from I2C sensor through a 20Hz timer interrupt. The interrupt handler only set the readSensorFlag, and I double checked that it happens at 20Hz through putting a Serial print there.

void TIMER2_Interrupt(void) {
  if (NRF_TIMER2->EVENTS_COMPARE[0] != 0) {
        readSensorFlag = true;
        NRF_TIMER2->EVENTS_COMPARE[0] = 0;
      }
    }

Now in the main loop I perform the reading of sensors.

void loop() {
  // Reading data from sensors to a buffer
  if (readSensorFlag) {
    readSensorFlag = false;

    if (bufferCounter < BUFLEN - 2*SAMPLESIZEINCHAR - 1) {
      epoch = millis();
      proximity = vcnl.readProximity();
      ambientLight = vcnl.readAmbient();

The strange this is that: if I set proximity and ambient light to be some constant and not reading from I2C, then the recorded sampling frequency is 20Hz:

  1988,    7,   10
  2038,    8,   10
  2088,    9,   10
  2188,    1,   10
  2238,    2,   10
  2288,    3,   10

If I revert back reading I2C code (second column is data from sensor), then frequency is only 8Hz!!!

 17637,    8,   33
 17763,    9,   33
 17937,    1,   34
 18067,    2,   35
 18194,    3,   34
 18320,    4,   34

How could reading I2C block the timer interrupt? And how could it be so slow? (I've tried a similar sensor before, and could reach 100Hz with that).

Let's take a look at a typical function for reading this sensor. This is from the Adafruit_VCNL4010 library and is for reading the proximity:

uint16_t  Adafruit_VCNL4010::readProximity(void) {
  uint8_t i = read8(VCNL4010_INTSTAT);
  i &= ~0x80;
  write8(VCNL4010_INTSTAT, i);

  write8(VCNL4010_COMMAND, VCNL4010_MEASUREPROXIMITY);
  while (1) {
    //Serial.println(read8(VCNL4010_INTSTAT), HEX);
    uint8_t result = read8(VCNL4010_COMMAND);
    //Serial.print("Ready = 0x"); Serial.println(result, HEX);
    if (result & VCNL4010_PROXIMITYREADY) {
      return read16(VCNL4010_PROXIMITYDATA);
    }
    delay(1);
  }
}

So let's tot up all the I2C transactions in that one function:

read8
write8
write8
{repeated
    read8
    [read16]
    delay(1)
}

So in a best case scenario, assuming it's in a "ready" state, that's the minimum number of transactions, and the delay doesn't occur.  So what is in each of those transactions?

read8:

Begin the transaction, write the address, end transaction, delay 170µs, begin request, read 1 byte, end transaction.  Total 4 bytes plus 170µs

write8:

Begin transaction, write address, write data. Total 3 bytes.

read16:

Begin the transaction, write the address, end transaction, begin request, read 2 bytes, end transaction.  Total 5 bytes (I notice this one has no delay...?)

So now we can see a best case scenario total of bytes transferred:

4 read8 *
3 write8
3 write8
{repeated
    4 read8 *
    5 [read16]
    delay(1)
}

4+3+3+4+5 = 19 bytes, plus 2x170µs delay.

The default clock speed for I2C on the Arduino is 100kHz. We have 19 bytes, plus start/stop/ack bits. So 19 * 8 for the data bytes (152 bits) plus 19 ACK bits (171 bits) and 5 * start + 5 * stop. That's 181 bits in total.

181 bits, at 100kHz, takes 1.81ms to transfer. Add to that the 2*170µs delay, and we are up to a best case scenario of 2.15ms transfer.

Double that up for reading the ambient light as well, and we're up to 4.3ms transfer. That's a theoretical absolute maximum of about 230Hz readings.

Remember: that's a best case scenario.  If the sensor isn't ready to return a reading at the time that there will immediately be a 1ms delay imposed and the number of transactions will increase.

So why would it not be ready to send a reading? The simplest explanation is that it's not set to a suitable sampling rate.

The library doesn't appear to change the sampling rate for the proximity from the default 1.95 samples per second, nor the ambient light sampling rate from the default of 2 samples per second - so unless you are using a different library, or manually changing these settings through your own Wire calls, even at a reduced triggering speed you'll not be getting anywhere near the kind of information you are after.

The fastest you can get for ambient light sampling is 10 samples per second. Proximity caps out at a more respectable 250 samples per second. But only if you tell it to...


Differential voltage measurement using Arduino I have a electrolysis cell in which the anode is hanging using a Structure in a electrolyte. The cathode is at the bottom of the cell with electrolyte above it and anode being dipped into this electrolyte (not completely, a portion of the anode is dipped). The cell operates at 7  volts DC and 90000 amperes of current flowing through it. This is a typical electrolysis process of producing aluminium from alumina powder in a aluminium smelter. The cell is called a pot.
Now the question is I need to measure a potential drop on the anode rod. We usually take a meter to measure the potential drop on the anode rod and typically the reading are in millivolts. As the readings are in millivolts, it just indicates the drop in rod voltage due to resistance of rod. Now can I measure this millivolts drop using Arduino provided the voltage at one point of anode is 5 volts with respect to ground and the voltage at the other point is 4.95 volts with respect to ground, however the difference between these voltages is 0.5 volts and this is voltage I need to measure using Arduino and some arrangements as add on to it. How can I do this?
Can anyone help.
If you want more details, please comment. I will also provide more details.
So far I have done is tried measuring 1.5 volts on a pencil cell using Arduino by connecting A0 analog pin on Arduino to positive directly to the positive of 1.5 volts battery and ground of Arduino to the negative of Arduino.
Can I do the same for this millivolts measurements? I understand that the ground of Arduino and the 2nd point of anode measurement will not be at same potential, so shouldn't be connected together. I am scared to burn my board, so didn't try practically and wanted to get some opinion.

As you do it with the multimeter: connecting ground to the lower potential (4.95 Volts in your example) and the volt probe to the higher potential (in your case 5.0 V), you can also connect the Arduino between the two potentials: Arduino GND to the lower (!) potential and A0, A1, ... or A7 to the higher (!) potential.
As long as you use the correct polarisation and the difference between the potentials is less than VCC of the ADC (5V Arduino ADCs) you should be save.
The resolution of the Arduino might be a problem. I don't know what resolution you need; 5V divided by 1024 is about 5 mV per step.
You might want to provide a reference Voltage at Vin of -let's say- 1 Volt if you need a better resolution. That would improve the resolution to about 1 mV per step. But then the meassured voltage must no exceed the 1 Volt reference voltage.
EDIT (Gerben's comment)
You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))
And please let me give you a security advice: If the resistence in any part of your meassuring setup is significantly lower than the resistance between the messuring points (e.g you shorten the probe wires), then there is a chance that 90000 A running through this setup. That could burn away your hand, arm or even your life. Amperes kill; not Voltage. I've seen a wrench that was vaporized (ok, melted, ok glowing ;-) ) in a second, when it had fallen between the poles of a car battery (12 V; 300 Amps). An you operate with 90000 Amps. !


CMDmessenger library I am trying to use the CMDmessanger library on my Arduino uno, and am facing an issue.

My issue starts right from the ArduinoController.ino example.

When i send the frequency command

3,1;

The led starts blinking correctly, once per second.

But when I send a wrong command (basically a command without an argument)

3;

The led just stops blinking. The state of the led depends on which state it was in when I sent the command.

I realised that, when I send the wrongly formatted command, it takes the frequency as 0.

Is there any method by which I can make sure that the command is received in the right format, before it is executed? Ideally I would love it if there is a method to know how many arguments were received, and I could call the readBoolArg, or other equivalent functions to retrieve the argument data.

I am planning on using this library for quite a few projects, and I don't want to be in a situation where things went wrong because there was not formatting check.

Thanks in advance.

The example code uses cmdMessenger.readFloatArg(); (source) to read an argument.

void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();
  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

That function will set ArgOk to false if there was no next argument.

float CmdMessenger::readFloatArg()
{
    if (next()) {
        dumped = true;
        ArgOk = true;
        //return atof(current);
        return strtod(current, NULL);
    }
    ArgOk = false;
    return 0;
}

Thus you should try to use public function

bool isArgOk();

/**
 * Returns if the latest argument is well formed.
 */
bool CmdMessenger::isArgOk()
{
    return ArgOk;
}

of the CmdMessenger object (which will return ArgOk) to check if the read argument was okay. You could e.g. modify the code as follows

void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();

  //Did we just read garbage because the argument wasn't there?
  if(!cmdMessenger.isArgOk()) {
      //Using Serial might be a bad idea because that cmdMessanger operates on the same Serial stream.. but you get the idea.
      Serial.println("You didn't supply a correct argument! Error.");
      return; //goodbye
  }

  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}


Push to 2D array (log) but last value pushed is everywhere I have this simple that is supposed to keep a log for me with a fixed number of entries. When I add to the log the oldest replaced is by the second oldest etc and the new entry added. Except when I add another entry both that and the one before have the same value (My C isn't any good, I'm more a ruby and lua guy).

What am I doing wrong here?

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

#define log_size 5
#define line_height 12
char *log_lines[log_size] = {"Hello", "World"};

void addToLog(char *text) {
  for(int i = log_size - 1; i > 0; i--) {
    log_lines[i] = log_lines[i-1];
  }
  log_lines[0] = text;
}

void printLog() {
  for(int i = 0; i < log_size; i++) {
    Serial.print(i);
    Serial.print(" ");
    Serial.println(log_lines[i]);
  }
}

void loop(void)
{
  char msg[20];
  sprintf(msg, "%d", millis());
  addToLog(msg);
  printLog();
  delay(1000);
}

The output after the first addToLog is

0 1000
1 Hello
2 World

second addToLog is

0 2001
1 2001
2 Hello
3 World

It is easy - in your log you store POINTERS to strings.

And you then create variable on the stack (ouch) and put its address to the log.

Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log_lines[0] points to UNALLOCATED place (where the variable msg once was).

Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log_lines[0] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.

Then you overwrite the variable msg with a new value, so the log_lines[0] point to that new value.

Then you move the content of log_lines up, so the log_lines[1] now points to the variable msg (and its NEW value) as well as log_lines[0].

Then you assign log_lines[0] with address of variable msg (which it accidetally already contains)

Then you wonder, why variable msg accesed via log_lines[1] is exactly same as the (same) variable msg accesed vial log_lines[0] and why it contains the last (NEW) value, which you assigned into it.

Some of possible solutions are:

1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate   last log_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.

2) allocate log_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log_line[0]

3) keep static index of last used log_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)


Strange adding behaviour I have an Arduino Nano and was adding up some values 2^i from 0..7:

void setup() {
  Serial.begin(9600);
  int i,k;
  k = 0;
  for (i=0;i<8;i++){
     k += pow(2, i);
     Serial.println(k);
  }
}

Those numbers should sum up to 255, but that's the output:

1
3
6
13
28
59
122
249

Is my Arduino not working or what can be the reason for this behaviour?

No, there is nothing "wrong" there. In fact it's the expected results.

The problem here is that pow() returns a float, and some numbers just can't be represented with floating point. When that floating point value is converted to an integer it truncates the decimal portion leaving you with the wrong integer value.

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

    int t = 0;
    for (int i = 0; i < 8; i++) {
        float f = pow(2, i);
        int d = f;
        t += f;
        Serial.print("2^");
        Serial.print(i);
        Serial.print(": float = ");
        Serial.print(f, 10);
        Serial.print(" int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

2^0: float = 1.0000000000 int = 1 total = 1
2^1: float = 2.0000000000 int = 2 total = 3
2^2: float = 3.9999995231 int = 3 total = 6
2^3: float = 7.9999980926 int = 7 total = 13
2^4: float = 15.9999961853 int = 15 total = 28
2^5: float = 31.9999885559 int = 31 total = 59
2^6: float = 63.9999771118 int = 63 total = 122
2^7: float = 127.9999542236 int = 127 total = 249

Instead you should use bit-shifting to perform the same operation on an integer:

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

    int t = 0;
    for (int i = 0; i < 8; i++) {
        int d = 1 << i;
        t += d;
        Serial.print("1<<");
        Serial.print(i);
        Serial.print(": int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

1<<0: int = 1 total = 1
1<<1: int = 2 total = 3
1<<2: int = 4 total = 7
1<<3: int = 8 total = 15
1<<4: int = 16 total = 31
1<<5: int = 32 total = 63
1<<6: int = 64 total = 127
1<<7: int = 128 total = 255


Arduino UNO - analogRead() returning mixed results I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.

I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:

int ledPin=9;
int inPin=A3;
long int in=0;
float V_in=0;
int val;

void setup() {
  analogReference(DEFAULT);
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT);
  Serial.begin(9600);
  }

  void loop() {
    if (Serial.available() > 0) {
      val = Serial.parseInt();

      if (val>=0 && val<=155) {
        analogWrite(ledPin, val);
        //Serial.println(val);

        for (int i=0; i<10; i++) {
          val+=5;
          analogWrite(ledPin, val);
          //Serial.println(val);

          delay(1000);
          in = analogRead(inPin);
          V_in=float(5.0)*(float(in)/float(1023));
          Serial.println(V_in);
          delay(1000);
          }

        }
        else {
          Serial.println("Dio è morto.");
          }
      }
    }

The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.

What am I doing wrong?

I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.

This is an output example:

The analogWrite function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.

So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

  I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

Reference

Arduino functions reference:

Reference > Language > Functions > Analog io > Analogwrite


How to use an Arduino Speaker module with DFPlayer Mini? I've bought an Arduino speaker module. How should I connect the module, if I want to use it with DFPlayer Mini? The problem is that the speaker module has 3 pins: GND, VCC, and IN; though the DFPlayer Mini has 2 pins for connecting a speaker: SPEAKER + and SPEAKER -.

The DFPlayer already has an amplifier on it, so you can connect the speaker directly.
You can just leave out the board you bought from AliExpress, and only use the speaker.


Stepper Motor is not working with A4988 board So, I have been following this tutorial on how to run a stepper motor with Arduino using an A4988 Stepper Driver. This is the tutorial: How To Control a Stepper Motor with A4988 Driver and Arduino. I have connected the wires according to this schematic:

I have connected the wires exactly like this and triple-checked it! The problem is the stepper motor is not turning. This is the code(it's simple):

// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}

void loop() {
  digitalWrithe(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(500); // One second delay
}

One weird thing:

  When I connect the sleep and reset pin on the A4988 board the stepper motor starts turning. Like why?

NOTE: I replaced the MEGA with a UNO because at the moment I'm just testing.

You have to connect the sleep and reset pin together. I assume that you took this schema on how to mechatronics. In his video you see that the sleep and reset pins are connected. I don't know why but it has to be like that.
Then, if the motor vibrates or click, it may be one of these problems:

You didn't connect the motor properly
The current is set too low on the board (screw on the motor driver)
The battery (Vmot) isn't powerful enough

If it's not one of those problems, the A4988 chip might have an issue. I have a similar problem where it turn in one direction and only when the pwm signal goes throught the direction pin  instead of the step pin.


How to call more than 10 different functions based on serial input? I'm looking to basically call functions based on the serial ID I assign to it. For example, if I want to call function A I would type on the serial A and if I want to call function B then I would type B.

Now I have taken a look at some arduino.cc ASCII and other lookup tables but I'm still not getting my results. YES I can indeed make up serial calls 1 through 9 using char datatype but as you can see I'm only limited to 9 function calls and so this is where I'm looking for tips. How can I expand this serial ID as I'm calling it?

char id;
int led = 6; // the PWM pin the LED is attached to

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

void loop() {
  id = Serial.read();
  /*
    will only read the 1st bit on the buffer so
    no 10s...90s because the whole char so we
    need to use Strings datatype somehow but
    the thing is that the Serial.Read func only
    reads the first byte. R&D?
  */
  if (id == '1') {
    digitalWrite(led, HIGH);
  } else if (id == '2') {
    digitalWrite(led, LOW);
  }
}

So in my above example I'm using char to communicate. I know there are other datatypes but not sure which is the best suited for the 100's of functions I would like to call via terminal.

I thought about using the alphabet A-Z as well as a-z to double the function calls but I would like to come up with something a bit more formal rather than single numbers or single letters (char).

First, you could use a string for the commands. You just need to ensure there is some special char to mark the end of a command - like the newline char. Read the input from the port one char at a time, building the string as you go:

char buffer[256];
uint16_t buffer_index = 0;
void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;   // Append EOS
      // Complete message - do something
      buffer_index = 0;   // Reset, ready for next message
    }
    else {
      // Append char to end of buffer
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

There are plenty of examples like this on this site.

Next, I don't recommend using an if statement with a hundred or more conditions. Instead, you can store pointers to each function in an array:

// Use a typedef to simplfy
typedef void (*function_type)(); // A function with no params and no return, change as needed
// Fixed array size
const int max_functions = 200;
// Create an array of 200 function pointers
function_type all_functions[max_functions] = {0};

So to call function #11:

all_functions[10]();

Now you just need a way to marry the function pointers to a name. A hash table could work here. A hash function converts a string to a number. There are lots of examples on the web. Here's one:

uint16_t djb2_hash(const char *str)
{
    unsigned long hash = 5381;
    int c;

    while (0 != (c = *str++)) {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }

    // Note: we use the mod operator to make sure value
    // is less than array size
    return hash % max_functions;
}

Create two functions, one to add a function and one to retreive:

bool add_function(const char *name, function_type f)
{
  // Convert name to number
  uint16_t index = djb2_hash(name);  //  0 <= index <= max_functions
  if (NULL != all_functions[index]) {
    // There is already a function stored at this index
    Serial.print("Adding ");
    Serial.print(name);
    Serial.print("failed. index = ");
    Serial.println(index);
    return false;
  }
  else {
    // Store the function in the array
    all_functions[index] = f;
    return true;
  }
}
bool run_function(const char *name)
{
  uint16_t index = djb2_hash(name);
  if (NULL == all_functions[index]) {
    // Name not found
    return false;
  }
  else {
    // Call the function
    all_functions[index]();
    return true;
  }
}

Last, create some functions and add to hash table:

void f1() {Serial.println("F1");}
void f2() {Serial.println("F2");}
void f3() {Serial.println("F3");}

void setup() {
  Serial.begin(9600);
  add_function("F1", f1);
  add_function("F2", f2);
  add_function("F3", f3);
}

All that's left is to modify loop() to call the functions when a complete message is received.

void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;
      run_function(buffer);
      buffer_index = 0;
    }
    else {
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

If you enter "F1", "F2", or "F3" in the serial monitor, those functions should execute. Just make sure you change the serial monitor to append a newline.

Some notes: the hash function may not create a unique id for each string. You need to handle this situation. Also, the names are case sensitive. If you don't want that, convert everything to all upper case or all lower.


ESP8266 using EEPROM to store a value of 100,000 I'm using Wemos mini in my project. I wish to store a Boolean value in cell #0, which changes every boot.

Since writing to EEPROM is limited to roughly 100,000 cycles - I want to store in cell #1 the amount of writing cycles done so far, so when reaching 100,000 , value will be stored in cell#2 and writing cycles will be stored in cell#3 and so on.

Reading and writing using #include <EEPROM.h> is done as needed, but since each cell can store a byte, it can only reach 255.

My question is how to store a value of 10^6 (except of convert it to a*2^0 + b*2^1 + c*2^2 + d*2^3....).

Guy

EDIT1

Part or relevant code:

void setup() {
        Serial.begin(9600);
        Serial.println("BEGIN:");
        if (HARD_REBOOT) {
                EEPROM.begin(1024);
        }
        if (HARD_REBOOT) {
                EEPROM.write(0,100000);
                EEPROM.commit();
                delay(50);
                Serial.print("value in flash: ");
                Serial.println(EEPROM.read(0));
        }
}

and its output:

Ȥl⸮⸮BGS[⸮<b8ɗ⸮BEGIN:
22:40:58.732 -> value in flash: 160

The esp doesn't have an eeprom, but emulates it in its flash. Therefore 100.000 cylces will not apply, it's more like 10.000 cycles for flash.

The easiest way to prepare a datatype to be stored as bytes is to use union like follows:

union Converter{
  uint32_t ui32;
  byte eeprom_bytes[4];
}convert;

void convert_for_eeprom (uint32_t your_number) {
  convert.ui32=your_number;
  // convert.eeprom_bytes contains the 4-byte represenstation of your number, write those to eeprom
}

uint32_t convert_from_eeprom () {
  // read four bytes from eeprom and assign those to convert.eeprom_bytes
  return convert.ui32;
}

Note that this isn't a type conversion and the value of convert.eeprom_bytes are not meant to be processed, as they are simply interpreted as if they were a four-byte array, indeed those bytes contain "dumb" values. This way you can "convert" any datatype for byte-wise storage and read-back respectively.

Another option to convert a 32 bit integer to 4 bytes is by using bit-wise operations:

uint32_t your_number=100000;
byte b1=your_number;
byte b2=your_number>>8;
byte b3=your_number>>16;
byte b4=your_number>>24;

But this only makes sense for integers and I suggest taking a look at union.


How to use d0 and d1 pins of arduino uno (Others) as a digital output when I don't want to use Serial I have searched this topic almost everywhere also got different results that couldn't satisfy me
My new project is a 4x4 LED cube
Of which
Will contain 4 Rows and each Row will contain 16 LEDs
So, I need to use all the digital pins 0-15 as digital output.
And other pins 16-20 for grounding.
But the problem is, this project needs d0 and d1 pin to be connected as a digital output pin. (Not Serial communication)
In some places I have seen that Experts saying

If you want to use Serial communication, then you can't use them.

You can't use it while your arduino is connected to PC.

You Can't do this ,as this may harm the device

You must turn off serial connection first.

OK, reading this, I got confused, I don't need to use any serial connection (console and others) in this LED cube project so I tried to turn off serial connection by not writing the code below.
Serial.begin(9600);

So, will that free those d0 and d1 pins as digital for me ? Or USB connection is also considered as a serial connection?
So, how can I do it? And will doing it really harm my board?

If you don't use the serial port, pins 0 and 1 are regular I/O pins.
It's just as simple as that.

If you want to use Serial communication, then you can't use them.

Correct.

You can't use it while your arduino is connected to PC.

Wrong. You can keep the USB cable connected as a power supply. You will
not be able to use it for communication though.

You Can't do this, as this may harm the device

What is “this”? The device can be harmed if you drive too much current
to/from an I/O pin, irrespective of whether it's a pin that could be
used for serial communication.

You must turn off serial connection first.

Only if you did turn it on before. If you never enable Serial, you
don't have to do anything more.


How to connect to pins when using I2C LCD shield? How are pins used with this shield? The tutorial says that the header pins are inserted into the Arduino but the guide says they are not used for signals. Is there any way of using the other pins?

Update:

What it means is although all pins from the Arduino are connected only A4, A5 5V and Gnd are actually used by the shield.  I think that these 4 pins are shared with other shields and all the rest of the pins are available for shields to either share or use exclusively.

So, if you have this shield and an Ethernet shield, which needs exclusive access to pins d7, d8 and d9 then you would be to use both shields at the same time.


Is the DHT.h library compatible with ESP8266 Arduino IDE compiler? I'm using the following 'compiler' to program my ESP8266-01 direct with Arduino IDE:

https://github.com/esp8266/Arduino

and I'm trying to read the temperature and humidity with the following library:

https://github.com/adafruit/DHT-sensor-library

since the DHT library was developed to be used on an Arduino board, should I be able to run it on the ESP8266?

As far as I see, the DHT sensor library does bit-banging, which is kind of expected given the ad-hoc nature of the protocol that DHT type of sensors utilize. It should be compatible, as the library doesn't use any Atmel-specific features of the MCU.


mqtt library which support softwareSerial on arduino uno with ESP8266 I am using ESP8266 and Arduino with SoftwareSerial. My requirement is to use MQTT protocol with it. So I am using an MQTT library named pubSubClient but the problem is it doesn't support SoftwareSerial. Could anyone tell me how can I use MQTT protocol with it?

#include
#include
SoftwareSerial esp(2, 3); // RX, TX
PubSubClient client(esp);

The error I get is: no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)

In order to use the ESP8266 WiFi module with pubSubCient, you need a library that interfaces with the module with the usual AT commands, while presenting an Arduino Client interface on the surface. A while back, I found this library after a great deal of searching. It supports SoftwareSerial as well as HardwareSerial objects. Its ESP8266 interface provides the standard Client methods of write(), read(), connected(), etc. There are some issues, of course, but its the best I've found so far. You can pass the created Client object to the pubSubClient constructor and you're good to go.


Is there such a thing as an "Always" loop? I seem to remember somewhere somebody making an "Always" loop between Setup() and Loop().

But I can't find any documentation on it. Does such a thing exist, or am I imagining it?

There's nothing officially called an "always" loops as such. However, you can make a loop which goes on forever like this:

while (true)
{
    // this bit repeats forever
}

A while loop checks the condition before every iteration of the main body. If it detects that the condition equals boolean false then it will stop the loop and move on to the next bit of code.

Normally, the condition would be some kind of expression, like (x < 10). However, in the example above, the condition is hard-coded as true, meaning it will never be false so it will never stop.


Python script to toggle LED's I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.

Should be pretty basic but I cant seem to get this working.

I have already botched my code trying to get this running:

the jist of my python script is

import serial
import os
import time

os.system('clear')

ser = serial.Serial('/dev/cu.usbmodem1431', 9600)

while True:
    led = input("Which LED do you wish to operate? (press x to quit): ")

    if led >= '0' and led <= '7':
        print("Operating LED # %s" % led)
        ser.write(str.encode(led)) # sends the choice of led to arduino'
        on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")

        if on_or_off == '0':
            #send command to arduino to turn off the selected LED
            print("Command sent to arduino to turn OFF LED %s" % led)
            ser.write(str.encode(on_or_off))
        elif on_or_off == '1':
            #send command to arduino to turn on the selected LED
            print("Command sent to arduino to turn ON LED %s" % led)
            ser.write(str.encode(on_or_off))
        else:
            print("Please enter 0 or 1 to operate the LED. ")

    elif led == 'x':
        ser.close()
        break
    else:
        continue

For some reason Arduino is only dealing with the first input...

HEre is my loop code on the arduino

void loop() {
  if(Serial.available() > 0){
    led = Serial.read(); // from python script the led to operate
    led = led - '0';
    if(led >= '0' && led <= '7'){
      if(Serial.available() > 0){
        ledState = Serial.read(); // expects the led state next
        ledState = ledState - '0';
        if(ledState == '0'){
          shiftWrite(led,LOW);
        }else if(ledState == '1'){
          shiftWrite(led,HIGH);
        }
      }
    }
  }
}

shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister

update:

I tried the state machine suggestion and it didnt work...

  void loop() {
  while(Serial.available()){
    led = Serial.read();
    led = led - '0';
    if(led>= 0 && led <= 7){
      state = 1; //We've received the LED # go to state 1
      Serial.println(led);
      Serial.println(state);
      Serial.println(ledState);
      continue;
    }
    if(state == 1){
      ledState = Serial.read();
      ledState = ledState - '0';
      if(ledState == '0'){
        shiftWrite(led,LOW);
      }else if(ledState == '1'){
        shiftWrite(led,HIGH);
      }
      state = 0; //Ended the operation return to state 0
    }
  }
}

With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1

This is my output on the serial monitor:

4
1
0
1
1
0

Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...

You're assuming that the microcontroller is going to wait until you choose LED state, which is wrong. Try this:

int state = 0;
int led;
int ledState;

void loop() {
  while (Serial.available())
  {
    if (state == 0)
    {
      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1; // Here we have got the LED number, go to state 1
        continue;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          shiftWrite(led,LOW);
        }
        else if(ledState == 1)
        {
          shiftWrite(led,HIGH);
        }
        state = 0; // Here we ended the operation, return back to state 0
    }
  }

}

You need what we call a state machine, here I use state=0 for the state corresponding to choosing LED number, state=1 is for the state that waits for the operation ON/OFF.


How to send data from Arduino Uno with SIM900 GPRS to Firebase I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from here. Here is some code that I've tried:

AT
OK
AT+CREG?
+CREG: 0,1

OK
AT+CGATT?
+CGATT: 1

OK
AT+CIPSTATUS
OK

STATE: IP INITIAL
AT+CIPMUX=0
OK
AT+CSTT="att.mvno","",""
OK
AT+CIICR
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
OK
CONNECT OK

and

AT+CIPSHUT
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
OK
CONNECT OK

If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret?
Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. This site explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.


Accidentally plugged in Arduino Uno before installing software, now it's not recognized by Windows 10, only powered by usb port Just got a new Arduino Uno, accidentally plugged it in before installing the IDE and windows installed its drivers and had it under ports as a generic device on COM3 (it wasn't named Arduino Uno on device manager).

When I installed the IDE, I couldn't upload sketches to the board because it wasn't recognized. So I uninstalled the device from device manager and also the IDE. I pressed the reset button on the Uno, restarted my PC, reinstalled the IDE, then plugged in the Uno. Since then however, the device isn't read by Windows at all; device manager doesn't show it anywhere, nor does it even refresh when plugged in.

I tried this restarting/reinstalling process multiple times, it's also not a cable issue because I checked for that as well. The power LED is still on, and the pin 13 LED is blinking, but the Arduino isn't being recognized.

I've also tried using the Hardware Install Wizard, but that gives me

  This Device Cannot Start (Code 10)

I've been trying to run this for a while now.

You do not need to install drivers in Windows 10 (unless you have a CH340G based Chinese clone, in which case it wouldn't have detected before installing the drivers).

Windows 10 has its own CDC/ACM drivers built in - something every other operating system has had for years and Windows has only just caught up with them. That is why it detected COM3 fine before.

It should have worked fine without installing drivers. It may have been the IDE with the wrong port selected or something else interfering with the port that was stopping you using it.

Uninstall the Arduino drivers and revert to using the Windows built-in ones and work on diagnosing why it wasn't working with those.


Does millis() work inside a function? So I know that millis() doesn't work how it's suppose to if you use it in an interrupt but lets say we have a code that looks like below, will millis() work properly or how it behaves in an interrupt? Do I need to use the delay() instead of millis() when I'm outside of void loop() ?

To clarify, I understand how millis() behaves in an interrupt and why delay() doesn't work in an interrupt.

const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;

void setup() {
 pinMode(ledPin, OUTPUT);
}
void loop(){
blink();
}
void blink(){
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Millis is driven by an interrupt. The reason it doesn't "work" from inside an interrupt is that you can't have two interrupts running at the same time. So when your interrupt is running the interrupt that makes millis count can't run.

Millis does work in an interrupt as long as all you want is to record a single point in time. If you do anything that relies on millis changing within the lifetime of the interrupt it will break. That is why delay is bad in interrupts.

So from that you can see that it's only when in an interrupt that things can go awry. Everywhere else, as long as interrupts are enabled, both millis and delay work fine.

After all, loop is just a function called by main, and main is just a function called by _startup... Etc...


counting ADC samples ( using a light sensor) i am new to micro controller programming and in need of help. i have managed to interface a light sensor to a micro controller (atmega 32a) and can read the value i.e. (1023) as per the set prescale. however i intended to achieve a single decimal value as the result. in this case (1) every time the sensor is exposed to light and successively perform an incremented tally as lights go on and off around the sensor ( i am using a LDR for this). i am currently having problem getting my micro controller to do this. i have searched all over the internet but no seems to assist me on this... please any insight on how to achieve this will be much appreciated. i know its a simple thing,HELP :(

basically just a means of making my micro controller count the number of times light falls on the LDR

There are 2 common light sensor types.  The photo diode and the photo resistor.  The first produces small amounts of current and operates fast.  The second changes resistance and operates (very) slowly.

There is a good stack exchange response here for how to use a photo diode.  Often the photo diode output is small and additional hardware is used to amplify the signal.  As discussed in this stack exchange response.

The photo resistor or cadmium sulphide cell or Light Dependent Resistor is much easier to interface with an Arduino.  However, the response time is very slow.  On the order of hundreds of milliseconds to seconds.  This is acceptable when controlling street lights.  But is not acceptable in applications requiring fast light detectors such as those used for communication.

Before going on, verify which device you are using in your design.

Generally, Arduinos contain a 10 bit ADC.  This results in values from 0 to 210−1 or 0 to 1023.  Should you consistently get a reading at or near the limits of the ADC check your hardware.  Do this by measuring the voltage at the input of the ADC pin used.  Do this under varying conditions to verify the hardware is operating as expected.

A good software design uses hysteresis to convert an analog value to a logical 1 or 0.  Here is a stack exchange response about using hysteresis with Arduinos.


Arduino Mega not flashable with XBee PRO S2B I have an Arduino Mega 2560 with a libelium XBee Shield. If I have an XBee S2 mounted on it and set the two jumpers to the USB setting or remove them, I am able to flash a program onto my Arduino.

However, when I'm mounting one of my XBee PRO S2B (I have three of them available and all behave the same) on the Arduino, no matter how I set the jumpers, it is not possible to flash anything on it. I always see avrdude: stk500v2_getsync(): timeout communicating with programmer in the Arduino IDE.

Is the XBee PRO S2B incompatible with the Arduino or what might be the issue? I also tried to add an external power source additionally to the USB, but it didn't help either.

Update

After some more experimenting, I found out new details. I tried to disconnect each pin of the shield individually. While doing it, I discovered that disconnecting the reset pin from the arduino makes it possible to flash it - take a look at the XBee shield schematic, it's pin 5 from the ICSP connector; Photo:

I used a multimeter and discovered that the XBee PRO S2B CTS / DIO7 port is high, while the one from the XBee S2 is low, and so constantly resetting the arduino. I mounted the XBee PRO S2B onto the Sparkfun XBee Explorer USB and opened a serial port with PuTTY.
In contrast to the S2, the PRO S2B provides a menu with several options:

B-Bypass Mode
F-Update App
T-Timeout
V-BL Version
A-App Version
R-Reset
>

As soon as I type B, the CTS port goes low, and would prevent the arduino from resetting. Also this mode is needed to detect the module via XCTU. However, with an unmodified arduino, I wouldn't have a chance to send this letter, since the XBee is constantly resetting it. What is this menu, can it be disabled somehow?

I don't have a PRO to play with, but I just looked at the datasheet and it appears that it SHOULD timeout after 60 seconds

  If no serial transaction is initiated within a 60 second timeout period, the bootloader times out and returns to
  the menu. If the upload is interrupted with a power cycle or reset event, the EM250 will detect an invalid
  application image and enter bootloader mode.  (page 139)

Also, it seems that it takes a particular set of conditions to get to the bootloader, obviously these conditions are being met:

  XBee modules use a modified version of Ember’s bootloader. This bootloader version supports a custom entry
  mechanism that uses module pins DIN (pin 3), DTR / SLEEP_RQ (pin 9), and RTS (pin 16). To invoke the bootloader,
  do the following:

  Set DTR / SLEEP_RQ low (TTL 0V) and RTS high.
  Send a serial break to the DIN pin and power cycle or reset the module.
  When the module powers up, DTR / SLEEP_RQ and DIN should be low (TTL 0V) and RTS should be high.
  Terminate the serial break and send a carriage return at 115200bps to the module.
  If successful, the module will send the Ember bootloader menu out the DOUT pin at 115200bps.
  Commands can be sent to the bootloader at 115200bps.

  Note: Hardware flow control should be disabled when entering and communicating with the EM250 bootloader.

Perhaps check pins 3, 9 and 16 on boot and see if you can modify their behaviour.


Arduino IDE Board Selection for 32u4 on custom PCB I am using a 32u4 on a custom PCB: 3.3v, 8MHz.

Are there any operational differences between using the Sparkfun ProMicro selection versus the Adafruit ItsyBitsy selection in IDE, since they are both for the 32u4?

There should not be any difference, However you would need to load the ItsyBitsy bootloader instead of the ProMicro Bootloader. Personally, I use the Pro Micro Bootloader on my 32u4 Boards.

The only difference would be in the size of each bootloader, one may be smaller and give you more actual codespace. Other than that there should be no performance difference because your code runs independently of the bootloader.


String to Dynamic Byte array I'm new in Arduino stuck in String to a dynamic byte array.

My String:

String Finalval="6D616320747820636E662031352033300D0A";

Dynamic Byte array:

byte ft[]={0x6D,0x61,0x63,0x20,0x74,0x78,0x20,0x63,0x6E,0x66,0x20,0x31,0x35,0x20,0x33,0x30,0x0D,0x0A};

Common C-string to byte array functions as shown in https://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c work perfectly fine.

Source hex string: 6D616320747820636E662031352033300D0A
Conversion OK buff 0x289 len 18
output byte array:
  00 6d 61 63 20 74 78 20 63 6e 66 20 31 35 20 33 30  mac tx cnf 15 30
  10 0d 0a                                            ..

#include <Arduino.h>

void hexDump (const char *desc, const void *addr, const int len);

bool convert_hexstr_to_bytearray(const char* source, uint8_t* &output,
        size_t& output_len) {
    size_t len = strlen(source);
    //cannot convert non-even string length
    if ((len % 2) != 0) {
        return false;
    }
    //dynamically allocate output buffer
    output_len = len / 2;
    output = (uint8_t*) malloc(output_len);
    const char* curPos = source;
    for (size_t count = 0; count < len; count++) {
        sscanf(curPos, "%2hhx", output + count);
        curPos += 2;
    }
    return true;
}

String Finalval="6D616320747820636E662031352033300D0A";

void setup() {
    Serial.begin(115200);
    Serial.print("Source hex string: ");
    Serial.println(Finalval);
    Serial.flush();

    uint8_t* buffer = nullptr;
    size_t buffer_len = 0;
    if(convert_hexstr_to_bytearray(Finalval.c_str(), buffer, buffer_len)) {
        Serial.println("Conversion OK buff 0x" + String((long)buffer,HEX) + " len " + String(buffer_len));
        hexDump("output byte array", buffer, buffer_len);
    } else {
        Serial.println("Conversion failed\n");
    }

    //free memory
    if(buffer)
        free(buffer);
}

void loop() {
}

void PrintHex8(const uint8_t *data, uint8_t length) // prints 8-bit data in hex
{
     char tmp[length*2+1];
     byte first;
     byte second;
     for (int i=0; i<length; i++) {
           first = (data[i] >> 4) & 0x0f;
           second = data[i] & 0x0f;
           // base for converting single digit numbers to ASCII is 48
           // base for 10-16 to become lower-case characters a-f is 87
           // note: difference is 39
           tmp[i*2] = first+48;
           tmp[i*2+1] = second+48;
           if (first > 9) tmp[i*2] += 39;
           if (second > 9) tmp[i*2+1] += 39;
     }
     tmp[length*2] = 0;
     Serial.print(tmp);
}

void hexDump (const char *desc, const void *addr, const int len) {
    int i;
    unsigned char buff[17];
    const unsigned char *pc = (const unsigned char*)addr;

    // Output description if given.
    if (desc != NULL) {
        Serial.print (desc);
        Serial.println(":");
    }

    if (len == 0) {
        Serial.print("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        Serial.println("  NEGATIVE LENGTH: " + String(len));
        return;
    }

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0) {
                Serial.print ("  ");
                Serial.println((char*)buff);
            }

            // Output the offset.
            Serial.print ("  ");
            PrintHex8((uint8_t*)&i, 1);
        }

        // Now the hex code for the specific character.
        Serial.print(" ");
        PrintHex8(pc + i,1);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        Serial.print ("   ");
        i++;
    }

    // And print the final ASCII bit.
    Serial.print ("  ");
    Serial.println((char*)buff);
}


Forwarding serial output from a Nano to Uno that's used as the ISP I'm trying to program a Nano by using an Uno as the ISP. So far, I've followed along with the example project for getting the Uno running as the ISP on https://www.arduino.cc/en/Tutorial/ArduinoISP.

After a bit of tinkering, it works, but the serial monitor won't work correctly. I'm uploading a super simple program that delays for 500 ms and prints to the log.

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

void loop() {
  Serial.println("test");
  delay(500);
}

I've wired the TX pin on the Nano to the RX pin on the uno. The monitor updates every 500 ms as expected after doing so, but displays ��� instead of the word test. When I tried wiring TX -> TX, the serial monitor does not update. Does anyone have any insight what's missing here?

As Chris Stratton suggests in his comment above:

  You can't really connect an ordinary Arduino's serial pins to both another device and the on-board USB serial converter at the same time.

To solve your serial monitor problem use a separate USB serial converter and connect that to your Arduino Nano.

If you don't have access to a dedicated USB serial converter you could use software serial on the Arduino Nano. This allows you to connect the Arduino Uno Rx pin to the software serial Tx pin. You will also need to program the Arduino Uno with a program that re-transmits the data it receives back out to the PC serial monitor.


How are Arduino's OSH if Atmel AVR is proprietary? I keep reading how Arduinos are "open source", but my understanding of OSH is that all its components must be open source.

Arduino uses an Atmel AVR CPU - but Googling this shows the Atmel is proprietary!?

So I ask: how can Arduino be truly OSH if it's chief component - its Atmel CPU - is proprietary?!?

The components are necessarily going to be proprietary.  There is no feasible way around this.  If you wanted to design a new open source microcontroller from scratch with no proprietary components, it would set you back several billion dollars.  The software used to design integrated circuits costs hundreds of thousands of dollars to license and represents billions of dollars of investment.  Production of the chips themselves takes place in wafer fabs that cost billions of dollars to build, and represent billions of dollars of investment in process technology and semiconductor physics research.  The equipment and process technologies are very closely held trade secrets.  If you are OK with proprietary production, then you can submit GDSII design files (developed with your own open source IC design software) to fabs such as TSMC for production, but the line setup costs will run in the hundreds of thousands of dollars.

Bottom line: you have to draw the line somewhere as to what is acceptable to be 'open' and what is not.  Open source hardware generally means the board-level design files and firmware sources are available, and generally nothing more.

Interestingly, there are many open source CPU designs available.  Sun's OpenSPARC is an open design, you can download the RTL description of the CPU core and modify it.  However, convering RTL to a chip requires IC design software or implementation on a proprietary FPGA with a proprietary development environment.


How to do with fzz file I have a file YunConfig.fzz file for arduino yun for map maker project with ultrasonic sensor.
How can I open or do with that file?
please answer me.

Download and install the open-source, Fritzing CAD software for electronics hobbyist and open the .fzz file with that.

Versions are available for Linux, Mac, and Windows.

Installation instructions are on the downloads page.


straight or 90 deg headers (pins) I just got an RFID module which I want to play with.
it came with two sets of headers (pins), both straight and 90 deg.
The pins are not soldered to the shield and I need to decide which and how to solder...

As they are not designated for any specific use (that implies packacging in a specific direction or other constraints) I was wandering if there are any consideration as to which one should I solder to the circuit? and in what orientation?

straight with long pins on the top of the RFID shield? (i.e.
solder the headers as if they where another component on the
shield?)
straight with long pins below RFID shield?
90 Deg on top of the shied pointing out / in of the shield
90 Deg below the shied facing out / in of the shield

Which of these configurations I am least likely to regret :) ?

I usually use female headers pointing straight up off the board because they accept the most common double-male breadboard wires. The downside is that their mechanical connection to the board is not terribly stable due to the board-end pins being little bitty extensions of the sheet-metal socket inside the header.

Male headers are much more stable, and a handful of male-female breadboard wires will connect them to a breadboard. The downside of going this route is it invites JRobert's Law of Erroneous Selection: whenever you have more than one kind of similar component, the first one you pick will always be the wrong kind.