Need help with a program for a button to change the display on an OLED display So I am programming an OLED display from my Arduino Uno. I am trying to have a button that switches the different words on the display. (The words are just placeholders for programs as of now.) My program has a button that changes a counter, and an if test to see what the counter is so it can display the appropriate word. The problem is, whenever I press the button, the display turns black and doesn't do anything anymore. When I start/reset the Arduino, it displays TEMPERATURE, but it should say TIME.

#include <OLED_I2C.h>

OLED  myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

//constants:
const int buttonPin = 2;

//variables:
byte oldButtonState = HIGH;
int screenNumber = 0;
byte buttonState = 0;

void setup()
{
  myOLED.begin();
  myOLED.setFont(SmallFont);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() { //myOLED.print formats with (string, text_placement,     pixel_location)
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // Test if the button is being pressed
  if (buttonState == HIGH) {
    myOLED.clrScr();
    myOLED.update();
    oldButtonState = buttonState;
    if (screenNumber != 2) {
      ++screenNumber;
    }
    else {
      screenNumber = 0;
    }
    //delay a little to avoid bouncing
    delay(200);
    }

  //Test for the screenNumber variable and change to the
  //according screen
  if (screenNumber == 0) {
    myOLED.print("TIME", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 1) {
    myOLED.print("TEMPERATURE", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 2) {
    myOLED.print("DIRECTION", CENTER, 16);
    myOLED.update();
  }
  else {
    myOLED.print("ERROR", CENTER, 16);
    myOLED.update();
  }
}

You have pinMode(buttonPin, INPUT_PULLUP); so I assume, you connected the button between pin and ground. With pull-up the pin will read HIGH if it is not grounded. If the button is pushed, grounding the button pulls it LOW. So you should test if the button is pressed with comparing to LOW.

We have this misleading idea in our heads that active is HIGH and not active is LOW. But you can see it this way:

button pushed down (low) is LOW
button not pushed is up (high) reading HIGH

I didn't see a problem in the code - but maybe I overlooked something.

Maybe your code is not the problem but your hardware. Did you make sure the input is connected to GND if it the button is not pressed?

Notes and Warnings

If the pin isn’t connected to anything, digitalRead() can return either HIGH or LOW (and this can change randomly).

https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/

I suggest you use serial to show the value of buttonState after this line

buttonState = digitalRead(buttonPin);

Maybe it is not what you expect it to be.


Microphone Data on Arduino to Wav File on RaspPi Working on an Arduino + Raspberry Pi project and hoping that this question fits into this category. I'm recording audio using a MEMS microphone on the Arduino and transmitting it over to the Pi to store in a playable file (WAV).

What I currently have setup is TCP transmission from the Arduino to the RaspPi. This part is fine and dandy for the purpose of seeing the data transmission that I am looking for.

Where my issue lies, is the audio data being recorded on the Arduino.
At the moment, I see data from my analogRead() function displaying like the following:

2035
2046
2030
2031
2044
2038
2034
2031
2034
2019
2028
2030
2024
2032
2028

My question is, what does this mean? How would I translate this, preferably on the Pi, as usable data that I can store in a WAV file?

Any libraries or hints/clues that can steer me in the right direction would be great.

Why use the arduino, when you can use the Pi directly? I would get a high quality ADC, connect the mic to it, and then make the Pi write the value from the ADC directly to file. The arduino simply isn't fast enough for good quality audio recording - the ADC is 10-bit, 9.6 khz. At best you could get a stereo 8-bit 8khz wav file. With a good ADC on the Pi, you would be able to go up to stereo, 16-bit(maybe even 24-bit), 44.1 khz. Also, the Arduino would be massively slowed down by sending the data, so the actual sample rate would be much lower.

It's difficult to answer this without seeing any code, but I will take a wild guess and assume you are not using any sort of FFT processing on the input. You could try looking into this library. Alternately, people seem to have good luck with this one too.


Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V? To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.

Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?

Your question should read:

  How do I scale a 0 to 5 V signal to -10 V to +10 V?

First write the conversion formula:

Vout = 4 * Vin - 10

Testing the formula gives the following:

Vin = 0.0 V ==> Vout = -10 V
Vin = 2.5 V ==> Vout = 0 V
Vin = 5.0 V ==> Vout = +10 V

You will need an op-amp circuit to create this function. In addition you will need a +12 and -12 V supply.

simulate this circuit – Schematic created using CircuitLab

How it works:

OA1 is an op-amp wired in an inverting summing amplifier configuration. We'll address the inversion later but for now all the answers will be "upside-down". The gain is set by -R2/R1 = -40k/10k = -4. If we feed 1 V in from the ADC we will get -4 V out.
R3 provides a negative input. The gain will be set by -R2/R3 = -40k/48k = -5/6. Since it's connected to -12 it will contribute +10 V to the output.
The actual output will be the sum of the two: in our example, +10 - 4 = 6 V.
C1 and C2 provide noise filtering for the op-amp. Place them close to the chip.

Now, what to do about the inversion? We have three choices:

Fix it in the micro controller code. Set +5 V as maximum reverse speed / torque. Set 0 V as maximum forward speed / torque.
Fix it in the servo amplifier and tell it to reverse its command signal.
Fix it in the electronics. By adding another inverting op-amp we can turn the signal the right way up.

The TL082 opamp suggested has two op-amps in the one 8-pin package.

Ref: Inverting Summing Amplifier.

Servo Enable

simulate this circuit

Delay the servo enable until the micro controller has initialised and all other functions are ready. See manual Section 3.2.3, page 73.

Note that this is a simplified relay drive schematic. You need a transistor drive and a snubbing / flyback diode around the relay so one of the small 5V relay boards would be a good solution as they are already built in. An opto-isolator would be simpler.

Ensure that safety circuits (guarding and e-stops) are correctly wired using safety-rated components (and not only, for example, the micro).

if you want to operate DC motor in both directions you need to use H-Bridge external small circuitry for that

Use relay circuit for that purpose


Macbook Pro CH340 Nano 14201 error I'm using a MacBook Pro Mojave 10.14.6 to code genuine Arduinos. Been working with multiple Uno R3s, no issue. Got a genuine Nano and get the following error: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory

The USB cable I'm using works fine with a cheap Chinese Uno clone, so there are data pins in the cable.

I followed instructions to delete the kext file, rebooted, installed CH341SER_MAC file and rebooted. Still getting the error message. I notice that others have asked this question; where are the answers? Thanks in advance.

Timekeeping isn't exact with any of the boards, though .05% - just over 7 minutes/day - doesn't sound like too high an expectation.

Restarting when you connect it to your computer is by design and doesn't indicate a fault. Opening the IDE's terminal or connecting another terminal program to a connected and running Arduino will - and is supposed to - reset it. Here is a forum discussion on how to disable the auto-reset function (Uno-specific) if you want to. Note that it involves modifying the board.

It's quite possible that this one board has a fault, though it still could be the cable. A couple of swaps should confirm it one way or the other.

I'm still not clear on where the error message,

  ser_open(): can't open device "/dev/cu.usbmodem14201"

came from, but I'm guess it's from AVRdude, the uploader application on your Mac, and still I'm wondering if the correct port is selected in the IDE's Tools | Port menu? For some reason, a USB device called "cu.usbmodem14201" is expected but not found. Since neither the Mac nor the IDE inherently knows this name - a USB device announces its name when you connect it - could this selection be left over from having previously used the genuine Arduino? Another reason to check the Ports menu. Also note that the Ports menu doesn't update its list spontaneously - only when you open it (and maybe only when you open the top-level, Tools, menu; I don't remember exactly).

Update:

  The regular Arduino at 0.5% is pretty crude, I'd pay more for a more
  accurate crystal, but I was able to develop a sketch that adjusts for
  the Arduino's inaccuracy.

You could try putting the Arduino in an "oven" - and I emphasize the quotes. This is not a heating chamber per-se but a temperature controlled chamber. If you're getting good results by adjusting the count, adding the oven should get you even better results, especially as the seasons change and if that makes enough difference where you are.


If (serial.available()) conditional statement I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()>0)

Thanks in advance!

In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.

Scenario A, it appears to me that there is no conditional statement, h

The first is a test on if available() returns a non zero value.


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

Not with any measure of accuracy, no.

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

No, it's mathematically impossible. Accelerometer returns acceleration, not velocity. You can calculate, but not measure, the velocity, as an integral of acceleration, but integral is a sum of delta values plus a constant. You can measure the delta values (the acceleration), but not the constant value, so you don't have enough data to calculate the velocity.


What are the 5V and VIN pins for? I believe I can supply the Arduino with power in three different ways:

Use USB. The design trusts the 5V to be regulated, and does not regulate it in any way.
Use a regulated power source, trusted to be 5V, and connect it to GND and 5V.
Connect an unregulated power source, eg a battery, to GND and VIN. This should be above 6.2V (since the dropout voltage is 1.2V) and preferably between 9V and 12V. There is a built-in regulator that will supply the Arduino with exactly 5V.

But can I use any of those pins to power other components. E.g. if the Arduino is powered with USB, can I use the 5V pin to power a diode? I thought I could, but the voltage is 4.70V, while the USB is 5.07V. The VIN is 4.26V btw.

Are the 5V and VIN only for powering the Arduino?

No. You can draw power from the 5v and VIN pins on the arduino. VIN is the completely unaltered input power before the regulator (it will be useless if regulated 5v is supplied directly). Outputting power is what the 5v pin is intended to be used for, not as a power input.

From the arduino website:

  5V. This pin outputs a regulated 5V from the regulator on the
  board. The board can be supplied with power either from the DC power
  jack (7 - 12V), the USB connector (5V), or the VIN pin of the board
  (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the
  regulator, and can damage your board. We don't advise it.

Usually I do is, after uploading the code to the barrel jack i give power to the barrel jack via vIn externally. that way u can power your other components directly from that source. you can go to higher voltage values too since the arduino allow up to 12v.


Arduino Pro Micro clone not recognized, flickering RX LED I have an Arduino Pro Micro clone that seems to be in some sort of reset loop. The RX LED is flickering very fast and very dim. The power LED also seems to flicker at the same frequency but has normal brightness.

The Arduino is not recognized by the PC at all anymore. It was working fine before. It doesn't matter if I try to go into the bootloader, by pressing reset twice, or not. Nothing happens. It feels like it is constantly resetting. The flickering stops if the reset pin stays connected to GND.

Another clone from the same shipment is still working fine. Both running the blink sketch. Just this one started to malfunction all of the sudden - after probing the pin I set in the blink sketch with my multimeter to see if the flashing was a success.

If your pro micro does not have a reset button, wire one between reset and ground.

Press reset twice, quickly, and immediately hit upload on the IDE.

Secondly, make sure you've downloaded and installed the Sparkfun board files for the pro micro.

It can be problem with bootloader.
You can try to burn bootloader again.

See for example:

http://angryelectron.com/how-to-update-the-bootloader-on-arduino-pro-mini-328/

Or use google


How to get a list of IPs in a LAN using NodeMcu? I'm going to create an IoT system. I use a Raspberry Pi as a MQTT broker and as a webserver. Every day, the Pi gets a new IP address, so I need to find its new IP address via ESP8266 to use this information in my code. I know that I can use a fixed IP, but I don't want to, so it is better if I can find a solution.

You should use mDNS.  Install (if it isn't already) avahi-daemon on your Raspberry.

Then check out the ESP8266mDNS library and the examples it has. Especially the mDNS-SD_Extended example, which performs a query for a service on the network.

First of all, if your Raspberry Pi acts as webserver and mqtt broker, in my opinion you should assign a fixed ip-address, either via configuration in the access point/router or via static ip.

However, if you insist on your approach you could do some hands-on method of pinging all addresses in your LAN-subnet and checking for the MAC-address of the respondents.
If the MAC-address matches to that of your Pi, you have found it.

I have not tested it myself, but this library seems to have what you need for this purpose.
After finding a responsive ip-address via ping, it tries to resolve the corresponding MAC-address using the etharp_find_addr function.

This struct field is the reference to a 6 byte character array that you can use for comparing with the Raspberry Pi's MAC address:

response.DestMacAddress->addr

Update:
If you only want to find the IP address of the Raspberry Pi, using mDNS as suggested by @Majenko is the superior choice.
If you are looking for all devices in your LAN, as your title suggests, pinging makes more sense.


Arduino I2C via USB Serial cable? An Arduino UNO is given.
I want to establish an I2C communication channel between Arduino UNO and a Linux Machine which have only USB ports available to communicate with peripherals.
Currently I can communicate with Arduino board via USB Serial cable (TXD and RXD which are on pins D0 and D1).

My question is: is there any way to use those pins as SCL/SDA to communicate via I2C with Arduino Board?

I am thinking that the only way to accomplish this is to buy an USB to I2C Adapter and connect to A4 (SDA) and A5 (SCL); but maybe I'm wrong.

I have also seen that way: https://gist.github.com/kraftb/8c0bbcc35a9778608d74. Basically to use an intermediate Arduino board.

With SoftwareI2CLibrary you can specify other pins, I haven't tested it with RX and TX.

I would recommend the USB serial interface is fast (2M baud) in perspective to that we are discussing a Arduino with a speed of 16MHz.

The Arduino contains a USB to UART adaptor (made from an ATMega16U2) which then connects to the UART pins 0/1. If you want a different protocol you will need a different adaptor that works with your desired protocol.


Sim900 error on AT command AT+HTTPINIT I want to send data to my php server using sim900 module but I am unable to initialize http service on sim900.

code:

#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(8, 9);

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

  Serial.println("Con");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // See if the SIM900 is ready
  gprsSerial.println("AT");
  delay(1000);
  toSerial();

  // SIM card inserted and unlocked?
  gprsSerial.println("AT+CPIN?");
  delay(1000);
  toSerial();

  // Is the SIM card registered?
  gprsSerial.println("AT+CREG?");
  delay(1000);
  toSerial();

  // Is GPRS attached?
  gprsSerial.println("AT+CGATT?");
  delay(1000);
  toSerial();

  // Check signal strength
  gprsSerial.println("AT+CSQ ");
  delay(1000);
  toSerial();

  // Set connection type to GPRS
  gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(2000);
  toSerial();

  // Set the APN
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"web\"");
  delay(2000);
  toSerial();

  // Enable GPRS
  gprsSerial.println("AT+SAPBR=1,1");
  delay(10000);
  toSerial();

  // Check to see if connection is correct and get your IP address
  gprsSerial.println("AT+SAPBR=2,1");
  delay(2000);
  toSerial();

}

void loop()
{
   // initialize http service
   gprsSerial.println("AT+HTTPINIT");
   delay(2000);
   toSerial();

   // set http param value
   // ToDO : send dynamic value
   gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.fohoraayo.000webhostapp.com/?lat=1111&lon=1111\"");
   delay(4000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   //gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}

output:

Config SIM900...
Done!...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 0,1

OK
AT+CGATT?

+CGATT: 1

OK
AT+CSQ

+CSQ: 31,0

OK
AT+SAPBR=3,1,"Contype","GPRS"

OK
AT+SAPBR=3,1,"APN","web"

OK
AT+SAPBR=1,1

ERROR
AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.x.x"

OK
AT+HTTPINIT

ERROR
AT+HTTPPARA="URL","http://www.fohoraayo.000webhostapp.com/?lat=AT+HTTPACTION=0

ERROR
AT+HTTPREAD

ERROR
AT+HTTPTERM

ERROR

For me, your code is working like charm. but change the

gprsSerial.begin(9600)

to

gprsSerial.begin(4800)


My Servo Won't Sweep Smoothly So I've tried this a few times and I always get the same issue. When I try to run the sweep example the servo goes round 180 degrees but only in steps. Anyone know a way to fix this?

The servo I'm using is a Tower Pro Micro Servo 9G SG90

// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

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

Video: http://vidd.me/A40

In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a decoupling cap between +5V and GND.

In your case, I would put at least 220uF; that would ensure two things:

the voltage used to control the servo never drops
the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a must-have for every electronics hobbyist (and professional as well, of course).

You can read more about decoupling capacitors on Wikipedia.

Edit:

According to @gwideman comment, it seems that using a decoupling capacitance above 10uF in a USB 2.0 device would violate USB specs and may damage the USB host controller on the computer.

I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.

It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (that should probably be the topic of a specific question); or maybe I have just been lucky all this time...

The program is faulty. 1) No servo can react to a command in 15 milliseconds. Delay should be more like 500 milliseconds (.5 seconds). 2) The for loops are not designed to work together. The 1st loop feeds a value of 181to the second loop which is designed to start with a value of 180. The 2nd loop feeds a value of -1 back to the first loop, which is designed to start with a value of 0.


I use Bluetooth to control LED,but LED can not turn off I use android to send the data to Arduino. when i send 0x02, LED turn on, and the breathing LED code are work. But when i send 0x03, it can not turn off the LED. i use UNO R3 the bluetooth is HC06

char data;
void setup()
{
  Serial.begin(9600);
  pinMode(9, OUTPUT);
}

void loop()
{

  if (Serial.available())
  {
    data = Serial.read();

  switch(data){

    case 0x02:

      for (int a = 0 ; a < 255; a=a-1){
        analogWrite(9, a);
        delay(10);
      }
      for (int a = 255; a>0; a=a-1){
        analogWrite(9, a);
        delay(10);
      }

      break;
    case 0x03 :
      digitalWrite(9, LOW);
      break;
    default:
      break;
    }
  }
}

this may be because of using digitalWrite in 0x03. Try using analogWrite(9, 0); instead.


Is it possible to supply Arduino nano with LED-stripe from 12V Arduino max amperage is 200mA with 5V supply.
But I can connect arduino with LED-stripe to one 12V 40A power supply in parallel. It gives most balanced power consumption between LED-stripe and arduino (If i understand correctly).
But, I want to control LED-stripe with arduino, and if it turn off all LED on stripe, all amperage will be directed to arduino.
Is it right? And what i must to do (than don't use 5V power supply additional).
Sorry for my worst english. Hope to your help.

I remember Answering similar question somewhere. Do not worry about Arduino sharing 12V supply with LEDs. Any supply with CE mark (I would have expected that to be standard in Russia and nearby countries) would be unlikely to spike above the means of arduinos voltage regulator.
There is a small chance that your supply may assume the consumption is too low and go to sleep, but that is rare.

I guess the question is a matter of controlling the LED strip. from the strong 40Amp I am guessing that LED strip would be longer then few CM, So transistor wont cut it
Its a question of MOSFET vs relay. MOSFETS are better if you keep switching LED's on and off a lot, few Milion times is no problem for them, however they are expensive especial if there is a high current (the 1K resistor is not necessary, just a habit to protect the output).

simulate this circuit – Schematic created using CircuitLab

Second option is a relay. its useful even on a higher load, but only gives several thousand, and in case of e-bay special like songle about a hundred switch of's(or ons). Note that many relays have two ratings in Amperes. The smaller number is for you here (DC).

simulate this circuit

Here 1K is required

Although when saying 40 ampere dont forget the rule of online shoping on power )supply, light emission etc:
50 Ebay Amperes = 60 BangGood Amperes= 80 Wish Amperes= Around 18 Real world amperes

So if your 40Amp supply is from ebay that would make it about 16Amp of long-term (more then half an hour-10 hours) running time


Controlling 10+x 5m led strips with 10+ individual analog floor switches I am looking to control around 10 (exact number TBD) non-addressable 5m led strips with an Arduino. Each led strip will be activated when a corresponding DIY analog floor switch.

The idea is to have a hallway with a number of these led strips oriented vertically from the floor to the ceiling and when somebody walks on the corresponding floor switch under the strip, the strip will light up.

I have a number of questions:

How could I have a setup that is scalable from 10 led strips and floor switches to 20? (having enough analog and digital pins)
How should I best distribute power to all the strips and for each switch? This is how I understand to setup 1 of the switches:
How do I wire the one colored non-addressable LED strips to the Arduino?

Note: I have coded before and done some soldering and simple electronics but have never used Arduino.

Thank you!

I think that the best solution for you, unless you want a simple on/off control (if you want it just go with Majenko's solution) is to use port expanders.

Maybe this can be slightly overkill, but you can think of using a MAX7313.

This IC is I2C controlled and has 16 I/O; you can configure each as input or output, and with automatic PWM generation too. This means that the uC just has to send it the value of light you want to output and it automatically keeps the LED strips at the correct duty cycle.

This way you can connect a sensor to P0, P2, P4, ... and configure them as input, then a pull-up resistor and a MOSFET to P1, P3, P5, ... and configure them as output with PWM. From the arduino, you will just have to connect two pins (SDA, SCL) and, of course, GND, then you will have the ability to control eight sensor/led pairs to one sensor. You want to extend it? Just solder another IC and assign it another address (pins AD0..2 serve for this purpose). You can set 64 different addresses, thus being able to drive 512 sensor/led pairs.

Want more? Use RGB led strips. Connect P0 to sensor, P1 to R, P2 to G, P3 to B, and with each IC you'll be able to drive four sensor/led pairs. You'll be able to drive only 256 sensor/led pairs, but they will be rainbow colored...

This solution has only one drawback: I could not find any pre-made board with the MAX7313 on ebay. So you'll have to design your own PCB and solder it. If you are not able to do this, alternatives exist.

Adafruit has a PCA9685 16-channels port expander board (and a lot of other manufacturers made this). This has also integrated PWM and a lot of addresses possible, but the PCA has only outputs (so no inputs). You will be able to arrange them in a matrix (so with the 18 pins remainig you will be able to control 81 switches).

Another alternative is the MCP23017; this has inputs and outputs, but no automatic PWM; this means that if you want turn them on and iff ok, but if you want a variable light you will have to "manually" pull the pin high or low (very heavy on the I2C network).

Other solutions using SPI may have better performances (SPI is faster than I2C), and a lot of other ICs with SPI, I2C or other serial connections exist. You just have to find out the most suitable for you

I have a number of questions:

use a transistor to turn on / off each leds. size the transistor based on the leds' voltage / current requirement.

make sure that your arduino has sufficient number of pins for the sensors + leds. if not, you can split the tasks among multiple arduinos.


Turn Arduino on with timer every 24h I'm currently working on an Arduino project that sends the charge of my car battery once a day via an ESP8266 to me. During the winter I don't drive my car, and I would like to get informed when the battery drops beyond a critical value, so I can charge it and prevent damage.

So energy efficiency is important for the project, so it doesn't discharge the battery itself. I read a lot about sleep mode, efficient drop down regulators etc. These all have in common that the voltage regulator is always running, which is not what I want.

I'm looking for some kind of "swich-on-timer circuit". It should count down 24 hours and then turn on a relay or MOSFET, which connects the voltage regulator to power and with that turns on the Arduino and the ESP8266. When the Arduino has finished with the transmission, it resets the timer, which disconnects the voltage regulator from power, and so on. Of course, the timer circuit should use only very little power.

Does anybody know a circuit like that? I searched on AliExpress with all variations of words that came to my mind, without success. Or maybe an IC which can be used (easily) to create such a circuit?

One approach would be use of a DS3231 (Precision Real Time Clock) module.  Such modules sell on Ebay for under $1.  Search for ds3231 arduino.

Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND.  As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output.  On page 13 of specs, in the Control Register section, it says:

  Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc.  Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.

The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino.  The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on.  The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs.  (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)

Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V.  See Electrical Characteristics, page 3 of specs.

you can use a timer switch. you can buy it from ebay for around 5 euros. i am using this one

https://www.ebay.com/itm/CN101-DC-12V-16A-Digital-LCD-Power-Programmable-Timer-Time-Relay-Switch-New/401190616827?hash=item5d68d2fefb:g:K3sAAOSwNRdX3ggT

i have also tried ds3231 but the arduino is on standby mode and it consume energy. this is the best solution i found


Convert ASCII output to human readable form and assign to a variable I'm reading the RFID output and I can print it to the serial monitor as human readable. But what I want is to assign that to a variable. But I'm getting the ASCII. Is there any way to convert it and get to the variable like Serial.write() do.

byte readbackblock[19];

for (int j=0 ; j<16 ; j++)//print the block contents
    {
      Serial.write (readbackblock[j]);
      cardNumber += readbackblock[j];
    }

Serial.print(cardNumber);

Serial output

read block: 1234567890123456

49505152535455565748495051525354

Any help please.

I don't think it is possible.

The Arduino is 8-bit microcontroller, and can't handle integers larger than 32-bit. The maximum value for a unsigned 32-bit integer is 4294967296. This is a smaller number than your readblock, so it wil never fit.

If you want to do this with smaller numbers, you can use these 2 function:

atoi -> convert char array to integer
atol -> convert char array to long integer


How to control 12v water pump by arduino? I have arduino uno and I've bought 12 Volt/350 GPH Seaflo Electric Bilge Pump, how to control it directly from arduino?

It's not possible to control it directly. You need relay module (better one is with opto coupler).

Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.

Although your question is somewhat vague, there are relatively simple solutions available. If all you require is on/off, you'd want to connect an SSR (Solid State Relay) into the circuit. Doing so allows a single pin on the Arduino to toggle the relay. The specifications I found for a similar model state 1 amp current draw, which far exceeds the capacity of the Arduino, but when operated by the SSR is easily within limits.

You could also use the SSR (representative item link here) and configure your program to use pulse width modulation - PWM - to control the speed of the pump if that was an objective.

Please consider to add more detail of your objective and also more detail of your experience and skill level with Arduino.


How to measure voltage with Arduino analog input I'm totally new to Arduino and to electrodynamics in general.

I'm wondering what happens if I connect my digital pin to an analog input on Arduino, and make digitalWrite and analogRead on the according pins. Here are the options I can think about:

Just connect them directly - it is not a short circuit, is it?
Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?
Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

As you see, I'm really confused now. I would highly appreciate if someone could explain in detail what is happening in all the cases, with corresponding values for the current, voltage and resistance.

You can connect digital pin to analog input directly. That's not very interesting though, since you'll only see two values from the analog input (at least theoretically).

The digital pin gives out 0 or 5 Volts. The analog pin expects 0 to 5 Volts input. The only thing that matters to the analog input is the voltage with respect to ground. That can be between 0 to 5 volts (returned as 0...1023 by analogRead function).

  Just connect them directly - it is not a short circuit, is it?

No, it's not a short circuit. In general, connecting anything to an input is not a short circuit. Connecting output to another output is potentially a short circuit.

  Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?

This makes no difference compared to connecting them directly, unless the resistor value is very high (should be hundreds of kOhms or even MOhms to see a difference, I suppose), because almost no current flows to the input.

  Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

This makes no other difference than that the resistor loads, i.e. draws current from, the digital output. If the resistor value is too small, then the digital output is unable to supply enough current so the 5 V voltage could become less than 5 V, or you could even burn the chip.

If you have a 250 ohm resistor from the digital pin to Gnd, and connect the digital pin to an analog input pin, then 20mA will flow thru the resistor to Gnd (5V/250 ohm = 20mA), while almost nothing flows into the analog input, as the max input current is 1uA per the datasheet, implying the input acts like a large resistor to Gnd: High input of 5V/.000001A = 5Meg-ohm.

I say acts because the input pin is the gate of a MOSFET, and a diode protection clamp to +5 and another to Gnd to limit the input voltage to -0.5 and Vcc+0.5V (so 5.5V with Vcc = 5V).

The diode clamps are only good for ~1mA (not shown in the data sheet, but discussed in an application note on detecting AC zero crossing), exceed that and you risk blowing the diode and/or the input pin and/or the chip (which will then feel warm or hot to the touch when it is powered up).

That's why you don't apply signals to unpowered chips - to prevent damaging the diode clamp circuits.


Arduino Uno R3 USB is not working I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is on and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.

I tried lsusb and I checked /dev/ ports. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.

I thought it was a bootloader problem, and I got a new ATmega328P chip board. It is getting power on and the LED is blinking, but the port is not mounted. I tried with lsusb and also ls /dev/ttyACM* with no result.

You could try to flash the firmware of the USB controller.

General steps for Arduino R3 are:

Put the Arduino in DFU mode (the R3 does not require soldering for that)
Flash the firmware using:

dfu-programmer atmega16u2 erase
dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
dfu-programmer atmega16u2 reset

The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).

Useful links for that:

Resetting your Uno R3's default firmware
Updating the Atmega8U2 and 16U2 on an Uno or Mega2560 using DFU

A useful search term for that is Arduino R3 DFU-programmer.

Maybe you need to "reflash" the FTDI firmware. Sorry, I'm very bad in Linux. To do this, you'll need some software and a HEX file. Check this video on YouTube:

ARDUINO- Upgrading USB FIRMWARE using FLIP

And download the arduino_usbtoserial.hex file.

If it doesn't work, and if your Arduino Uno has the ATmega328P chip as DIP, try to change the ATmega328P chip in the board. Remove this chip carefully. Put another chip in with the bootloader and test.


Reduce 5v Trinket Pro to 3.3v? Apparently these nRF24L01+ modules need 3.3v, but I've only got 5v Trinket Pros that I'm using.

How can I reduce the voltage to the RF transmitter?

Would a voltage regulator work? Specifically looking at this: http://addicore.com/product-p/165.htm

The NRF24L01+ has inputs that are 5V tolerant! So you only need to provide 3.3V on the Vcc pin of the module, which you can do by putting a voltage regulator between it, and the 5V of the Trinket. So there isn't really any need to convert the Trinket to 3.3V.

PS Remember to add some capacitors to the output of the voltage regulator, as the NRF needs a pretty stable 3.3V. Noise in the power lines can cause instability in the operation of the device.

There are 3.3V Trinkets. Anything you try to do will cost more than buying one.


my LM35 temperature sensor gives weird measurements, Board: esp32

I know my wiring is correct because I get data from the sensor, but the data is a bit weird.

At 22 celcius I get 140, even though if I do the voltage calculation (* 0.473372) it still doesn't work.

the number 0.473372... comes from taking the voltage 4.7v / 1024 * 1000 / 10

My code:

 Serial.print("temp: ");
 float temp = (analogRead(A13) * 0.473372781065088);
 Serial.println(temp);
 delay(2000);

Any answers?

ok, the problem is that i used to the wrong voltage conversion, just use:

RawValue = analogRead("your analog input pin");
Voltage = (RawValue / 2048.0) * 3300;
Serial.println(Voltage);

this should print the tempeture in celcious

try this one i have worked with lm35 using this code and circuit. i have done this thing with arduino uno but you can try it with esp32


Using Intel Galileo Ethernet Port Is it possible to use the galileo's ethernet port through arduino IDE? Or should I buy an arduino ethernet shield? Will I be able to use galileo as a server to which arduino board can send data to?

I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)
Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access to the wonderful world of BSD sockets (much more powerful than then sockets within the W5100)
Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script which changes the IP parameters at startup, but it's pretty heavy to do.

Yup - the Galileo Ethernet port works the same way as any other Arduino. For some sketch examples have a look at

  File > Examples > Ethernet


Do ultrasonic sensors sense through transparent materials? Do ultrasonic sensors sense through transparent materials?

In my case, I have to read if there's something inside a transparent acrylic bottle.

I'm assuming you mean a "normal" sensor, like this:

Ultrasonic sensors work by sending out sound waves. Obviously, sound waves don't care whether a material is transparent or opaque, so they are blocked just as easily by acrylic as by a brick wall.

Side note: If you look on the front of an ultrasonic sensor, you will notice that it is covered by a screen, not glass or plastic. This is why.

Well, you can visualize babies in a womb using ultrasonic sensors. So why should it be a problem to "hear" inside a bottle? Maybe not with the sensors you can afford, and maybe not with an arduino, but basically it is possible, even if the bottle is not transparent.

if the bottle is open, and the content is liquid, a simple approach could be implementing a kind of ultrasonic range finder. This can be done with comparatively cheap hardware.


Employing C++ code for Arduino I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:

I have written a C++ program which imports RGB data of a 24 bit bitmap (which was generated using Matlab) and now I would like to use this array (3 arrays - R,G,B) for an Arduino sketch to be used for a LED matrix project that I am working on. I am not exactly a programmer and hence had to resort to this path -- MATLAB to c++ and then Arduino, although this could be entirely done in C++ too (importing a bitmap and extracting pixel info). So, my C++ code spits out the 3 arrays and I am not sure how to get those into an Arduino sketch.

I read a lot about this and I understood this - As the Arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++? I cannot understand much of this method, hence trying to bypass this.

If anybody's got any better method, I would be really glad if you could share it. I am also looking to use the Arduino package for MATLAB to send the array directly from there using serial communication. But I just wanted to make sure I at least tried this path.

Would really appreciate if somebody could offer some help. I am quite stuck here.

Can share any other info if required.

Thanks a lot!

EDIT 1:

To clarify as Nick Gammon pointed out in the comments below. In brief steps, this is what I have done till now:

Got a 24 bit bitmap (some random image)
Extracted the RGB data for each pixel using Matlab
Have 3 arrays of (for eg.) 122X300 dimensions whose every element has values between 0-255 (8 bit) and for R,G and B colors
Want to get these 3 arrays for use in Arduino sketch for further working
Stuck here - how to do that .....
So I did this - I imported that the RGB data into 3 separate text files and made a c++ program to read those arrays assuming that I should be able to then somehow use this program in Arduino sketch.
Now I am not sure what to do....my goal would be to have these 3 arrays (CRGB arrays, FastLED) in my arduino sketch which I can control and then upload to my Due.
On googling I found that to use c++ for arduino , you need the avr compiler and make file, which I want to avoid. Tried other IDEs too, Eclipse, PlatformIO too .. ummmm ... not that successful to be honest.
as per Paul's ans- Matlab to Arduino method I have to try.
Hope I have clarified my process till now :)

EDIT 2:

C++ code for reading the above array (thought I could use the output in Arduino)

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>

const int HEIGHT = 4;

const int WIDTH = 5;

using namespace std;

int main(){

  int array_req [HEIGHT][WIDTH];

string userinputprompt, filename;

userinputprompt = "COLORDATA FILENAME: ";

cout<<userinputprompt<<endl;

getline(cin,filename);

ifstream inputfile;

inputfile.open(filename.c_str());

 for (int i = 0; i < HEIGHT; ++i)
{
  std::string tmpString;
  std::getline(inputfile, tmpString);

 std::stringstream ss(tmpString);

 for(int j=0;j < WIDTH; ++j)
  {
    ss >> array_req[i][j];
  }
 }

    for(int p=0; p<HEIGHT; p++)
    {
      for(int q=0; q<WIDTH; q++)
    {
        cout<<array_req[p][q]<<" ";
    }
    cout<<"\n";
}

inputfile.close();
getchar();
return 0;

}

Here's a sample program you could use as reference, just replace the values in the array and adjust VALUES_NUMBER accordingly.

Disclaimer: I didn't try to compile/run it, but it should give you an idea of how to use the values you already have.

// These are Arduino Pins that support "analog" output.
const unsigned short ANALOG_RED_PIN = 3;
const unsigned short ANALOG_GREEN_PIN = 5;
const unsigned short ANALOG_BLUE_PIN = 6;

const unsigned int VALUES_NUMBER = 12;

const unsigned short REDS[VALUES_NUMBER] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
};

const unsigned short GREENS[VALUES_NUMBER] = {
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05
};

const unsigned short BLUES[VALUES_NUMBER] = {
  0x09, 0x0A, 0x0B, 0x03, 0x04, 0x05,
  0x00, 0x01, 0x02, 0x06, 0x07, 0x08
};

void setup() {
  pinMode(analogRed, OUTPUT);
  pinMode(analogGreen, OUTPUT);
  pinMode(analogBlue, OUTPUT);
}

void loop() {
  unsigned int counter;
  for (counter = 0; counter < VALUES_NUMBER; counter++) {
    analogWrite(ANALOG_RED_PIN, REDS[counter]);
    analogWrite(ANALOG_GREEN_PIN, GREENS[counter]);
    analogWrite(ANALOG_BLUE_PIN, BLUES[counter]);
    delay(1000); //sleep 1 second
  }
}

Use the Visual Studio free community edition (or the paid versions if you already have them) with the Visual Micro extension for Arduino. Makes life a lot easier since you have indicated your desire to write in C++, and you get true debugging and intellisense as well, which you DO NOT get with the aforementioned IDE's.


Controlling 5V PWM Fan with Potentiometer Alright so I wanted to make myself a Deskfan using Arduino and a potentiometer. The reason for using arduino is that I want to display the current temperatur and the fan speed either through rpm or with %. Currently it seems to work fine using the potentiometer to control the pwm. But either i'm just not believing that it works correctly or it really isn't. My only problem is that I think the fan is not outputting 100% of its power with the pwm signal. Maybe about a few % less. But I don't really know if there is something that I am missing or if it really is outputting 100%.  The fan in question would be a Noctua NF-A14 5V PWM (+-1500 MAX).

Edit: Is it possible  that I'm not using full 100% of the fan?
 If so what would I need to change if that were the case. I heard something about changing to 25khz pwm but yeah..

Here is my code without the lcd stuff.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(9, OUTPUT);
}

void loop() {

  int potValue = analogRead(A5);

  int newpotValue = map(potValue, 0, 1023, 0, 255);
  Serial.println(newpotValue);
  analogWrite(9, newpotValue);
}

According to Your Fan Datasheet its 1.3 W/5V Fan...
That means its nearly consume 3 A current which cant be supplied directly from arduino pins...
so you have to use PWM converter ...
it almost solve your issues...


Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode This is a follow up to my previous question.

I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).

The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.

I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.

In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.

I have the following minimal(-ish) example:

#define OCIEA 1
#define CA21 1

void setup() {
  // PD3 as output
  DDRD |= (1 << PD3);

  // Pause the timers so they sync up
  GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

  // Reset timer
  TCNT2 = 0; // set timer2 to 0 (8-bit timer)

  // Enable CTC mode
  TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

  // Clear output pins on compare match
  TCCR2A |= (1 << COM2B1); // Clear OC2B on match

  // Set prescaler
  TCCR2B = (1 << CA21); // set timer 2 divisor to 8

  // Set output compare
  OCR2A = 150; // Determines TOP for Timer2

  // Determines the pulse width
  OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

  // Enable interrupts for timer 2
  TIMSK2 = (1 << OCIEA);

  // Set the timers going again
  GTCCR = 0; // release all timers
}

ISR(TIMER2_COMPA_vect)
{
  TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
  DDRD |= (1 << PD3); // Enable output
  PORTD |= (1 << PD3); // Output high
  TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
}

void loop() {

}

Ideally the ISR would just consist of PORTD |= (1 << PD3); but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.

Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).

Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?

I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.

The PWM modes manage pin at both ends of the cycle.

The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.

To manage both ends explicitly, you use normal mode.

To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:

ISR(TIMER2_COMPA_vect)
{
  TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
  TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
  TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
}

Arduino pre-configures as

  TCCR2A = (1 << WGM20);

  TCCR2B = (1 << WGM22);

  thus
  Initially reset the register

      TCCR2A=0;//reset the register

      TCCR2B=0;//reset the register


Why doesn't my 7 segment update every second like in the program? I used sevseg.h library to write numbers to my 4 digit seven segment. The display should update every second with the current time since program started running. This is my code so far:

#include <SevSeg.h>

SevSeg sevseg;

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
}

void loop() {
    unsigned long timer = millis();
    for (int i = 0; i < 500; i++) {
        sevseg.setNumber(timer/1000, -1);
        sevseg.refreshDisplay();
        delay(2);
    }
}

Since the delay is 2, the for loop loops 500 times, resulting in 1000ms or 1 second. The current second is written to the display. For some reason, the display is updated every other 5 or 6 seconds. Why is this occurring? How can this be fixed so that my display turns into a stopwatch in a way?

This is the code that fixed the issue:

  #include <SevSeg.h>
  SevSeg sevseg;

  void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
  }

  void loop() {
    unsigned long timerGlobal = millis();
    sevseg.setNumber(timerGlobal/1000, -1);
    sevseg.refreshDisplay();
  }

In this, no delays are needed. millis is divided by 1000 and the integer second is drawn on the display. Proved to be much easier than I previously thought.

On SevSeg.h Arduino Page, It says:

  Your program must run the refreshDisplay() function repeatedly to
  display the number.

I think that's the Problem. You are calling it just once and then your the number is changed.

Plus, you are saying it must get updated after One Second, but I think in your code, its being updated ever other 2 milisecond (WOW).

What I suggest is that you add a delay() for one second and then call sevseg.refreshDisplay(); several times in a for loop. You also need to change the way you measure no. of seconds elapsed.

i.e. try Something like this:

#include <SevSeg.h>
SevSeg sevseg;
void setup() {
  byte numDigits = 4;
  byte digitPins[] = {5, 4, 3, 2};
  byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(50);
  sevseg.setNumber(0000, -1);
}
unsigned long timerGlobal = millis();
void loop() {
  delay(1000);
  sevseg.setNumber( (timerGlobal - millis())/1000, -1)
  for (int i = 0; i < 50; i++) {
    sevseg.refreshDisplay();
  }
}


Simple Arduino Bluetooth Shield Android Display I need help with my Arduino code. Here is my setup:

LM35 connected to Arduino with output connected to Analog 0.

Temperature computation work and serial monitor displays the correct reading.

I want to connect via Bluetooth to an Android app to display the temperature.

It displays it a few times but 98% of the time it doesn't display it on the app. I'm thinking the problem may be in the code that I have:

#include <SoftwareSerial.h>

#define RxD 6
#define TxD 7

float temp;
int temperaturePin = 0;
float  temp1;
SoftwareSerial blueToothSerial(RxD, TxD);

void setup() {
  Serial.begin(9600);
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
}

void loop() {
  temp = analogRead(temperaturePin);
  temp1 = temp * 0.48828125;
  Serial.print(temp1);
  delay(1000);
  blueToothSerial.print(temp1);
  delay(1000);
}

I just really want to make it simple. Kindly help.

You need to terminate the string sent by adding blueToothSerial.println(""); after blueToothSerial.print(temp1);. As it is the code doesn't terminate the temperature string with an LF char, and the Android app thinks it hasn't received the full string yet.

void loop() {
  temp = analogRead(temperaturePin);
  temp1 = temp * 0.48828125;
  Serial.print(temp1);
  delay(1000);
  blueToothSerial.print(temp1);
  blueToothSerial.println("");
  delay(1000);
}

try to use Pin 1 and 2 for your bluetooth and change the code


problem uploading arduino sketch on esp8266-12e i have a new mac os sierra installed.
i just installed arduino IDE and the serial drivers for mac os x to make the serial usb port available for esp8266 device

when i try to flash the device through the IDE i have these errors:

Arduino:1.8.3 (Mac OS X), Scheda:"NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

Archiving built core (caching) in: /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_cache_169716/core/core_esp8266_esp8266_nodemcuv2_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_244c37a477ed4ef8a63952f7a6e6a50b.a
Lo sketch usa 222149 byte (21%) dello spazio disponibile per i programmi. Il massimo è 1044464 byte.
Le variabili globali usano 31524 byte (38%) di memoria dinamica, lasciando altri 50396 byte liberi per le variabili locali. Il massimo è 81920 byte.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: unslip sequence wrong
warning: espcomm_send_command: can't receive command response header
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

what can i do?

I installed another version of the driver from silabs' website and now it's working.


Using nrf24l01 with mpu 6050 unstable I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050.  Each works perfectly on its own.  However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes.

I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself.  I have not had any errors, in that all the attempts have uploaded fine.

Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ):
Changing clock rates from 24 to 12, and 400 to 200
Changing the header file for mpu from 100 hz to 20 hz and back
Adding pullup and pulldown resistors on sla/sda
Using external variable power supply to make sure exact voltage
Powering devices off arduino 3.3 and external 3.3
Running code without using serial reader on computer and just transmitting data

Edit:

After more debugging, I reduced the issue (I think).  As each module works fine independently, i thought there could be a code issue.  It seems though, that the issue is the combination of buffers.  I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer).

The second part is the wireless.  It seems like the code is looking by default for an acknowledgment the package is received.  This slows down the broadcasting.  So, if we disable the ack requirement, the gyro becomes stable.  However, the receiver stops receiving any packets at all.  If someone knows why, please explain.

So what we thought would work is by sending only some packets as the write with ack on a particular pipe.  This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem.  Again, this does not get recognized by the receiver at all.

Questions:
Does it make sense that the buffers are working against eachother, and this is not solvable through hardware.
Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?

I could not figure out what was wrong, but I changed to this library for NRF24: http://tmrh20.github.io/RF24/

and I started using the GY-85 with the FreeIMU Library : http://www.varesano.net/projects/hardware/FreeIMU

Following this advice:
http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961

It works now, so if it was SRAM as @Avamander suggested, it was not on my side.

It seems to me you are running out of memory (SRAM).  https://www.arduino.cc/en/Tutorial/Memory


Arduino Uno Digital to Analog Converter I'm trying to read in an analog signal (a heartbeat) to pin A0 on the Arduino Uno and then convert it to digital. I'm hoping to use the digital signal to make an LED light up every time the voltage of the heartbeat signal goes over 1 volt. This is the code I have right now, but something is wrong because it isn't lighting up the LED.

unsigned int analog0;             // Raw data from A0 ranging from 0 to 1023
unsigned long data_range = 2000;  // Length of time to record data for
double volts;                     // The analog data from A0 converted to volts
int ledPin = 13;
unsigned long start_time;
unsigned long data_time;

void setup() {
  Serial.begin(9600);             // Initialize and set serial port baud rate
  pinMode(ledPin , OUTPUT);
}

void loop() {
  start_time = millis();
  while ((millis() - start_time) < data_range)
  {
    // Record current time of analog acquisition
    data_time = millis();

    // Record analog data on A0
    analog0 = analogRead(0);

    // Convert raw data into voltage
    volts = (analog0 / 1023.0) * 5;

    Serial.print(volts);
    Serial.println();

    // Slow the rate of data acquisition
    //delay(1);

    if (volts > 1.5){
      digitalWrite(ledPin, HIGH);
      //delay(50);
    }
    else{
      digitalWrite(ledPin, LOW);
    }
  }
}

Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.
Edit: even better, you could try this for a faster response time:

void setup(){
  digitalWrite(13,0);
  pinMode(13, OUTPUT);
}

void loop(){
  if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
    digitalWrite(13,1);
    delay(100);
    digitalWrite(13,0);
  }
}

I think your voltage formula is wrong. Try this:

float volts = analog0 * (5.0 / 1023.0);


I2C LCD Serial Interface Board not displaying text (wrong pins?) I have a 1602 LCD screen that works fine on its own. However I wanted to free some pins by using an I2C / IIC LCD controller I purchased separately.

While the controller seems to be communicating with my Arduino UNO on the right address, I cannot get text to display. By default (no code) it seems the LCD will have 1 line of 16 solid "squares". When using address 27 in my code, the LCD will change to 2 lines of 16 squares (see photo below). The code also calls for the backlight to flash 3 times, which works. However I cannot get anything but 2 lines of squares. (Full code is at the bottom of this question).

I'm using the LiquidCrystal_I2C library by F Malpartida, which seems to be commonly used.
Is there a better library I should be using?

I'm wondering whether it's just the wrong pins being used in the code. All sketches I see online use the following pins:

//                    addr,en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// Set the LCD I2C address

But all of the 1602 LCDs I see online have the same pins as mine, as you can see in my photo below:

These pins seem to be standard:

To further confuse me, the pins on the LCD board start with 1 on the left, yet the default code's pins seem to start with 0! So I tried changing the code's pins to the numbers on the LCD board. The LCD no longer changes to 2 lines of squares and no longer blinks the backlight. I then tried subtracting 1 from each pin (to start from 0), same result. I then tried used the default pins minus 1, same result. Thus the default pins are somehow more correct?! What am I doing wrong?

Has anyone else gotten one of these I2C controllers to work for them, and if so, how?

Full code:

/* YourDuino.com Example Software Sketch
 16 character 2 line I2C Display
 Backpack Interface labelled "YwRobot Arduino LCM1602 IIC V1"
 terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
// Get the LCD I2C Library here:
// https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
#include <LiquidCrystal_I2C.h>

/*-----( Declare objects )-----*/
// set the LCD address to 0x27 for a 20 chars 2 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);  // Used to type in characters
  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------
  for(int i = 0; i< 3; i++) {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);
  }
  lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------
// NOTE: Cursor Position: (CHAR, LINE) start at 0
  lcd.setCursor(0,0); //Start at character 4 on line 0
  lcd.print("Hello, world!");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("HI!YourDuino.com");
  delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to
// Display. (Set Serial Monitor option to "No Line Ending")
  lcd.clear();
  lcd.setCursor(0,0); //Start at character 0 on line 0
  lcd.print("Use Serial Mon");
  lcd.setCursor(0,1);
  lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }
  }

}/* --(end main loop )-- */

First of all, it looks like these wires aren't properly connected:

I haven't disassembled a female jumper before, so that might not be the issue. However, it seems likely that this could be a cause.

Also, you need to adjust the contrast by turning that trimmer (the blue thing that looks kinda like it has a screw in it). LCDs will either display nothing, a washed out version of the text, or blue boxes if the contrast is not set correctly. This is probably the cause.

LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 6, 5, 7, 3, POSITIVE);  // Set the LCD

The I2C module D6->P5 is D5->P6 (inverted).


Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter) BACKGROUND

To test the capability of uploading program to ESP8266,  I use an empty program with only a blank setup function and a blank loop function. The result showed me that there are a espcomm_sync error and a espcomm_open error. Any idea to solve this problem?

HARDWARE

PIN CONNECTION

  Foca v2.2 <-> ESP8266
        TXD <-> RXD
        RXD <-> TXD
        DTR <-> RST

Arduino UNO <-> ESP8266
        GND <-> GND
       3.3V <-> Vcc

PIN DIAGRAMS

Foca v2.2

ESP8266

ON LINUX UBUNTU 15.04

ON WINDOWS 10

REFERENCE

Bring IoT to Arduino, together [Getting Started] - http://www.arduinesp.com/getting-started

by the comments I think you are not understanding correctly how to connect Reset and GPIO_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO_0 Low (GND) and then also apply Low on RST ESP pin.
To debug the things and be certain that there is no hardware problem let just start by doing these connections:

Foca v2.2 <-> ESP =1
      TXD <-> RXD
      RXD <-> TXD
      GND <-> GND
  Arduino <-> ESP 01
     3.3V <-> 3.3V
     3.3V <-> CH_PD
     GND  <-> GND

Now, with a wire, connect GPIO_0 to ground. With another wire, briefly connect RST of the ground to make ESP reset. You should be now in flash mode. Remove the connection on GPIO_0 and make it float. Now upload the code.

Note: this is basically the option C on the link you provide. If you have some buttons you can make it too:

(source: arduinesp.com)

Now, does the code upload in Arduino IDE?

If the answer is still no, try to add a small capacitor between 3.3v and ground.

If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

(source: arduinesp.com)

Any generic npn transistor should work

I had the same problem. I solved connecting GPIO0 to GND and connecting RST to GND a while after uploading and then leave it floating while uploading


Arduino Nano PWM pin not functioning I am building a project using an Arduino Nano. In it, I am using pin 3 as PWM output. However, If I supply values lower than 255 to it, the pin does not output any voltage at all.

According to this diagram, pin 3 is PWM:

I have tested it on two boards, it doesn't function on either one. It's not my sketch, either (I tested it with a simple analogWrite();).

This is the code:

void setup() {
  // put your setup code here, to run once:
  #define E1 3  // Enable Pin for motor 1
  #define E2 10  // Enable Pin for motor 2
  #define I1 4  // Control pin 1 for motor 1
  #define I2 2  // Control pin 2 for motor 1
  #define I3 A1  // Control pin 1 for motor 2
  #define I4 A0  // Control pin 2 for motor 2
}

void loop() {
  // put your main code here, to run repeatedly:
  // I use differential steering, speed is important
  analogWrite(E1, 100); // Run in full speed
  analogWrite(E2, 100); // Run in full speed

  // always go forward
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
  digitalWrite(I3, LOW);
  digitalWrite(I4, HIGH);
}

What could be the reason of this?

Try to replace #define E1 3 with #define E1 PD3 and see if that helps.

The PBx, PCx and PDx designations are unambiguous, so using those are pretty much a safe bet.

Replace digitalWrite with analogWrite(pin, value)


Is it possible to press a button from Arduino and my computer will get a key event? My idea seems easy:

I connect a button with arduino, then write some code and upload it to arduino. Then I open the notepad(or any other editor) on my computer. When I press the button, there will be a character "A" displayed in the notepad.

I have tried with my Arduino uno, and use Serial.write/print function to send an A to serial port 9600, but it seems the character A only shows in the serial monitor GUI.

My question is:

Is "Arduino uno" is OK to implement this?
If not, what other board should I use?
Is Serial.write/print the correct function?
Or shall I use the Keyboard.??? function?
Do I have to write an application which runs on the computer and listens the serial port, and emit a real key event? (that's sad)

The Uno is not the best board for this. You may be able to get somewhere with the Virtual USB project but there are a couple of boards that are better suited for this.

Those are the Arduino Leonardo, Micro, and Due. In those, you can use the Keyboard Library just like you are using the Serial library now. This page has an example very similar to your project:

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send the message
    Keyboard.print("Hello!");
  }
}

I have same problem I have build 12 buttons keypad with Arduino and it working with USB very well now I need to use bluetooth module instead of USB, but I can't find some code which will enable me to send press from Arduino to my PC.

here is my code which I need change for my bluetooth module CH-6
thank you for help.

#include <Keyboard.h>
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the kpd
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the kpd

Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

unsigned long loopCount;
unsigned long startTime;

void setup() {
    Serial.begin(9600);
    loopCount = 0;
    startTime = millis();

}

void loop() {

    loopCount++;
    if ( (millis()-startTime)>5000 ) {
        startTime = millis();
        loopCount = 0;
    }

    // Fills kpd.key[ ] array with up-to 10 active keys.
    // Returns true if there are ANY active keys.
    if (kpd.getKeys())
    {
        for (int i=0; i<LIST_MAX; i++)   // Scan the whole key list.
        {
            if ( kpd.key[i].stateChanged )   // Only find keys that have changed state.
            {
                switch (kpd.key[i].kstate) {  // Report active key state : IDLE, PRESSED, HOLD, or RELEASED
                    case PRESSED:
                    Keyboard.write(kpd.key[i].kchar);

                    //Serial.print(kpd.key[i].kchar); //active keys number
                break;
                }
            }
        }
    }
}  // End loop


Loop code without manually pressing the button In a piece off code I am modifying I have a button connected to start the code and then it resets its self afterwards. Is they a way to make the arduino loop that code without manually pressing the button again?

This is a section off the code:

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN 6
#define BUTTON_PIN 9

Adafruit_NeoPixel strip = Adafruit_NeoPixel(120, PIN, NEO_GRB + NEO_KHZ800);

bool oldState = HIGH;
int showType = 0;

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Get current button state.
  bool newState = digitalRead(BUTTON_PIN);

  // Check if state changed from high to low (button press).
  if (newState == LOW && oldState == HIGH) {
    // Short delay to debounce button.
    delay(20);
    // Check if button is still low after debounce.
    newState = digitalRead(BUTTON_PIN);
    if (newState == LOW) {
      showType++;
      if (showType > 9)
        showType=0;
      startShow(showType);
    }
  }

  // Set the last button state to the old state.
  oldState = newState;
}

void startShow(int i) {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
  resetFunc();  //call reset
}

Thanks Reece

As pointed out by Delta_G, there is no point in resetting your program.
What you should do is think your program in terms of the Arduino logic:

You put in setup() the code you want to run when your program
starts.
You put in loop() the code you want to run over and over again.

In this case loop() is fairly simple, as the stuff you want to run
over and over again is the animation, thus:

void loop() {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
}

Note that I removed the call to resetFunc().

The stuff you want to do at startup is the initialization. Oh, wait. In
a comment you wrote “I want to wait for the button press”. So this also
has to be done before the program starts looping. Hence your setup()
should initialize stuff, then wait for the button press:

void setup() {
  // Initialize the strip to all piwels off.
  strip.begin();
  strip.show();

  // Wait until the button is pressed.
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  while (digitalRead(BUTTON_PIN) == HIGH)
      ; // do nothing
}

Fairly simple.
Void loop(void) (
  Static int buttonpressed = 0. //button isn't pressed initially

If (button pressed == 0) (
    If (isbuttonpressed() == !0) button pressed = !0.
  ) else ledshow()

)

Basically it polls constantly until the button is pressed. Once the button is pressed, it ignores the button and loops to show the led.


What background do I need to have before starting Arduino? Like: basics of electrical circuits, etc..

In order to go far in Arduino and electronics.

I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.

The end result is that he is the one showing me new stuff.

In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.

Good luck

There is a good How-To for many Arduino subjects, and a good "Getting Started With Arduino" on the http://ArduinoInfo.Info site.

Another link is just "Arduino.Info"

Any suggestions/corrections/critiques welcome!


How can I handle the millis() rollover? I need to read a sensor every five minutes, but since my sketch also has
other tasks to do, I cannot just delay() between the readings. There
is the Blink without
delay tutorial
suggesting I code along these lines:

void loop()
{
    unsigned long currentMillis = millis();

    // Read the sensor when needed.
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        readSensor();
    }

    // Do other stuff...
}

The problem is that millis() is going to roll over back to zero after
roughly 49.7 days. Since my sketch is intended to run for longer
than that, I need to make sure the rollover does not make my sketch
fail. I can easily detect the rollover condition
(currentMillis < previousMillis), but I am not sure what to do then.

Thus my question: what would be the proper/simplest way to handle the
millis() rollover?

Short answer: do not try to “handle” the millis rollover, write
rollover-safe code instead. Your example code from the tutorial is fine.
If you try to detect the rollover in order to implement corrective
measures, chances are you are doing something wrong. Most Arduino
programs only have to manage events that span relatively short
durations, like debouncing a button for 50 ms, or turning a heater
on for 12 hours... Then, and even if the program is meant to run
for years at a time, the millis rollover should not be a concern.

The correct way to manage (or rather, avoid having to manage) the
rollover problem is to think of the unsigned long number returned by
millis() in terms of modular
arithmetics. For the
mathematically inclined, some familiarity with this concept is very
useful when programming. You can see the math in action in Nick Gammon's
article millis() overflow ... a bad
thing?. For the problem at hand,
what's important to know is that in modular arithmetics the numbers
“wrap around” when reaching a certain value – the modulus – so that
1 − modulus is not a negative number but 1 (think of a
12 hour clock where the modulus is 12: 1 − 12 = 1).

For those who do not want to
go through the computational details, I offer here an alternative
(hopefully simpler) way of thinking about it. It is based on the simple
distinction between instants and durations. As long as your tests
only involve comparing durations, you should be fine.

Note on micros(): Everything said here about millis() applies
equally to micros(), except for the fact that micros() rolls over
every 71.6 minutes, and the setMillis() function provided below
does not affect micros().

Instants, timestamps and durations

When dealing with time, we have to make the distinction between at least
two different concepts: instants and durations. An instant is a
point on the time axis. A duration is the length of a time interval,
i.e. the distance in time between the instants that define the start and
the end of the interval. The distinction between these concepts is not
always very sharp in everyday language. For example, if I say “I will
be back in five minutes”, then “five minutes” is the estimated
duration of my absence, whereas “in five minutes” is the instant
of my predicted coming back. Keeping the distinction in mind is
important, because it is the simplest way to entirely avoid the rollover
problem.

The return value of millis() could be interpreted as a duration: the
time elapsed from the start of the program until now. This
interpretation, however, breaks down as soon as millis overflows. It is
generally far more useful to think of millis() as returning a
timestamp, i.e. a “label” identifying a particular instant. It could
be argued that this interpretation suffers from these labels being
ambiguous, as they are reused every 49.7 days. This is, however,
seldom a problem: in most embedded applications, anything that happened
49.7 days ago is ancient history we do not care about. Thus,
recycling the old labels should not be an issue.

Do not compare timestamps

Trying to find out which among two timestamps is greater than the other
does not make sense. Example:

unsigned long t1 = millis();
delay(3000);
unsigned long t2 = millis();
if (t2 > t1) { ... }

Naively, one would expect the condition of the if () to be always
true. But it will actually be false if millis overflows during
delay(3000). Thinking of t1 and t2 as recyclable labels is the
simplest way to avoid the error: the label t1 has clearly been assigned
to an instant prior to t2, but in 49.7 days it will be reassigned
to a future instant. Thus, t1 happens both before and after t2. This
should make clear that the expression t2 > t1 makes no sense.

But, if these are mere labels, the obvious question is: how can we do
any useful time calculations with them? The answer is: by restricting
ourselves to the only two calculations that make sense for timestamps:

later_timestamp - earlier_timestamp yields a duration, namely the
amount of time elapsed between the earlier instant and the later
instant. This is the most useful arithmetic operation involving
timestamps.
timestamp ± duration yields a timestamp which is some time after
(if using +) or before (if −) the initial timestamp. Not as useful as
it sounds, since the resulting timestamp can be used in only two
kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine
across the millis rollover, at least as long as the delays involved are
shorter than 49.7 days.

Comparing durations is fine

A duration is just the amount of milliseconds elapsed during some time
interval. As long as we do not need to handle durations longer than
49.7 days, any operation that physically makes sense should also
make sense computationally. We can, for example, multiply a duration by
a frequency to get a number of periods. Or we can compare two durations
to know which one is longer. For example, here are two alternative
implementations of delay(). First, the buggy one:

void myDelay(unsigned long ms) {          // ms: duration
    unsigned long start = millis();       // start: timestamp
    unsigned long finished = start + ms;  // finished: timestamp
    for (;;) {
        unsigned long now = millis();     // now: timestamp
        if (now >= finished)              // comparing timestamps: BUG!
            return;
    }
}

And here is the correct one:

void myDelay(unsigned long ms) {              // ms: duration
    unsigned long start = millis();           // start: timestamp
    for (;;) {
        unsigned long now = millis();         // now: timestamp
        unsigned long elapsed = now - start;  // elapsed: duration
        if (elapsed >= ms)                    // comparing durations: OK
            return;
    }
}

Most C programmers would write the above loops in a terser form, like

while (millis() < start + ms) ;  // BUGGY version

and

while (millis() - start < ms) ;  // CORRECT version

Although they look deceptively similar, the timestamp/duration
distinction should make clear which one is buggy and which one is
correct.

What if I really need to compare timestamps?

Better try to avoid the situation. If it is unavoidable, there is still
hope if it is known that the respective instants are close enough:
closer than 24.85 days. Yes, our maximum manageable delay of
49.7 days just got cut in half.

The obvious solution is to convert our timestamp comparison problem into
a duration comparison problem. Say we need to know whether instant t1 is
before or after t2. We choose some reference instant in their common
past, and compare the durations from this reference until both t1 and
t2. The reference instant is obtained by subtracting a long enough
duration from either t1 or t2:

unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
unsigned long from_reference_until_t1 = t1 - reference_instant;
unsigned long from_reference_until_t2 = t2 - reference_instant;
if (from_reference_until_t1 < from_reference_until_t2)
    // t1 is before t2

This can be simplified as:

if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
    // t1 is before t2

It is tempting to simplify further into if (t1 - t2 < 0). Obviously,
this does not work, because t1 - t2, being computed as an unsigned
number, cannot be negative. This, however, although not portable, does
work:

if ((signed long)(t1 - t2) < 0)  // works with gcc
    // t1 is before t2

The keyword signed above is redundant (a plain long is always
signed), but it helps make the intent clear. Converting to a signed long
is equivalent to setting LONG_ENOUGH_DURATION equal to
24.85 days. The trick is not portable because, according to the C
standard, the result is implementation defined. But since the gcc
compiler promises to do the right
thing,
it works reliably on Arduino. If we wish to avoid implementation defined
behavior, the above signed comparison is mathematically equivalent to
this:

#include <limits.h>

if (t1 - t2 > LONG_MAX)  // too big to be believed
    // t1 is before t2

with the only problem that the comparison looks backwards. It is also
equivalent, as long as longs are 32-bits, to this single-bit test:

if ((t1 - t2) & 0x80000000)  // test the "sign" bit
    // t1 is before t2

The last three tests are actually compiled by gcc into the exact same
machine code.

How do I test my sketch against the millis rollover

If you follow the precepts above, you should be all good. If you
nevertheless want to test, add this function to your sketch:

#include <util/atomic.h>

void setMillis(unsigned long ms)
{
    extern unsigned long timer0_millis;
    ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        timer0_millis = ms;
    }
}

and you can now time-travel your program by calling
setMillis(destination). If you want it to go through the millis
overflow over and over again, like Phil Connors reliving Groundhog Day,
you can put this inside loop():

// 6-second time loop starting at rollover - 3 seconds
if (millis() - (-3000) >= 6000)
    setMillis(-3000);

The negative timestamp above (-3000) is implicitly converted by the
compiler to an unsigned long corresponding to 3000 milliseconds before
the rollover (it is converted to 4294964296).

What if I really need to track very long durations?

If you need to turn a relay on and turn it off three months later, then
you really need to track the millis overflows. There are many ways to do
so. The most straightforward solution may be to simply extend millis()
to 64 bits:

uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This is essentially counting the rollover events, and using this count
as the 32 most significant bits of a 64 bit millisecond count.
For this counting to work properly, the function needs to be called at
least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check (new_low32 < low32) fails and the code misses a count of high32. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.

Keep in mind, though, that 64 bit arithmetic is expensive on the
Arduino. It may be worth to reduce the time resolution in order to stay
at 32 bits.

Wrap the millis() in a class!

Logic:

Use id's instead of millis() directly.
Compare reversals using id's. This is clean and rollover independent.
For specific applications, to calculate exact difference between two id's, keep track of reversals and stamps. Calculate the difference.

Keeping track of reversals:

Update a local stamp periodically faster than millis(). This will help you find out if millis() has overflown.
The period of the timer determines accuracy

class Timer {

public:
    static long last_stamp;
    static long *stamps;
    static int *reversals;
    static int count;
    static int reversal_count;

    static void setup_timer() {
        // Setup Timer2 overflow to fire every 8ms (125Hz)
        //   period [sec] = (1 / f_clock [sec]) * prescale * (255-count)
        //                  (1/16000000)  * 1024 * (255-130) = .008 sec

        TCCR2B = 0x00;        // Disable Timer2 while we set it up

        TCNT2  = 130;         // Reset Timer Count  (255-130) = execute ev 125-th T/C clock
        TIFR2  = 0x00;        // Timer2 INT Flag Reg: Clear Timer Overflow Flag
        TIMSK2 = 0x01;        // Timer2 INT Reg: Timer2 Overflow Interrupt Enable
        TCCR2A = 0x00;        // Timer2 Control Reg A: Wave Gen Mode normal
        TCCR2B = 0x07;        // Timer2 Control Reg B: Timer Prescaler set to 1024

        count = 0;
        stamps = new long[50];
        reversals = new int [10];
        reversal_count =0;
    }

    static long get_stamp () {
        stamps[count++] = millis();
        return count-1;
    }

    static bool compare_stamps_by_id(int s1, int s2) {
        return s1 > s2;
    }

    static long long get_stamp_difference(int s1, int s2) {
        int no_of_reversals = 0;
        for(int j=0; j < reversal_count; j++)
        if(reversals[j] < s2 && reversals[j] > s1)
            no_of_reversals++;
        return stamps[s2]-stamps[s1] + 49.7 * 86400 * 1000;
    }

};

long Timer::last_stamp;
long *Timer::stamps;
int *Timer::reversals;
int Timer::count;
int Timer::reversal_count;

ISR(TIMER2_OVF_vect) {

    long stamp = millis();
    if(stamp < Timer::last_stamp) // reversal
        Timer::reversals[Timer::reversal_count++] = Timer::count;
    else
        ; // no reversal
    Timer::last_stamp = stamp;
    TCNT2 = 130;     // reset timer ct to 130 out of 255
    TIFR2 = 0x00;    // timer2 int flag reg: clear timer overflow flag
};

// Usage

void setup () {
    Timer::setup_timer();

    long s1 = Timer::get_stamp();
    delay(3000);
    long s2 = Timer::get_stamp();

    Timer::compare_stamps_by_id(s1, s2); // true

    Timer::get_stamp_difference(s1, s2); // return true difference, taking into account reversals
}

Timer credits.


I'm trying to control a servo with a push of a button but its not working HELP I'm new to Arduino and I'm following this tutorial: https://www.youtube.com/watch?v=T2HMJiy9b_I   but the problem is the servo just keeps moving back and forwards on it own and the button is doing nothing when pressed please help.

Code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =90;    // initial angle  for servo
int angleStep =5;
const int minAngle = 50;
const int maxAngle = 110;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Robojax Servo Button ");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }

}

This condition below is never met because a boolean comparison is implied :

if( buttonPushed ){

and buttonPushed is declared as :

int buttonPushed =0;

A proper comparison should be OK :

if( buttonPushed == 1)
{
   // Do something
}

Also the buttons need proper debouncing or the push event will have undetectable results :

https://dduino.blogspot.com/2012/03/arduino-button-debouncing.html


Link Arduino Uno to Particle Photon I'm working on a prototype with a Particle Photon, but I've realized the required number of pins is bigger than the number of pins on my photon.

I thought I could have an Arduino Uno wired to some sensors, and link the Arduino to the photon via a Software Serial from the Arduino (as its serial pins will already be busy) to the Serial pins of the photon.

Is it possible, and is there a better way to solve my problem?

If you just need to get more inputs you could use multiplexing. The multiplexing method is more robust than software serial will be. How to do this is explained here and datasheet for the commonly used cd4051 here

You don't specify what kind of sensors you will use. if the sensors are i2c or similar it is possible to daisychain (multiplex too) them.

Everything is possible, it is programming. People are doing software-only USB on AVRs.

I doubt that the effort is worth it, given how hard it is to debug such low-level code. Besides you can use on-board UART if you don't need the USB connectivity - just disable it.

Main question is - where is the main software run, aka "Who's the Brain"? If Photon, maybe you can use SPI? SPI is dead-simple to emulate in software.


SKETCH quits working after unplugging from computer Arduino Sketch program runs fine as long as it stays plugged in usb to computer. If I plug in a different power source the sketch quits working. I have plug back in usb and re-download ??? It stops working if I unplug from computer than plug right back in. I have to re down load every time.

I have ran into this problem personally. I believe that you are drawing too much power from your computer's USB port. A USB port can give 500 mA output max provides 5 Volts x 0.5 Amo = 2.5 Watts. With real world efficency losses (nominally 80~90% efficent), you can provide a Higher Voltage with Less Current, or a Lower Voltage with More Current, but you can't create powerout of nowhere.

See this post on a similar issue:
http://forum.arduino.cc/index.php?topic=289005.0

I hope this helps.


GSM dongle instead of GSM shield? I googled for this problem many times and ended up with no results, so I decided to post it here.

Can we use a GSM Dongle (usb dongle) instead of a GSM shield (like SIM900 module) to send and receive SMS in Arduino? If so how it is possible?

Not directly. The standard Arduino Uno doesn't have the hardware/software necessary to act as a USB host, which means it can't talk directly to other USB devices.

You might be able to get it work via a USB Host Shield. I don't know how compatible that is with GSM dongles though because I assume you can't install drivers on it. Additionally, if you're using a shield anyway, you might as well use a GSM shield.

If you're able to get an alternative board then another possibility might be the Arduino Yún. It has a USB host built-in which is operated by the Linux part of the board. I don't know for certain that it would handle a GSM dongle, but it may be worth looking into.

also im in the try of that.YOU HAVE TO USE USB TO SERIAL CONVERTOR CIRCUIT TO ACCESS ARDUINO BY UART (mosi....... miso) connections .and the software in the dongle is the problem here.the difference between the gsm shield and the dongle is .........the SOFTWARE  FIREWALL you have to flash the dongle by your own risk.........try this