Razor 9DOF SMD Capacitor replacing I just bought This IMU a while ago, and when I reached the point where I wanna connect it, I noticed that one of the capacitors have been removed by accedint, and since it took too long to check the product, I won't get to replace it or get any refund, so my question, how can I replace that SMD capacitor?
P.S. I have some Ultrasonic sensors might have the same SMD capacitors that I can take off and replace with if anyone can help.

You are on a tough road. I hope someone can give you specifics.  Normally you would able to identify the capacitor from its parts designation, but that board does not have any. So you will have to match the schematic (assuming spark fun provides one) to the board layout to figure out what it is.  The cost of the part is probably over a penny, maybe even 2 cents. In other words, not an issue.

It will require hot air to desolder one from another board and to solder this one on. Someone might be able to do it with a fine tip solder  pencil, but not likely.

Bottom line; find someone who has experience repairing boards, or order another one. Amazon has breakout boards for the 6050 for $6. But I see this one has Serial, and a magnetometer, so it is not quite the same. But depending on what you plan to do with it, it could work.


Which Arduino board to select for designing a Quadcopter? I want to design a Quadcopter. I am a novice and would like to start off with the basic Arduino that can support making a Quadcopter.

Which Arduino board will be good...?

Also, I plan to add Android interface later.

Also, can anybody suggest places in India where Arduino boards are available so I can buy one..?

Thanks!

The right board for you is the board that best fits your design.  Leave the Arduino as a "black box" in your design and don't worry about it.  Once you know what you need from your Arduino board in the way of control interfaces, IO, processing power, etc, you (and we) will be in a better position to choose a suitable board.

Until then you're basically asking "I want to take my driving test. What kind of car should I buy?", which makes absolutely no sense.


Make OTA work with Arduino Uno Wifi I just bought a Arduino Uni Wifi Rev. 2, with the itention of doing over the air uploads to the devices.

By reading the official Gettings started with the Arduino Uno Wifi guide, I thought the process was just to power the devices, connect to the SSID, then browse to it's IP and set it up.

But it seems like this is not the case, and that others have made this same mistake. This Arduino device doesn't create network by default, we have to upload a sketch that connects to our wifi.

So I have two questions.

What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?
How can I get OTA support for my particular board?

What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?

The first Uno WiFi was made in 2016 by arduino.org. It is retired and not available in stores.

  How can I get OTA support for my particular board?

The OTA support for Uno WiFi Rev. 2 is ready or almost ready, but the required additions are not merged in GitHub firmware and library repository even if they wait some months now. It looks like Arduino focuses on something else.


What does "Update of OCR1x at" mean in the WGM table of ATMEGA328? I just finished a reading a couple of online guides on how to use timer registers with pulse width modulation, so I'm still new to its concept.  When I looked in the ATMEGA328 specification sheet, I see this table:

The column that I'm not completely clear on is the "Update of OCR1x at".  I circled row 14 as an example.  If you're operating in mode 14 (ie. setting WGM 13, 12 and 11 to high), then you'll be in Fast PWM.  By setting a value for ICR1, you are effectively setting the TOP value, which will control the period of the pulse waves.  And the overflow flag on the timer will be set when the timer reaches the TOP value.

So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins if COMx bits are set?

So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins...

Yes, that's what it means. To prevent glitches in the PWM output, you frequently do NOT want the PWM waveform to change immediately the instant you update an OCR1A value, for instance, to change the PWM output on output pin A. So, the PWM value you set is double-buffered and only updates the inner buffer used by the output pins once it finishes its current PWM period and reaches the BOTTOM value again, which would be a counter value of 0 in this case. Now, by allowing a previous PWM period to finish before the hardware reads the latest value from the OCR1A/B register (outer buffer) to its inner buffer (which inner buffer actually determines the pin state), you have a nice, clean, glitch-free PWM transition from one value to the next regardless of when you updated the OCR1A or OCR1B output register.


Level detection of 3.3V from 5V arduino A quick question about microcontroller digital level on I/O pins. I have a photo interrupter which is powered at 3.3V which is interfaced to Arduino UNO running at 5V.

For microcontroller to detect high or low level is determined by signal higher than 5V*(2/3) = 3.33V is high and signal lower than 5V*(1/3) is low. What I don't understand is that arduino is able to detect the level change from the photo interrupter. Doesn't the supply on pins have to be greater than (2/3) or Vcc in order for it to detect logic high? The circuit works and I am able to count pulses from the interrupter but I want to know why that works considering the photo interrupt only gets about 3.23V.

Please clarify

You've... misread the datasheet. The '328 input high voltage (VIH) for most pins is 0.6VCC minimum for devices with a 2.4-5.5V supply. This means that a 5V device has a 3V threshold.


Arduino output pin from 5V to 3.3V I just have a question regarding Arduino output-pins and Voltage divider, because I am getting other results than what my calculations are giving me.

I have measured the output-pin (from the Arduino) at 4.74V, according to my caulculations I will have and output voltage of 3.39V, with R1 = 4k ohm and R2 = 10k ohm, but when I use my multimeter to measure I read a voltage of 0.97V.

I have tested with a 9V battery, measured to 8.72V. With the same resistors, the calculations gives me 6.23V as output, when I use my multimeter I can read a output of 6.21 which I consider as ok.

So my question is, why is my output from the Arduino only 0.97V with the voltage divider?

For information: I am using Arduino OSEPP Uno R3 Plus.

Hope someone can give me helpfull information.

***************************************update********************************************

My code:

int echoPin = 7;
int trigPin = 6;

int SignalPin = 10;

void setup(){

  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);

}

void loop(){

  float distanceCentimeters;
  int pulseLenMicroseconds;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(20);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);

  pulseLenMicroseconds = pulseIn(echoPin, HIGH);

  distanceCentimeters = pulseLenMicroseconds / 29.387 / 2;

  if(distanceCentimeters <= 35 && distanceCentimeters >= 10){

      digitalWrite(SignalPin, HIGH);

  } else {

      digitalWrite(SignalPin, LOW);

  }

  delay(400);

}

Image of the setup (not with Raspberry Pi).

Your code does not configured SignalPin as an output, but only trigPin.

As already explained in comments, your observed voltage is due not really to the voltage divider you constructed, but rather one formed by the "weak" internal pull-up resistance and your external resistors.  From your measurement, it appears the value of the weak internal pull-up is about 35K, which is within the range of expectations.  That and your 4K external form the top of the divider (39K) while your 10K forms the lower half, yielding about a fifth of the supply voltage.

In some versions of the Arduino library, writing to an input pin enables and disables the internal pull-up resistor, so you could have observed your program seeming to control the pin - but at minimal drive strength.

To get the desired behavior, you merely need to add

pinMode(SignalPin, OUTPUT);


ESP8266 - Error: unknown opcode or format name 'jmp' I bought a nodeMCU 8266 and I'm hoping that it can replace my bulkier UNO+WiFi 101.

I'm getting an error when I compile:
Error: unknown opcode or format name 'jmp'

I'm using it in void SoftReset() function:

void softReset() {
  delay(1000);
  asm volatile ("  jmp 0");
}

This reset works great with my Uno+101 setup but, for whatever reason, doesn't like the ESP8266.  I removed the WiFi101 library and added the ESP8266 WiFi libraries.  That has been the only change.

Can you please help me understand why I'm receiving this error?

EDIT:  I have read this SO answer but the "syntactical sugar" didn't work for me.

I am also perusing various ESP8266 sites but they are not as well managed as SE/SO and answers are tough to find.

The proper way to reset the esp8266 when using the Arduino IDE is to call ESP.reset(). You may need to #include <Esp.h>, but almost all esp8266 headers you include to use any of its functionality will have included it already.


What is the difference between delay() and delaymicroseconds() Does delaymicroseconds() provide something more than the time accuracy

There is a more important difference between the two functions other than the unit of time the accept as parameters
the function delay() calculates time using the time interript of the arduino. However Delaymicroseconds() does not use the time interrupt
As you may know once an interrupt is called it stops all other interrupts
So the real difference is you can not use delay() in a program in which you are using an interrupt and instead, use delaymicroseconds() but be aware that it has a range where it is accurate and it is between 3 and 16383 micro seconds


Wemos D1 mini not being shown when connected to macbook I have multiple Wemos d1 mini lying around, but can't seem to get them connected to my macbook, to they do not show up in my /dev/tty?

I tried updating the driver, both using home-brew and installing the driver manually -  as suggested here

https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

but nothing seem to work?
I tried different cables? no way to connect to it?

All of the cables I tried don't have a data line


How to define and use a list/array of chars using `Serial.print` I wish to define a list of months names and access it when printing a report.

Array was defined as follows:

const char months []=
{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};

for (int i=0; i<=11; i++) {

                                 Serial.print(months[i]);
                        }

Tries:

I was looking for help under Arrays in Arduino documentation didn't give, as far as I found, any explanation for such case, but arrays of int

Appreciate any help.

You are almost there:

Use a char* instead of char, a char can only contain one character
Use " instead of ' (Thanks Juraj)

Then you get:

const char* months[] =
 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};


RS485 Multimaster Communication with collision avoidance I'd like to know if there is an easy way to implement communication between multiple arduinos that avoids collisions using the RS485 module.

My setup would have multiple masters that send messages to only one slave that performs a task upon been given the message.

I've tried researching some libraries for this, but they normally don't fulfil the multimaster requisite, nevertheless I found this library which apparently does implement what I need, but I haven't been able to understand how it works.

My current options are either finding an easier library that is capable of doing what I need, learning how to make the linked library work (which I have already tried) or building my own serial communication protocol that implements collision avoidance and a multiple master configuration.

What path should I follow? Can you give me any recommendation for any of the paths I'm suggesting? Is there a better way of implementing this type of communication?

There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).

The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.

In ‘understanding the library’ there are two aspects: how it works, and how to make it work.

The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.

However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.

So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.

The preferred way to contact me on these matters is by creating an issue on my Github project page:

https://github.com/MichaelJonker/HardwareSerialRS485/issues

BTW one of the issues addresses the same topic.

I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).

Best regards

MichaelJonker


expected unqualified id-before '/' token ------ can someone help, please /* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

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

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
/-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
/-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  deley(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}

OK, you just had a couple of minor typos.

It's nice to break up your code for readability, but single-line comments comments start with a double slash //, rather than a single.

Also, you had mis-spelled 'delay' in your loop.

This should compile without errors:

/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

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

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
//-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
//-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  delay(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}


Looking for a waterproof SPI temperature sensor In my current project I'm using a DS18B20, which seems to be the only temperature sensor to show up when googling for waterproof temperature sensor for an arduino.

The sensor itself is fine, however, I'm outputting the sensor's data to a SPI screen, and whenever the sensor is called to read data I believe the SPI communication is interrupted because of 1-Wire, and you can see a white flicker on the screen. The background LED is flashing more brightly for one frame. It's almost unnoticeable, but it bothers me.

I'm not using delays, and I'm not redrawing unnecessary elements on the screen again. Only dynamic elements are refreshed when they need to, static elements are only drawn once on the screen. The sensor is called every 5 seconds with a comparison:

if(currentTime - lastTimeQueried >= delay){
    lastTimeQueried = currentTime;
    temperature = new temperature;
    return temperature;
} else {
    return temperature;
}

I also tried a function where I'm constantly calling the sensor and only drawing on the screen if there's a change in temperature, but then the screen is flickering all the time. Thus I conclude that the flickering is caused by the actual calling of the sensor, and not from redrawing anything on the screen.

So I'm wondering if there's an alternative to the DS18B20 that communicates via SPI, and that I can use in an aquarium, so I don't have to use both protocols in my project.

Edit:

As requested some more of my code and wiring:

The screen is wired to the ICSP headers on my Arduino Mega 2560 and power is supplied via 5V on a powersupply that is connected to my breadboard.

The DS18B20 is wired to pin 29 on the Arduino and is also supplied with power via 5V on the same powersupply.

//TFT SPI
#define TFT_DC 9
#define TFT_CS 10
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

//SD Card Reader SPI
//#define SD_CS 4

//Touchscreen I2C
UTouch  myTouch(5, 8, 6, 7, 2);  //(T_CLK, T_CS, T_DIN, T_DOUT, T_IRQ)

#define ONE_WIRE_BUS 29
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

Here are some more variables that I have defined to help with using the sensor:

//Temperature measurement
unsigned long lastTempMeasure;  //Holds last unix timestamp temperature was measured at
char tempMeasureDelay = 5;      //Call temperature every 5 seconds
float sensorTemp;               //Holds measured temperature

In my loop I then use this function:

tft.print(temperatureCall());

and then:

float temperatureCall(){
  //get unix time for right now
  unsigned long currentUnix = now();

  //if 5 seconds passed since last poll, ask for new temperature, else return old measurement
  if(currentUnix - lastTempMeasure >= tempMeasureDelay){
    lastTempMeasure = currentUnix; //save last polling time

    sensors.requestTemperatures();
    sensorTemp = sensors.getTempCByIndex(0);

    return sensorTemp;
  } else {
    return sensorTemp;
  }
}

As I said, the flicker only occurs when these two are used every 5 seconds:

sensors.requestTemperatures();
sensorTemp = sensors.getTempCByIndex(0);

Edit 2:

Pic of wiring:

There is a delay in the DallasTemperature requestTemperatures() function - it blocks until the temperature conversion is complete unless you have previously called setWaitForConversion(FALSE). If you did that, you would still have to wait for the conversion but you can do it an a non-blocking manner, and I don't see that happening in your code.


How to send data from a smartphone to Arduino My goal is to build an extremely low cost quadcopter, by using the sensors of my smartphone (it will be mounted on the quadcopter). The arduino will only control the speed of each motor, as received from the smartphone. What methods exist to transfer data from a smartphone to arduino?

My first idea was to simply use USB, but it turns out that my smartphone doesn't support the USB host mode. Is it possible to send data over USB without USB host mode? What alternatives do I have? I thought of using the audio port: Can I directly connect an audio channel to analog in?

I have been using a bluetooth module - they can be had for just a few dollars (depending on which country you're in). I've got an HC-06 which works great : http://www.dx.com/s/hc-05

It has 4 pins: VCC (connect to +5V on Arduino), GND, RX and TX (connected to RX and TX, digital pins 0 and 1 on the Arduino).

You will probably not be able to use Bluetooth and USB at the same time - both will be sending to the Arduino at the same time, and the communications will get garbled.

I have an app called "Bluetooth Serial Controller", which lets me send commands over bluetooth.

If using this, think carefully about what will happen if your phone goes out of range of your arduino.


Button to stop a stopwatch not working correctly! I'm trying to implement a stopwatch with an LCD display, and I'm supposed to be using the attachInterrupt command to catch the button press. The clock runs perfectly, but the button input isn't caught or acted upon at all.
In void setup(), I have set it up this way: attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, RISING);.
And the buttonInterrupt function only does start = !start, so in a sense just flipping the start variable.
This is the updated version of the code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = 7;
volatile int buttonState;
int lastButtonState;
long sec;
long startTime;

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT_PULLUP);
  lcd.setCursor(0,0);
  lcd.print("Push the button!");
  attachInterrupt(digitalPinToInterrupt(buttonPin),buttonInterrupt,HIGH);
}

void loop() {

  buttonState = digitalRead(buttonPin);
  if(buttonState == LOW){
    startTime = millis();
  }

  while(buttonState == HIGH){
    long time = millis();
    long z = (time - startTime);
    sec = (z/1000);
    long ms = z%1000;
    lcd.setCursor(0,1);
    lcd.print(sec);
    lcd.print(".");
    lcd.print(ms);
    lcd.setCursor(8,1);
    lcd.print("Secs");

    if(buttonState == LOW){
      break;
    }
  }
}

void buttonInterrupt() {
  if(buttonState == LOW){
    buttonState = HIGH;
  }else{
    buttonState = LOW;
  }
}

The loop function works as far as time counting is concerned, but doesn't work to stop the time with the button. Any help is appreciated, I'm extremely new to Arduino (literally started yesterday). My circuit looks like this: https://i.imgur.com/yCR9fhP.png
If there is any other way to print the numbers other than printString, more than happy to hear them!
Thanks!

There are several issues here. First and foremost, your button is wired
incorrectly. If you connect one end of the button to +5V, then the other
end should have a pushdown to GND, like here:

(Image from the Arduino Button example).
The second issue is the lack of debouncing. You should ignore the rising
edges you sense for a few milliseconds after you record one.
The third issue is the timekeeping. As explained by Sim Son, your
seconds will not be very accurate. It's better to just count the
milliseconds elapsed since the button press, and then break the count
into full seconds and remaining milliseconds.


Gboard 800 (SIM900 + ATmega 328) Greetings dear reader!

I have some trouble storing my IMEI code inside a variable. It always returns an error: "void value not ignored as it ought to be".

Since then I tried to write it to the serial line by just running the gsm.SimpleWriteln("AT+GSN"); AT command, but I am stuck at storing this displayed value inside a variable. Does anyone here know a way to store a serial value into a variable? I just want to send the IMEI code as an identifier to the cloud application...

Thanks in advance, your response is really appreciated.

The code:

#include "SIM900.h"
#include <SoftwareSerial.h>
//#include "inetGSM.h"
//#include "sms.h"
//#include "call.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to communicate with SIM900 through AT commands.

//InetGSM inet;
//CallGSM call;
//SMSGSM sms;

int numdata;
char inSerial[40];
int i=0;
boolean startUp = false;

void setup() {
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");

  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(9600)) {
    Serial.println("\nstatus=READY");
    getIMEI();
  } else Serial.println("\nstatus=IDLE");
};

void loop() {
  //Read for new byte on serial hardware,
  //and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i=0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i]=(Serial.read());
      delay(10);
      i++;
    }
    inSerial[i]='\0';
    if(!strcmp(inSerial,"/END")) {
      Serial.println("_");
      inSerial[0]=0x1a;
      inSerial[1]='\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if(!strcmp(inSerial,"TEST")) {
      Serial.println("SIGNAL QUALITY");
      gsm.SimpleWriteln("AT+CSQ");
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0]='\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

void getIMEI() {
  long IMEI = gsm.SimpleWriteln("AT+GSN"); // IMEI code
  Serial.println(IMEI);
  return IMEI
}

The SimpleWriteln() function just sends an instruction. It doesn't return anything.  Once you have sent the instruction to retrieve the IMEI you then have to actually read the IMEI.

However, fortunately, there is a function that does it for you:

char imei[20];
gsm.getIMEI(imei);

The IMEI should now be in the C string imei. What you do with it then is up to you.


How can I read delay of a note that I am playing I am playing note tone with CapacitiveSensor and an output of tone
like this

void loop() {
    time_before = millis();

    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);

    if((total1>200)||(total2>200)) {

        if(total1>200) {

            tone(12,261);
            time_after = millis();
            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
        if(total2>200) {
             tone(12,294);
             time_after = millis();
             Serial.print("Time: ");
             Serial.println(time_after-time_before);
        }
    }
}

How can I read how many seconds I play this note par example

Your code currently will only measure the code execution time and not the duration of the note(s) being played.

You need to follow uint128_t's suggestion and rewrite the code to detect the "button release", at which point you measure the time with millis(), and call noTone(). Only then will you be able to measure the note's duration.

I believe that the source of confusion is that you seem to think that tone() acts like delay() and waits for the note to finish - it does not. tone() merely starts the note and then the next instruction is executed, without waiting for the note to end.

So, using millis() straight after calling tone() will actually only measure the time it takes to execute the tone() statement (and a few if statements - depending on whether you use your original code, or Maximus's code).


Arduino wire can't send char Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver.
I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like Wire.write("blablabla"); it pass. But when in char is NRF data code crashing when go to "Wire.write".

/*
*/
#include <Wire.h>
#include <SPI.h>
#include "RF24.h"

char datar = '';

//Konfiguracja
const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
//-- Konfiguracja

void setup() {
  Serial.begin(9600);
  Serial.println("LOL");
  Wire.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1, pipes[0]);
  radio.openWritingPipe(pipes[1]);
  radio.setChannel(78);
  radio.setAutoAck(true);
  radio.startListening();
}

void loop() {

  int len;
  if(radio.available())
  {
  len = radio.getDynamicPayloadSize();
  radio.read(&datar, len);
  delay(5);
  Serial.println(datar);
  Wire.beginTransmission(7);
  Wire.write(&datar);
  Wire.endTran345smission();
  radio.printDetails();
  }
  delay(5);

}

Your problem is here:

char datar = '';

...

 len = radio.getDynamicPayloadSize();
 radio.read(&datar, len);

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into datar more than one byte. This overwrites other parts of memory and the program crashes. You need to make datar larger, eg.

char datar [50];

The exact size would depend on your maximum payload size.


nRF24L01 not communicating I have been using two nRF24L01 to communicate with each other using a simple Arduino Uno Board. It worked for 5 days and now all of a sudden it is now working. I tried to change the modules and the Arduino boards too, but even if trying a simple example the communication between them is not happening.

I googled everything and tried every option, it is not working.

I used printDetails() to check the config of the modules. It shows everything is ok but I am not able to understand if the transmitter or the receiver is the problem. Please guide me to solve this problem. Also how to make sure if both are working (any debugging technique)?

I have been trying it for 9 days now, and I badly want it to work.

The code I am using is very simple code. It doesn't have any errors.

Receiver code:

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String response;
boolean done = false;

void setup() {
  delay(500);
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(0,0xF0F0F0F0AA);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&response, sizeof(response));
    done = true;
  }
  if (done) {
    Serial.println(response);
  }
  done = false;
  delay(1000);
}

Sender code:

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String request;

void setup() {
  delay(500);
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(0xF0F0F0F0AA);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  while (Serial.available() > 0) {
    request = Serial.readString();
    Serial.println(request);
    radio.write(&request, sizeof(request));
    delay(1000);
  }
}

Hello,
You need to set a channel to both NRF:

void setup() {
   delay(500);
   Serial.begin(9600);
   radio.begin();
   radio.setChannel(0x55); //set the channel
   radio.openWritingPipe(0xF0F0F0F0AA);
   radio.setPALevel(RF24_PA_MIN);
   radio.stopListening();
   radio.powerUp(); //Power up the radio
}

Change this.

void loop() {
    if (radio.available()) {
        radio.read(&response, sizeof(response));
        done = true;
    }
    if (done) {
        Serial.println(response);
        done = false;
    }
    //done = false;
    delay(1000);
}


HC-05 can not use lower pins only 8 and higher #include <Arduino.h>
#include <SoftwareSerial.h>

char Incoming_value = 0;

// SoftwareSerial BTSerial( 10, 11 ); // RX | TX +
// SoftwareSerial BTSerial( 9, 10 ); // RX | TX +
// SoftwareSerial BTSerial( 8, 9 ); // RX | TX +
// SoftwareSerial BTSerial( 7, 8 ); // RX | TX - ???
// SoftwareSerial BTSerial( 6, 7 ); // RX | TX - ???
// SoftwareSerial BTSerial( 5, 6 ); // RX | TX - ???
// SoftwareSerial BTSerial( 4, 5 ); // RX | TX - ???
// SoftwareSerial BTSerial( 3, 4 ); // RX | TX - ???

SoftwareSerial BTSerial( 8, 9 ); // RX | TX +

void setup() {
        BTSerial.begin( 9600 );
        pinMode( 13, OUTPUT);
}

void loop() {
        delay( 1000 );
        BTSerial.println( "hello" );
        if( BTSerial.available() > 0 ) {
                BTSerial.println( "BINGO!" );
                Incoming_value = BTSerial.read();
                BTSerial.println( Incoming_value );
                if ( Incoming_value == '1' ) digitalWrite( 13, HIGH );
                else if ( Incoming_value == '0' ) digitalWrite( 13, LOW );
        }
}

My HC-05 Bluetooth module wont't work on lowers digital pins.

  BOARD_TAG = leonardo

It works fine on highers digital pins: 8-9, 9-10 or 10-11 - everything fine.
but 2-3, 3-4, 4-5, 5-6, 6-7 or 7-8 - no....

Why? Should I inject jumper somewhere or what?

And yes: @Majenko, "0,1 - is required to debug from host". I want to have Serial from PC and BTSerial from bluetooth - to have both accesses to device simultaneously.

@Peter_Paul_Kiefer, so, you think, this is impossible with lowest pins, lower than 8?

From the official SoftwareSerial Site: https://www.arduino.cc/en/Reference/softwareSerial (Section Limitations)

  Not all pins on the Leonardo and Micro support change interrupts, so
  only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15
  (SCK), 16 (MOSI).


Attiny45 resets when setting digitalOutput to low I currently try to program an Attiny45 with an Arduino UNO as ISP.

The Arduino is able to program the Attiny45.

However, when I try the blink example, it resets the Attiny, when setting digitalOutput to low
(on any pin)

To further confirm, that it resets only, when setting a pin to low, I wrote this sketch and let it run on the Attiny.

void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  delay(1000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
  delay(10000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
}

The LED I connected to pin 3 waits 1 second, and then turns on, but when 1 second passed and it should stay off for 10 seconds, it resets and only waits 1 second.

I tried reburning the bootloader onto the Attiny, which had no effect.

Including the 220Ω resistor with the LED as in the last step?

...

  My LED can handle 5V, so I used it without, but that cant be the issue

The one thing that "can't be the issue" is indeed the issue! Without a resistor the LED will attempt to conduct a lot of current which will damage both it and the output pin of the processor.

See The care and feeding of LEDs. From that page:

  LEDs are not like normally electronic devices in that you can’t just apply a voltage to them and they work, they have to be fed the correct voltage and current to keep them happy.

And then:

  There are several web sites and schematics on the web that suggest you can attach an LED directly to an Arduino output pin with no current limiting resistor. They are wrong, and following them will damage your Arduino.

So, by not using a resistor, when the output pin goes LOW it attempts to "sink" current, in order to turn on the LED. Since you have no resistor, it sinks as much as the output drivers can handle, dropping the supply voltage inside the Attiny, which then goes below the brownout level, and resets itself.

Please, when following a circuit, don't just omit bits of it, and then post a question about why it doesn't work. At least follow the circuit exactly, and then when you have learned more about electronics, you can start experimenting.


GPS library for Proteus I am working on a project in which I have to connect my Arduino with a GPS module. In this project I need to get longitude, latitude, time and date from the GPS module and need to send these values via USB to a computer.

On this computer, I am going to design software in Microsoft Visual Studio 2010, which will receive this data and display it on a map.

Now, before designing it in hardware, I want to simulate it on Proteus. I have searched in Proteus but there's no GPS module in it, so does anyone know any GPS module library for Proteus?

I have found the solution to my question so I thought to post it here so that others could also get benefit out of it. Here's the link to GPS Library for Proteus - A complete step by step tutorial on How to download GPS Library for Proteus.

From this link you can download the GPS Library which you need to add to the libraries folder of your Proteus software and you will have the GPS module in Proteus and you can design your simulation quite easily. More details are given in this link.


Running two NEMA 17 motors, one by one, using the Arduino Uno I am new to Arduino. I am trying to run two stepper motors NEMA 17 through respective A4988 driver and controlling via Arduino Uno.

The thought is that first stepper motor will carry out a first horizontal scan and then as it reaches to its initial position, second stepper motor will move a single step in vertical direction. This is a kind of raster scan that I want to perform with both motors.

When I am running the code, only horizontal scan motor is running and vertical scan motor is not moving. I have checked my circuit, motors and drivers and everything is working fine. I think there is some mistake in my code. It is a basic level code and I would really appreciate the help for helping me out.

int x, y; //stepper motor 'x' and stepper motor 'y'
#define BAUD (9600)

void setup()
{
  Serial.begin(BAUD);
  pinMode(6,OUTPUT); // Enable for x
  pinMode(5,OUTPUT); // Step for x
  pinMode(4,OUTPUT); // Dir for x
  digitalWrite(6,LOW); // Set Enable low for x

  pinMode(9,OUTPUT); // Enable for y
  pinMode(8,OUTPUT); // Step for y
  pinMode(7,OUTPUT); // Dir for y
  digitalWrite(9,LOW); // Set Enable low for y
}

void loop()
{

  digitalWrite(9,LOW); // Set Enable low for y

  for(y = 0; y < 20; y++)
  {
     digitalWrite(6,LOW); // Set Enable low for x
     digitalWrite(4,HIGH); // Set Dir high for x - Clockwise

     Serial.println("CLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

     for(x = 0; x < 50; x++) // Loop 50 times
     {
      digitalWrite(5,HIGH); // Output high for x
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low for x
      delay(100); // Wait
     }

    digitalWrite(6,LOW); // Set Enable low for x
    digitalWrite(4,LOW); // Set Dir low for x - Anticlockwise

    Serial.println("ANTICLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

    for(x = 0; x < 50; x++) // Loop 50 times
    {
      digitalWrite(5,HIGH); // Output high
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low
      delay(100); // Wait
    }

    Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");

    digitalWrite(7,HIGH); // Set Dir high for y

    digitalWrite(8,HIGH); // Output high for y
    delay(100); // Wait
    digitalWrite(8,LOW); // Output low for y
    delay(100); // Wait
  }

  digitalWrite(9,LOW); // Set Enable low for y
  digitalWrite(7,LOW); // Set Dir low for y

  Serial.println("RESETTING ON VERTCAL AXIS");

  for(y = 0; y < 20; y++) // Loop 20 times
    {
      digitalWrite(8,HIGH); // Output high for y
      delay(10); // Wait
      digitalWrite(8,LOW); // Output low for y
      delay(100); // Wait
    }

}

Do i need to look after the delay being provided??

A minor issue that probably won't affect your result is that

Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");
--> digitalWrite(9,LOW);  // This line 'needs' adding
digitalWrite(7,HIGH); // Set Dir high for y

I can't see anything in the code that will prevent the motors running, OK it will take ~13 seconds to start moving, but it should move.

So - without any hardware attached to the motor spindles - is it possible to switch the motors over to check for a wiring breakage issue?  With one motor working and one not it implies to me that either the motor is broken, the wiring is broken or the driver circuit is broken.  If the fault moves then its a motor/wiring fault if it stays the same then its a driver fault.


Making a 7-hour timer-based relay I want to make a very small 7-hour timer circuit that can turn on a relay after 7 hours. I am trying to make the first prototype with an Arduino Nano but I can't understand how to program it for such purpose. So please help me out.

Once I make a prototype in Arduino then I was thinking to make a small one  using an ATtiny13. Can I use an ATtiny13 for such purpose?

cant understand how to program it for such purpose so please help me out

it is fairly easy to approach such questions:

1) you can program any?

2) can you program this mcu to blink an led?

3) can you program this mcu to do short time counting?

4) can you program this mcu to do long time counting?

what you help helps you the most depends on your  answers to those questions.


Pre-heat time required for MQ-5 gas sensor The datasheet of MQ5 sensor says, it requires a pre-heat of 24 hours. Does this mean that it needs to be powered on for 24 hours consecutively before usage? Some other websites (e.g. http://www.circuitstoday.com/interfacing-mq5-lpg-sensor-to-arduino) say that 15 minutes pre-heat would suffice. Could someone clarify this issue? Thanks.

Please be clear when you mean the one time only pre-heat and when you mean turning the sensor on to take a measurement.

It is a electrochemical sensor and it needs time to burn-in. During those 24 hours, the impedance of the sensor changes a lot. After those 24 hours it can be used in a normal way and it will return consistant values.

The pre-heat should be done just once. I mean: just once in the lifespan of the sensor. After buying it, you should run the pre-heat.
When the manufacturer writes in the datasheet that the pre-heat time is 24 hours, then you should do 24 hours.
I suggest to connect the sensor in a normal way, with 'A' en 'B' pins connected and with the load resistor, and keep it on for 24 hours. Maybe it is already stable after a few hours, but keep it on for 24 hours to be sure.

To take a measurement, the sensor needs time to warm up. About 5 minutes might be okay. I think that 2 minutes is definitely too short.
When the sensor is always at room temperature, and the time to warm up is always the same, then the measurement is relative accurate and can be compared with other measurements. That means that when the sensor is mostly turned off to save power, only a few minutes to warm up can be used. However, I would start with at least 5 minutes.

[EDIT] The datasheets and other information from the manufacturers use the term "pre-heat" in different ways. The Technical Note in the link by @EnricBlanco uses the term "preheating" only for the "one-time-only" heating after storage to make the sensor more stable, as far as I can tell. Although it is not "one-time-only", it should be applied after storage or changing conditions as well. @EnricBlanco, try a very cheap MQ gas sensor (which is probably not preheated in the factory) and see how the impedance changes a lot during the first hours of preheating, and becomes stable after a few hours.


Turn off power to a moisture sensor except when reading values I have an Arduino Uno and a moisture sensor (looks like a YL-69 clone) submerged in water. I need to read the sensor's (analog) value every 3 min or so. The problem is: the sensor is always powered by the Arduino (GND and VCC), i.e. the current passes through it at all times. Because of this, one of the sensor's electrodes (presumably containing copper) grows a cyan residue. I'd like to NOT supply any power to the sensor except for the brief moment when I need to read the value. How can I do this?

EDIT: I've just noticed a related question (link below). The user decided to intermittently power the sensor via a digital pin, rather than VCC. Is this reasonable?

Does a moisture sensor need warm-up time?

If your sensor draws less than 40mA to operate, then you can safely "power" it from an GPIO pin.

The related question also asks how long the sensor must be powered in order to get a stable reading. For a sensor such as this one, it appears to be a simple resistive voltage divider, with the moisture sensor itself providing one leg of the divider circuit. The active component appears to be a comparator to provide a digital HIGH/LOW output as an alternative to the analog output.

Most schematics show a capacitor between ground and the voltage divider output, presumably to reduce noise. You need to allow for this capacitor to charge up and become stable before you take a reading. The time for this depends somewhat on the value of that capacitor and the supply voltage you are using.

Safe to assume, however, that a wait time of 1 second is more than enough.


LM35 readings are erratic My son just did the Love-o-meter project in the Arduino Start Kit. However, the sensor readings of the LM35 temperature control vary widely. Below is a sample. What could be wrong?

Sensor Value: 217, Volts: 1.06, degrees C: 105.96
Sensor Value: 587, Volts: 2.87, degrees C: 286.62
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 320, Volts: 1.56, degrees C: 156.25
Sensor Value: 445, Volts: 2.17, degrees C: 217.29
Sensor Value: 141, Volts: 0.69, degrees C: 68.85
Sensor Value: 510, Volts: 2.49, degrees C: 249.02
Sensor Value: 247, Volts: 1.21, degrees C: 120.61
Sensor Value: 168, Volts: 0.82, degrees C: 82.03
Sensor Value: 595, Volts: 2.91, degrees C: 290.53
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 206, Volts: 1.01, degrees C: 100.59
Sensor Value: 606, Volts: 2.96, degrees C: 295.90
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 290, Volts: 1.42, degrees C: 141.60
Sensor Value: 487, Volts: 2.38, degrees C: 237.79

Here's the code:

const int sensorPin = A0;
const float baselineTemp = 25.0;

void setup(){
  Serial.begin(9600); // open a serial port
  for(int pinNumber = 2; pinNumber<5; pinNumber++){
    pinMode(pinNumber,OUTPUT);
    digitalWrite(pinNumber, LOW);
  }
}

void loop(){
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);
  // convert the ADC reading to voltage
  float voltage = (sensorVal/1024.0) * 5.0;
  Serial.print(", Volts: ");
  Serial.print(voltage);
  Serial.print(", degrees C: ");
  // convert the voltage to temperature in degrees
  float temperature = (voltage) * 100;
  Serial.println(temperature);

  if(temperature < baselineTemp){
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+2 &&
    temperature < baselineTemp+4){
    digitalWrite(1, HIGH);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+4 &&
    temperature < baselineTemp+6){
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+6){
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
  }
  delay(1);
}

The GND is connected to the left most connector in the LM35, the A0 to the middle, and the power to the right most connector.

I've had a look round and spotted this:

https://electronics.stackexchange.com/questions/117970/why-is-my-analog-temp-sensors-signal-so-unstable

In summary it says that the fault maybe that the Arduino's 5V isn't stable enough, so you need to decouple it.  For once it seems that running from batteries may have been a better idea.

I've also seen posts saying there should be a 500Ohm resistor between the Ground of the LM35 and Ground.  Apparently it says 499Ohm on the datasheet.

And as a final resort I saw said that the 'Data Direction Register' influenced the analog pins.  If it was set to digital output this could lead to unstable readings for the ADC.  Basically it implied you needed to set the analog pin's to pinMode (A0, output). But I really don't think this will work


Accepting strings and integers via UART My intention is to write a code that asks a user to enter the name and then the age. The code should then simply display the persons name and age. To do that, I have written a simple code. I find it difficult to get it to work.

char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer
    while (Serial.available()==1){
        temp = Serial.read();
    }

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    age = temp;

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available()==1){
        temp = Serial.read();
        delay (10);
    }

}

The error I receive is that the program already outputs age without me even typing it.  Would it be possible to know the error?
I use both NL and CR to send in characters to Arduino and the Arduino IDEs default UART terminal.

EDIT:

Listening to advice gotton from answers I got the code to work but in a very weird way. My new code works! but it proves the clearing of buffer cannot be done by just reading it. This is in contrast to Arduino documents. My new code is as follows.

char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer **WHY IS THIS CODE NOT EFFECTIVE?**
    while (Serial.available() >= 1){
        temp = Serial.read(); // performing dummy reads untill buffer empty.
    }

    temp = Serial.read();
    delay (1000);
    temp = Serial.read();
    temp = Serial.read();
    temp = Serial.read();

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    temp = temp - 48;
    age = temp*10;
    delay (1000); // providing the user a day to enter next digit of age

    if (Serial.available()){
        temp =  Serial.read ();
        temp = temp - 48;
        age = (int) temp + age; //whatever that is added have to be of same type. Else they need to be cased to same type.
    }

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available() >=1 ){
        temp = Serial.read();
        delay (10);
    }

}

As we don't know what you are using as a terminal program we can't comment specifically on your choice of EOL characters.

It is likely you are receiving everything in ASCII code.  That is, when you type the number 1 you are actually getting the ASCII equivalent (0x31) from your terminal.

This is fine when you are working with character strings.  But when you want to work with numbers that are to be used in equations you need to 1) make sure that the user is only entering a number (check to make sure the values are from 0x30 to 0x39) and 2) subtract the ASCII value for '0' from the value you received from the terminal.  That is, subtract 0x30.

It should now be obvious that you can only enter 1 digit at a time when using a terminal.  That you will have to reconstruct the number as the user types each digit.  For example the number 13 is a 1 and a 3 and you will have to multiply the 1 by 10 then add it to the 3.

Since this is such a common conversion, there are Arduino libraries that do this for you.  Consider using ParseInt for this purpose.

Added later...

In the modified code, consider the possibility the terminal program is sending both a Carriage Return (aka: CR, 0x0D, \r) and Line Feed (aka: LF, 0x0A, \n) each time the Enter key is pressed.  And that the code is only waiting for the CR.

The delays are necessary as UART communication, as most communications, takes a finite amount of time.  And additional characters, if any, and even if autonomously sent, will take a finite amount of time to arrive.

Consider "looking" for the LF character after finding for the CR character and removing the added delays.


AVR - How to know that there is collision between stack and heap or the memory has filled? I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The AVR heap implementation has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

Typically the minimum margin should be able to hold the largest stack usage (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.

If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.

Not checking NULL return from malloc() gives some interesting errors on the AVR as the processors registers are memory mapped. NULL points to R0.

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.


Problem with sending DMX I want to send DMX with my Arduino Mega 2560. I'm using the IDE 1.6.7

I tried the AVR -> DMX source code from Ulrich Radig and also the layout for the RS-485 transmission.

I modified the code to fit the ATMega2560 but when I upload the code nothing happens.

The only thing I didn't do is to use the 22 Ohm resistors, is that a problem?

Any idea?

Here is my circuit:

Here is the source

#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000
#include <util/delay.h>

#define DMX_BAUD 250000
#define DMX_BAUD_BREAK 80000
#define DMX_BAUD_BREAK_UBBR ((F_CPU+DMX_BAUD_BREAK*8)/(DMX_BAUD_BREAK*16)-1)
#define DMX_BAUD_UBBR ((F_CPU+DMX_BAUD*8)/(DMX_BAUD*16)-1)

volatile unsigned char dmx_buffer[512];

//############################################################################
//DMX Senderoutine
ISR (USART_TX_vect)
//############################################################################
{
  static unsigned int  dmx_channel_tx_count = 0;
  static unsigned char dmx_tx_state = 0;

  switch (dmx_tx_state)
  {
    case (0):
      UBRR0   = DMX_BAUD_BREAK_UBBR;
      UDR0 = 0; //RESET Frame
      dmx_tx_state = 1;
      break;

    case (1):
      UBRR0   = DMX_BAUD_UBBR;
      UDR0 = 0; //Start Byte
      dmx_tx_state = 2;
      break;

    case (2):
      _delay_us(10);
      //Ausgabe des Zeichens
      UDR0 = dmx_buffer[dmx_channel_tx_count];
      dmx_channel_tx_count++;

      if(dmx_channel_tx_count == 512)
      {
        dmx_channel_tx_count = 0;
        dmx_tx_state = 0;
      }
      break;
  }
}

void setup() {
 //Init usart DMX-BUS
 UBRR0   = DMX_BAUD_UBBR;
  DDRE |= (1<<PE1); //Output TXD Pin ATmega2560
  UCSR0B|=(1<<TXEN0)|(1<<TXCIE0); // TXEN0 Transmitter enable / TXCIE0 TX complete interrupt enable
  UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
  sei();//Globale Interrupts Enable
  UDR0 = 0;//Start DMX

}

void loop() {
  // put your main code here, to run repeatedly:
    dmx_buffer[4]=255;
    _delay_ms(1000);
    dmx_buffer[5]=255;
     _delay_ms(1000);
    dmx_buffer[6]=255;
    _delay_ms(1000);
    dmx_buffer[4]=0;
    _delay_ms(1000);
    dmx_buffer[5]=0;
     _delay_ms(1000);
    dmx_buffer[6]=0;
     _delay_ms(1000);

}

The only thing I didnt do is to use the 22 Ohm resitors, is that a problem?

Yes, that's a huge problem. The resistors are there to prevent reflections from distorting the signal. Without them the best you can hope for is a garbled mess.


Arduino 16 MHz with only 3.3V? Now I have these Arduino Pro Mini from Sparkfun. They are the latest version that I know (yeah, it's the one that have those horrible misaligned pins). Now they are designed around the ATmega328P and have a 16MHz crystal on them.

Now, my question is: Can I run an ATmega328 with a 16MHz crystal while supplying ONLY 3.3V.

The reason I'm doing this is because 5V / 16MHz Pro Minis from China are way cheaper then 3.3 / 8MHz.

Facts that I already know:

If I follow the datasheet to the the letter, this configuration should not work. BUT... After some test, it did work.

Also, I want an answers based on personal experience (NOT OPINIONS) and not datasheet and specs.

[EDIT] Including a way to use the internal clock (at 8MHz) of the ATmega328P would really help!

Officially, no.  Practically, often but not always.

  If I follow the datasheet to the the letter, this configuration should not work. BUT... After some test, it did work.

The data sheet does not say that it "should not" work, it says that it is that the part is not qualified for operation at 16 MHz below some voltage higher than you want to use.  That does not mean that a given chip cannot work there, it only means that a chip that fails to may not be considered "bad".  Failure may be total and obvious or subtle.

In practice I have seen it work, both on small modified import boards and those with switchable power supply voltage.  But I also recall seeing it fail to work.

Two factors that can make a theoretical difference are part-to-part manufacturing variation and operating temperature.

Note that with an ISP setup you can change the fuses to run the chip on what was sold as a 5v external crystal board, to operate from the internal 8 MHz oscillator instead, and you can do this even while leaving the crystal on the board.  If you also change the brownout detector fuse, you can lower the voltage further, for example to operate without a regulator directly on two AA cells.  Of course that applies to the ATmega itself - any other active components on the board would have to be qualified for the intended voltage too.


Sending a string to arduino and is not reacting to it I am trying to move servos with a VR headset, I am using the Unreak 4 Arduino Plugin, but that is not the problem. I send the rotation Y and Z from the headset, convert them to int and then send them together as an int separated by commas. Here's what it does: It gets the rotation Z, it converts it to int, then it converts it to String, I add a comma at the end of the String, then I add the rotation Y after the comma, and it returns me: "rotationZ","rotationY" (the values between " are the numbers sent by Unreal to arduino), these results may come in negative or positive value.

Then inside arduino I have this code:

#include <Servo.h>
#include <SoftwareSerial.h>

Servo servo1;
Servo servo2;  // Crea un Objeto servo

int angle = 10;
int posicion = 10;    // Variable de la posicion del servo

String user_input1;

int r;
int g;

void setup()
{
  Serial.begin(9600);
  servo1.attach(2);  // Selecionamos el pin 2 como el pin de control para el servo
  servo2.attach(3);  // Selecionamos el pin 2 como el pin de control para el servo

  servo1.write(0);
  servo2.write(0);

  Serial.setTimeout(5);
}

void loop()
{
  if (Serial.available() > 0)
    {
  String firstValue  = Serial.readStringUntil(',');
 // String first = Serial.readString(); //next character is comma, so skip it using this
  String secondValue = Serial.readStringUntil(',');
//  String second =  Serial.readString();

   r = firstValue.toInt();
   g = secondValue.toInt();
    }
  if (r < 0)
  {
    r = r * -1;
  }

  if (g < 0)
  {
    g = g * -1;
  }

  Serial.println(r);
  Serial.println(g);

  servo1.write(r);
  servo2.write(g);

}

As you can see, it gets the numbers between the commas and then it converts them to int, and then it applies to the servos which are in pins number 2 and 3 (yes, everything is plugged in correctly), which it should then move them acordingly the position of the VR headset, I've also tried to make them always receive positive results but still doesn't work. I have searched over the internet on how to separate a string divided by commas and I still don't know if it's correctly done.

EDIT: I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR. I also added Serial.setTimeout(5) to try if it works that way.

Thanks in advance for reading this bunch'o text about my problem.

I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR.

This implies that the problem is in the code sending the data.  Get a terminal emulator program and hook that up to the code generating the data from the VR headset (you will need 'local echo' turned on).  I suspect you will see the headset is not writing the data in the format you expect.  Also it will let you capture a real sample of data that you can feed into you program to generate a repeatable test.

If this isn't the fault, then please can you post the a few lines of data so we can see whats wrong.


Serial Monitor listing rapidly I am using an infrared sensor and a flex sensor to read values from the serial monitor in arduino, however after maybe ten seconds or so it seems the serial monitor breaks and the printed values start to print out rapidly. Does anyone have any suggestions on why this might occurring. Any information would be highly appreciated.

Thanks.

int previousMillis = 0;

long interval1 = 300;
long interval2 = 350;

void setup() {

    Serial.begin(9600);
}

void loop() {

    unsigned long currentMillis = millis();

    if ( currentMillis - previousMillis >= interval1 ) {
        previousMillis = currentMillis;

        Serial.println( "TIMER IS DONE!" );

        int val1 = analogRead(0);
        Serial.print("Sensor Value 1 is ");
        Serial.println(val1);
        delay(5);
    }
    if ( currentMillis - previousMillis >= interval2 ) {
        previousMillis = currentMillis;

        int val2 = analogRead(1);

        Serial.print("Sensor Value 2 is ");
        Serial.println(val2);
    }
    delay(10);
}

You are doing math with 2 different types.   One is long and the other is an int.  So, eventually the long will always be lager than the int and the test will always be true.  (A 32 bit long can count up to over 2 billion.  A 16 bit int can only count up to about 32 thousand.)

Also, the method millis() is of type "unsigned long".  So change all your variables to match this type.

Also note that when the millis() timer overflows and start over your program may perform unexpectedly.  Since this rarely happens it may not concern you.


arduino ethernet shield I bought a ethernet shield for my Arduino Uno. I plug it my Arduino and PC with ethernet cable. There is all led is working on ethernet shield. But when i try to examples about ethernet which is in Arduino IDE as "DHCPChatServer" example.

I hope to see;
"Trying to get an IP address using DHCP"
"My IP address: 192.168.1.177"

But I just see "Trying to get an IP address using DHCP"

Any problem with my ethernet shield?

When you connect your arduino directly to the PC using the ethernet cable, neither of them have any information about the network.

Most ethernet devices attach to switches, routers, and gateways, and one or more of these devices host network services such as DHCP, DNS, or provide a way to obtain those services.

Without DHCP, for instance, neither your PC nor the Arduino know what IP adress to use, what their netmask is, and whether there's a gateway to other IP addresses.

You have a few options:

Follow the Automatic Private IP Addressing specification, which windows computers default to when no DHCP server is present or available. Set the IP address of the Arduino to 169.254.x.y where x and y are randomly chosen numbers between 0 and 255, and set th netmask to 255.255.0.0.  The windows computer should have done the same if no static IP address was set - use ipconfig on the windows command prompt to find its IP address.  Your computer and arduino should be able to talk to each other.
Set up a router. It doesn't need to connect to the internet, it just needs to connect to both the PC and the Arduino.  It'll implement a DHCP server and make sure, at minimum, that the two devices can talk to each other and the router.
Set static IP addresses on both devices.  Set up the PC with something like 192.168.42.1 with a netmask of 255.255.0.0 and the Arduino with 192.168.42.2 and the same netmask.  Now they should be able to talk to each other.
Connect both to an existing network.  The network should already have a router with DHCP on it, so it'll take care of everything, and as a bonus you may be able to get internet access as well, which could help with testing since you can use the ethernet shield to communicate with google and other known working services, rather than trying to set up a server on the PC.


Issues using HC-06 Bluetooth module with arduino I recently ordered an HC-06 Bluetooth module for my Arduino Uno, and after watching this video, and many others, I still have been having many issues figuring out how to get it to work, and some questions for how the code receives and reads serial data from my phone.

I assume this wiring is correct, right?

Rx  > Tx
Tx  > Rx
Gnd > Gnd
Vcc > 3.3V

When I sent a command over the Bluetooth terminal app I have, the serial monitor displays that command over and over, I assume that is correct also?
How do I read the serial input? I've been using

if(Serial.available() > 0)
        phoneInput = (char) Serial.read();

and then displaying the value of phoneInput to the serial monitor, but for some reason I can't seem to have it control anything properly (in this case an LED)
What datatype is the Serial.read() returning to my variable before I cast char on to it?
I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

I assume this wiring is correct, right?

Rx > Tx
Tx > Rx
Gnd > Gnd
Vcc > 3.3V

Almost. The Arduino's TX should be reduced to 3.3V using a 10k/20k potential divider.

  How do I read the serial input? I've been using

if(Serial.available() > 0)
       phoneInput = (char) Serial.read();

You should read and digest this.

  What datatype is the Serial.read() returning to my variable before I cast char on to it?

An integer. It holds either 0-255 representing the ASCII code for a character, or -1 if there is nothing in the buffer to read.

  I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

That will be because you are using pins 0/1 to communicate with the bluetooth which you can't do because those are used to communicate with the PC.


Programming ESP32 MCUs for production Before committing to learning about the ESP32 and how to program it, I would like to know if the ESP can be programme the same way for production as it can on évaluation boards (with the Arduino IDE).

Since it obviusly much easier than most for microcontrollers, I was wondering if a product is eventually mass produced, if the code used to program the evaluation board (such as this one https://makeradvisor.com/tools/esp32-dev-board-wi-fi-bluetooth/) could be used on the final product.

Yes. Most manufacturers would just require a binary (or HEX depending on MCU) file of your compiled code. If it's not a system they already know how to handle you will also need to provide a procedure for them to follow to program the device. What form that takes depends on the manufacturer.

You can also generally order pre-programmed MCUs and modules direct from the manufacturer where they (for a small fee) will program the chips for you before they are then sent to the board manufacturer for population.

If there is no facility on the MCU manufacturer's website then just email their sales department and I am sure they would be happy to quote you. Again, all they will require is a HEX or BIN file (depending on manufacturer) for programming.


Problem with ATtiny85 and RF modules I am doing a project on a ATtiny85 which involves using 433MHz RF modules. Whenever I want to compile any sketch using the Manchester library I always get these errors : "Manchester library doesnt support your microcontroller". Could anyone help me solving this?

Somehow I got it working. I don't know the cause of the problem but in order to fix it I had to Arduino 1.0 IDE; use this ATtiny support and this Manchester library. Thank you all for your help.


SerialEvent handling when using multiple serial ports I would like to use multiple (three) serial ports on an Arduino Due. Instead of polling the ports continuously, I would like to use a Serial.Event function for each of the ports. These handler functions will read out the incoming string from the port and parse the string (i.e. check for a pre-defined command and call a corresponding sub-routine).

I was wondering what is going to happen when serial data arrives at the same time at two different ports? For example, if the program is in the process of handling/parsing the first serial message, will it interrupt/abandon this process as soon as another SerialEvent on another port is triggered? Or will it complete the first SerialEvent routine before going to the second one?

The built in serialEvent() function on arduino only responds to serial port 0, called just "Serial" in the code. To respond to messages on "Serial1", use serialEvent1() on the Arduino Due there also exists serialEvent2() and so on.

EDIT: the serialEvent() handlers are not on interrupts; they run sequentially in-between loops. If the loop is blocking they do not get run, and they do not interrupt eachother.


Can I safely connect my A6 GPRS module to this 5V 2A phone adapter I have an A6 GPRS module, and my Samsung phone power adapter has output of 5V and 2A. But it also says 9V and 1.6A

My Phone's Adapter
So would it damage my A6 GPRS Module if I plug this to it via the micro usb power port? (especially because it also says 9V)?

My A6 GPRS module

The standard output for USB is 5V but there are some such chargers that will output more for enhanced charging output on devices that support it.
In this case the adapter will default to 5V and will only upgrade to 9V if the device requests it.  The GPRS module will not request 9V and so the adapter will continue to provide only 5V which is what you want.


If condition for switch not working as expected I am trying to write a simple program to control one LED with two switches.
If any of the switches is pressed, I want to turn the LED on.
My LED however is always ON even when none of the switches are pushed.
Why could this happen?
Thanks!
https://www.tinkercad.com/things/7SRoEXkHRqh-one-led-two-switches-

It's hard to tell which pins of the switch do what. Since you have your inputs set up as INPUT (instead of INPUT_PULLUP) you should have a resistor (10k Ω, say) tying those pins to ground. Then the other end of switch should connect to +5V. Don't connect the switches to both +5V and ground.
Use a multimeter on continuity to make sure that the pins of the switch that you are using are open normally, and close when you press the switch. With 4 pins it's easy to get confused as to which switch pin does what.


Timer for Control Motor using Limit Switch Im not good in arduino, but I have project that control motor using limit switch.

The rule is:

When switch OFF, motor ON
When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)
After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the millis() function, like in the BlinkWithoutDelay example of the Arduino IDE (You should really try it and understand how it works). The millis() function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).

Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:

boolean state=true; // on by default
unsigned long timestamp=0;

void loop(){
  if(switch_on() && state){
    state=false;
    // switch off the motor here
    timestamp = millis();
  }
  if(switch_off()){
    state=true;
  }
  if(!state && millis()-timestamp > INTERVAL){
    //switch on the motor here
  }
}

Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.


HMC5883L - Tilt compensation without Accelerometer Trying to get an HMC5883L to compensate for being installed in 90 degrees. Doesn't seem to me that it'll need too complex math or accelerometer. But I have no idea how to do the compensation for it. Any idea?

Using the Adafruit HMC5883L and its library.

You can always use the normal tilt compensation equations with a fixed value instead of a calculation from the accelerometer; Since you know the rotation beforehand the equations may not be as complex. For example, if the tilt is only on one axis, it's just one rotation matrix multiply (and you don't need to calculate the result z axis) instead of 3 in general.

If the tilt is constant and exactly 90 degrees, You just need to swap which magnetometer axis are put into the magnetic field angle equations. If one axis is pointed towards the center of the earth, you can use the other two axis to calculate the direction of the magnetic field without an explicit rotation transformation.


Using Modbus TCP server on Arduino I have a scd30 sensor wired to an Arduino Uno. The scd30 works on the I2C protocol. I am able to read data live on the serial monitor on the Arduino IDE. I have an ethernet shield on my Arduino. I would like the Arduino to communicate with a field agent which will upload the data to the internet.

I have tried numerous modbus TCP libraries and dont seem to be getting anywhere. I can connect my arduino to the field agent but whenever it sends data I get a 0x02 exception code - Illegal data address. This is the library I'm using https://github.com/andresarmento/modbus-arduino/tree/master/libraries/ModbusIP/examples

I believe the right way to go about it is through holding registers but im not sure how to do this when using I2C. The connection is fine, the problem is the format. Any help is appreciated thanks.

/*
  Reading CO2, humidity and temperature from the SCD30
  This example prints the current CO2 level, relative humidity, and temperature in C.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>
#include <ModbusIP.h>
#include <Wire.h>
#include <Streaming.h>
#include "SparkFun_SCD30_Arduino_Library.h"

SCD30 airSensor;
//Modbus Registers Offsets (0-9999)
const int SENSOR_ISTS = 100;
//ModbusIP object
ModbusIP mb;
long ts;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.println("SCD30 Example");

 // The media access control (ethernet hardware) address for the shield
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // The IP address for the shield
    byte ip[] = { 000 , 00,0, 00  };
    byte gateway[] = { 0, 0, 0, 0 };
    byte subnet[] = { 255, 255, 255, 0 };
    //Config Modbus IP
    mb.config(mac, ip,gateway,subnet);
    // Add SWITCH_ISTS register - Use addIsts() for digital inputs
    mb.addHreg(SENSOR_ISTS);
  airSensor.begin(); //This will cause readings to occur every two seconds

}

void loop()
{

mb.task();
   mb.Hreg(SENSOR_ISTS, digitalRead(airSensor.getTemperature()));

}

The ModbusIP library expects from you that you supply the value of the register. The AirSensor library gives you that value.

Set the register value to Hreg:

mb.Hreg(SENSOR_ISTS, airSensor.getTemperature());

I tested your sketch without the sensor library and it is working. Client was my java test client I use to test access to Modbus TCP registers of my photovoltaic system.

Make sure that the client calls "0x03 - Read Holding Registers" and test address 100 and 101 because some modbus clients offsets are 1-based.


Measuring frequency of 3-wire 12V fan on Arduino Uno I am using a PC 12V fan (40x40mm), which I control speed with voltage (with adjustable power supply). I would like to measure the frequency of the fan with Arduino and read it on serial monitor.

I've googled over some results and I came across pulseIn(), which I don't quite understand. I've also used this code, which I found here, but it doesn't work for me. I've added serial.print and delay line.

My output of this program is: "0000000" etc. and nothing else.

My goal is to set the frequency of the fan to around 50-500 Hz somewhere.

int pin = 7;
unsigned long duration;

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

void loop()
{
  duration = pulseIn(pin, HIGH);
  Serial.print(duration);
  delay(1);
}

My schematics:

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

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

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

Here's some untested code:

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

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

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

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

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

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

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

unsigned long rpm = 30000000L / duration;


Using both TMRpcm and VirtualWire libs with ATmega328, despite the conflict on TIMER1 I wanted to use both TMRpcm and VirtualWire with ATmega328 in an Arduino-like board I'm making, but both libraries use TIMER1. I wanted to use each lib for the following purposes:

TMRpcm: play a WAV sound from an SD Card;
VirtualWire: to receive commands from an RF remote control.

TMRpcm Advanced Features Wiki has a section on how to use TIMER2 instead, but I couldn't get it to work. They also say:

Notes:

This is usually not the best solution.

So, before I spend any more time on this, I would like to hear what you guys have to say.
So, my question is: is there a workaround to solve this conflict on the use of TIMER1, so I can use both libs in my project?
If not, what other alternatives do I have?
My circuits for reading the SD card and driving the speaker are similar to the schematic in this Instructable: Playing Wave file using Arduino. And I'm using one of those
433MHz Receiver modules for the RF part (standard, working circuit).
Both features, the RF receiver and SD card WAV playing, work correctly, when run separately (with separate sketches).

You could edit the VirtualWire.cpp source to use Timer2 instead of Timer1. For VirtualWire 1.18 the relevant section starts on line 512 with #else // ARDUINO.

On line 515 change (uint16_t)-1 to (uint8_t)-1 since Timer2 is only 8 bit. Then change all the TCCR1A, TCCR1B, OCR1A, TIMSK1 and OCIE1A to their Timer2 equivalent (hint: swap the 1's for 2's). Line 533 should be the last. On line 778 you also need to make a change to use TIMER2_COMPA_vect for VW_TIMER_VECTOR.

I hope that it helps.


How do I use this sound sensor? I bought one of these:

There are 3 pins on it:

5V
GND
OUT

My guess is that OUT is an analogue signal that I can measure with my Arduino, am I right?

I am using the "Analogue Output" example code but I just get 5V all the time, it does not seems to change with the sound levels.

Am I doing something wrong? What am I adjusting with the blue square on the board? Should I maybe do that?

The wording on this particular eBay item is pretty poor but there are plenty of similar products with better descriptions that are photographically identical... example that make a little bit more sense.

Anyway, I don't think this gives an analog value output, the LM393 is a comparator, so I think the blue dial sets the 'threshold level' and any sounds over that level cause a logic low. i.e. it compares the audio level and the dial and when one exceeds the other it gives a signal.

The features also say "The output effective signal is low level" which is probably Chinglish for the signal is a logic low, i.e. when the sound is heard it goes to 0V rather than 5V which is what I think you were expecting.

In summary: This device is is more like a Clapper, it detects a loud noise and sends a digital low signal.

Try making a loud noise with the same setup you already have, and if not try adjusting the potentiometer by turning it, but not too far! It probably only turns 180-270º.


Capacitors, Arduinos and Saving Data In short, I have programmed and wired a speed/odometer and all is working well. However, I need to save data from the components/sensors once a power button is pressed, which has led me down the road of capacitors which seem to be the solution to my problem. Reading online about capacitors has dropped me in the deep end where I would like some help to see if I am thinking right.

I have attached a clearly very crude circuit which I need someone to confirm if I have it correct. If it's important, the whole system ran on 5v, powered by a 9v battery. Is a 5v Capacitor even the right one to use, considering that most components will not be active at the point of powering down?

OLD IMAGE: https://imgur.com/a/TTZGS1n
NEW IMAGE: https://imgur.com/a/aHRpzE4

Just tried to download the app and it's not happening for some reason, so the link(edited) will have to do, I'm sorry.

Just slapping a random capacitor across your supply is not going to work. It's far more complex than that.

Yes, a capacitor is used to store a charge, but you have to manage that charge properly or you won't get much of a chance to do anything with it.

You need to:

Ensure that the discharge voltage remains high enough to run the chip for long enough to save your data (Note: writing to EEPROM causes an increase in current)
Isolate the capacitor from the rest of the circuit so it only powers the main chip
Monitor the incoming power to know when to do the saving.

A block-diagram of your setup may look something like this:

simulate this circuit – Schematic created using CircuitLab

In that diagram R1 and R2 form a voltage divider so you can monitor the battery voltage. C1 is a big capacitor. We're talking super-cap teritory here. Rated at 9V minimum. The regulator on the Arduino is ignored. You don't want to use it.  Two external regulators are now used to power your project - one direct from the battery to run the breadboard and other external components (which will lose power immediately the battery power is removed) and the other to run the main MCU and nothing else.  The second regulator is isolated from the rest of the circuit by D1, and the capacitor's charge then can only go through that regulator to power the main MCU.

That regulator for the MCU should be a switching regulator (DC-DC, "buck" regulator).  If you use a linear ("LDO") regulator you will waste power and your capacitor will have to be two or three times bigger than otherwise.  Even better would be to have a "buck-boost" regulator that will boost the voltage up to 5V when the input voltage drops below 5V, thus giving you even more life from the capacitor.

An alternative to all this is to use the 47C16 chip (5V) or 47L16 chip (3.3V) to store your data. This is an "EERAM" chip - an EEPROM with RAM buffer and automatic saving to EEPROM at power failure. It works through I2C and needs a capacitor connected to it directly to provide the backup power while it stores the data to EEPROM.


Using a potentiometer to control number of lit pixels on an NeoPixel strip I'm working on controlling an Adafruit NeoPixel strip with an Arduino and a potentiometer. Specifically, I'm trying to use the potentiometer to control how many pixels are lit up on the strip. As I turn the potentiometer "up" (i.e., increasing the value), the number of lit-up pixels increases.

However, if I try to turn the potentiometer the other way and decrease the number of lit-up pixels, then the strip will stay at whatever the last value was.

I have a method below that's called during the 'void loop()' method that read in the potentiometer data:

void readAndSendPotentiometerDataIfChanged(void) {
 //Read data from analog pin 2, and scale it
 int newPotentiometerValue = analogRead(A2) / 5.68;
  if (newPotentiometerValue != lastPotentiometerValue) {
      Serial.print("POT. value");
      Serial.print(newPotentiometerValue);
      lastPotentiometerValue = newPotentiometerValue;

      /* The value of "colorVal" is determined by a switch, and seems to be
         working properly */
      if (colorVal == "RED") {
        //If the value is 0, we want to clear the pixel values to white
        if (lastPotentiometerValue == 0) {
          clearPixels();
        } else {
          colorWipe(strip.Color(255, 0, 0)); // Red
        }
      } else if (colorVal == "BLUE") {
        if (lastPotentiometerValue == 0) {
          clearPixels();
        } else {
          colorWipe(strip.Color(0, 0, 255)); // Blue
        }
      }
   }
}

The method below will clear out all 180 pixels on my strip to no color (clear).

void clearPixels() {
   uint16_t clearColor = (127, 127, 127);
   strip.setPixelColor(180, clearColor);
   strip.show();
}

Here's where the pixels on the strip get set...I'm sure the problem is in the for loop below, but I haven't been able to come up with a better way to set the pixels on the strip and then turn them on:

void colorWipe(uint32_t c) {

  /* Use the value of 'lastPotentiometerValue' to determine how many pixels
   on the strip should be lit up */
  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }
   strip.show();
}

Anyone have a pointer to how I could refactor my code so that the potentiometer works in both directions, and will light up or turn off the pixels on the strip as appropriate? Thank you!

EDIT Based on Ignacio's answer, I changed my colorWipe method to this:

void colorWipe(uint32_t c) {

  for (uint16_t i = lastPotentiometerValue; lastPotentiometerValue<180; i++){
      uint16_t clearColor = (127, 127, 127);
      strip.setPixelColor(i, clearColor);
  }

  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }

   strip.show();
}

However, now no strips are lit up.

EDIT 2

The condition was wrong; below is the code that works:

void colorWipe(uint32_t c) {

  for(uint16_t i = lastPotentiometerValue; i<180; i++){
      uint16_t clearColor = (0, 0, 0);
      strip.setPixelColor(i, clearColor);
  }

  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }

   strip.show();
}

You forgot to clear every other pixel in colorWipe(). Pixels that aren't sent a color retain their previous color.


Arduino IDE Based Data Logger - Stops Running I have created a data logger that writes to a MicroSD on a user defined interval.  The data logger also has the ability to use an xBee unit to transmit the data received to a base station.

This is a link to the code and pictures of the data logger.

I use Arduino IDE for prototyping and coding.  After compiling the code, I use the temp HEX file and upload it to the boards using AVR Studio 4.

The problem I am experiencing is the data loggers will stop running after a random number of recordings.  This can be days or weeks of running before the problem is experienced. This issue rarely occurs when the logger is running in local mode, but occurs often when running with an XBee unit.

A temporary fix I have found for the problem is to add delay(10); before and after the SD card writes.  I do not know why this fixes the problem and would like to find a more appropriate solution.

This use of String is dangerous.  You are growing and shrinking the String in a loop and hoping the memory manager prevents any holes from forming:

void clockResetcheck() {

  char clkset[] = "CLKSET.TXT";
  if  (myFile.open(clkset, O_READ)) {

    uint16_t newYr;
    uint8_t  newDay;
    uint8_t  newMo;
    uint8_t  newHr;
    uint8_t  newMin;
    uint8_t  newSec;
    char data;
    String temp;
    int place = 0;

    while ((data = myFile.read()) > 0) {

    if (data == '/' || data == ':' || data == ',') {
      if (place == 0) {
        newDay = temp.toInt();
        temp = "";
      }
      if (place == 1) {
      newMo = temp.toInt();
      temp = "";
      }
      if (place == 2) {
        newYr = temp.toInt();
        temp = "";
      }
      if (place == 3) {
        newHr = temp.toInt();
        temp = "";
      }
      if (place == 4) {
        newMin = temp.toInt();
        temp = "";
      }
      if (place == 5) {
        newSec = temp.toInt();
        temp = "";
      }
      place++;
      if (place == 6) {
        myFile.close();
        break;
      }
    }
    else {
      temp = temp + data;
    }
  }
...

The line

temp = temp + data

is a danger flag.  This sort of concatenation is going to reallocate the buffer used by String to make it fit the result.  The reallocate will leave behind a hole with the previous smaller string.

String has logic to reuse the buffer if possible.  So if you start big, it should not have to reallocate.  Something like:

String temp("12345678");  // allocates the buffer at largest needed size
temp = ""; // clear out

That is a less likely to fragment memory.  You have a few other concatenates in code that are similar danger.

The best advice to long running programs I ever received:

  Stay off the heap.

You are using String inside functions.  That means that buffers are allocated and freed again and again.

A better pattern is to remove all the local String's in functions.  Instead use one global String as a temp buffer.

String g_temp("                        ");
void function1() {
   g_temp = "";
   g_temp += char
}
void functionB() {
   g_temp = "";
   // do stuff with g_temp
}

With this pattern, the allocate happens once when the program starts.  If the size is setup large enough, if will never need to reallocate.  This means your high water mark for memory use is established at the time the program starts.  You don't have to monitor for a week to see if some corner case will run out of memory.


Wifly Library that works with RN171 Does anyone know of a library that works with the WiFly-RN171?
I've tried all that I could find (WiFly, WiFlyHQ and WiFlySerial) but none of them work.

WiFly and WiFlySerial both hang on WiFly.begin().

WiFlyHQ fails to enter command mode and hence proceeds no further.

I'm using the WiFly-RN171 with an Arduino Uno and Communication Shield (XBee, Bluetooth, RFID) - XBee Shield as seen below.

Has anybody gotten this configuration to work?

I have the same configuration and it works (Arduino UNO rev3)
I used WiFlyHQ library. Just be carefull with the serial.

Serial.begin(9600);
...
if (!wifly.begin(&Serial, NULL)) {
   ...

Upload with serial select then put it on USB and then open the monitor.


Serial structure data transfer between an Arduino and a Linux PC I use the Arduino compatible chipKIT WF32 board. I want to transfer structure data between my board and a Linux PC. Can I do it like the following?

struct data d;
char *tx = (char*)d;
Serial.print(tx);

Even if the above code works, the data type size in Arduino and on Linux will vary. Is there a way to serialize the data, like Protocol Buffers on Arduino?

The following solution isn't strictly portable, but it should work as long as both ends are little-endian (most platforms).

You can use the GCC attribute packed to tell the compiler not to pad the fields like this:

struct __attribute__ ((packed)) my_struct {
  char c;
  int32_t n;
};

Then you can send your struct like this:

Serial.write((uint8_t*) a_my_struct_ptr, sizeof(my_struct));

On the receiving end you just copy the received data to a similarly packed struct. If you would rather use Python over C/C++ you can use the struct module to unserialize the data.

I just googled your product and the MIPS processor is bi-endian, but I will assume that it is configured for little-endian by default. You can try and see if ints keep their value after transmit. Also remember to use explicit size types such as int16_t, uint64_t, etc.


Any possible way to stack Motor Driver shield L293D with Xbee Shield v03 on arduino? So i am trying to stack these two shield on arduino, now the problem here is that i guess there is a conflict between the pins of arduino being used by both shields, so can anyone suggest a solution?

Read the documentation for both boards. They should list the pins used. Their associated libraries will define variables to which you can assign non-conflicting pins. Review the sample code provided as well. Usually, the sample code included setting the pins to use, even if the code only sets them to their default.

There is another possibility. I don’t think this is the case, but I’ve run into this issue with different shields. If the shields use I2C, they may need to have jumpers shorted to set an address.