Arduino Uno versus Arduino Nano power consumption I have both an Arduino Uno and an Arduino Nano but I can't decide which one to use for my project. My aim is to maximize battery lifetime. I have also implemented an 8-second watchdog timer to periodically sleep and wake up the ATMega328P.

Option 1: Arduino Uno R3 + DHT11 sensor: The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (Arduino Uno specification DC Current per I/O Pin 40 mA, DC Current for 3.3V Pin 50 mA).
Option 2: Arduino Nano + DHT11 sensor. The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (Arduino Nano specification: DC Current per I/O Pin: 40 mA but NO information for DC current for 3.3V or 5V).

I would like to know which one will be more power-efficient.

A Uno which isn't doing anything useful except being turned on will use about 50 mA of current from the power jack at 9V.

If you use 3 x alkaline AA batteries (giving a nominal voltage of 4.5V) directly into the 5V pin of the Arduino then you might get 2500 mAh which would be 50 hours at 50 mA per hour.

You can save a considerable amount of power by using sleep modes as I describe on my page about power. It also helps to use a bare processor (no voltage regulator, no LEDs).

I made a temperature and humidity sensor which runs from 3 x AA batteries. Using sleep mode, plus various other techniques, that is running for over a year without needing new batteries.

  I would like to know which one will be power efficient?

Both the Uno and the Nano use the same Atmega328P processor. Thus the technical considerations would be the same. Both have a voltage regulator and a "power on" LED which alone would use a lot of current, compared to everything else.

It's not that hard to make a minimal board. I have a page about doing that. Example of all you need:

If you use a deep sleep mode, combined with using the watchdog timer to wake every 8 seconds (and check the time, say every 10 times it wakes) you can reduce power consumption right down.

My temperature sensor uses an average of 42 µA which is a lot less than 50 mA. (A thousand times less). Thus your 50 hours run time becomes 50,000 hours which is 2083 days. Your batteries will probably self-discharge sooner. :)


How many WS2811 LED strips can I control with Arduino? Is there any limitation to connecting more strips?

I plan to create for my temple Ganpati Street Lighting LED Decoration - Full HD Ahmednagar Mh India

Watch this video and give me some ideas and suggestions.

There are three factors to consider when driving strings of these LEDs from an Arduino:

How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.


ESP-01 wakes up from deep sleep and then hangs I have found a number of other posts from people with the same problem but I can't find an answer.
I have a small batch of ESP-01 boards, sold by Inland, and I wish to use deep sleep mode on them.
I soldered a small copper wire from pin 8 (i.e. GPIO 16) to RST.  On one board I soldered it directly, on another I soldered pin 8 and RST to two sides of a 2 pin header so I could use  jumper in case I wanted to disconnet GPIO 16 from RST.
I am flashing the following simple code (using Arduino IDE 1.8.12), which is about the simplest test of the deep sleep mode that I can think of.
void setup()
{
   Serial.begin(74880);
   Serial.setTimeout(2000);

   while(!Serial) { }

   Serial.println(
     "I'm awake, but I'm going into deep sleep mode for 15 seconds");

   ESP.deepSleep(15e6);
}

void loop() {
}

On starting the serial monitor shows
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3664, room 16
tail 0
chksum 0xee
csum 0xee
v39c79d9b
~ld
I'm awake, but I'm going into deep sleep mode for 15 seconds

After 15 seconds the serial monitor shows
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

and nothing else. After that the thing hangs and nothing further happens.
So,  it appears that the setup runs, the serial monitor prints the message, the mc goes into deep sleep, after 15 seconds it wakes up by a reset, but doesn't go through set up again, hence doesn't print the message or go back sleep.
Here are some comments.    The problem has nothing to do with Wifi, MQTT etc, I have tried many fancy sketches using all of these, I have same problem no matter what, the above sketched is my distillation to the simplest demonstration of the deep sleep problem.
I have flashed the program with Arduino IDE, Platform IO, and esptool.py from a command line.  It doesn't make a difference.
There may be a problem with my soldering job, but I'm pretty good at soldering and SMD rework, and I have repeated the job on a number of these ESP-01 modules, inspected and tested with multimeter, etc.  all with the same outcome.
I don't see a problem with my code or IDE, I have a batch of Lolin Nodemcu boards, and this sketch works perfectly on all of those.  In that case I simply connect GPIO 16 to RST with a jumper wire, the program prints the message, sleeps for 15s, wakes up, prints it again, goes back to sleep for 15s more, etc. etc.
Are these just bad boards?  I have read some things that say the flash chips might be lousy, and if I replace those it might help? I'm tempted to trash these boards and buy some D1 mini's, but I've seen a number of posts from people who say they've had the same problem with D1 minis.   If the board is the problem, are there any recommendations for manufacturers or vendors that sell better quality?

Not necessarily an answer, but something to look at: check the Manufacturer ID of the Flash on your board.  My suspicion is that when some Flash chips come out of suspend, they're in lower drive mode than on initial power-up.  At least one person fixed his 'zombie mode' by replacing the Flash with a different vendor.  Nobody else has attempted it yet.
I have an Inland ESP-01S that's reporting MID = 0x5E (supposedly Zbit) and it comes out of Deep Sleep repeatedly.  Here's all of the Manufacturer IDs I know of or have seen:
Winbond EF
GigaDevice C8
Puya 85
Bright Moon 53
BergMicro E0
XMC 20
XTX 0B
Eon 1C
Shanghai Fundan A1
Macronix C2
Hua Hong Zhixin 68
ISSI 9D
Paragon E0 (same as Berg - oopsie or clone?)
Zbit 5E
Zetta BA
esptool.py --port /dev/ttyUSB0 flash_id   (linux)
esptool.py -p COMx flash_id    (Windoze)
Note: the cheap D1 Mini boards with no-name ESP-12F modules flooding eBay, Aliexpress and other places report XTX Flash, and they have a 5.6K pull-up on EXT_RSTB which will shorten the RST pulse from GPIO16, as well as making it hard to hit the level to be detected as a LOW due to the series 470 ohm resistor.  We're unsure whether it's the Flash or the low value pull-up (typically 10 or 12K on other boards/modules) that's causing issues with those boards.  Normally if RST isn't seen as LOW after Deep Sleep then you'll get an "ets_main.c" message at boot before it hangs.
I have a clone D1 Mini Pro that has a Flash that reports MID = EF (Winbond), although the marking on the Flash is nothing I can find on Winbond's site, only on places selling cheap Flash.  Luckily the D1 Mini Pro also exits Deep Sleep successfully.


How to generate 3 PWM signals I have 2560 mega, and I Want to generate 3-phase PWM signal at 62.5khz, synced and shifted 120 degrees apart.

I need that for 3-phase split-coil boost converter (or even isolated flyback converter), with 3 phase transformer coupled inductor. So I dont need sine wave table like here, but actually, a direct square wave PWM output, from 3 synced digital pins, with chosen duty cycle. How can I do that?

If you have any timers left, I would (regardless of the number of PWM signals and if you need different PWM frequencies) just dedicate a timer to do IRQs to manage them.

The frequency of the IRQs would then depend on how accurately you want to control the duty cycle, ref. also to the comment from Edgar Bonet .


Ultrasonic sensor and ledstrip color problem So I've made a parking sensor with the Ultrasonic sensor and a ledstrip. But the ledstrip doesn't turn yellow or green. I think it has to do with the Thresholds. Can anyone help me to set this up? I also want a longer distance greater than 1 meter. This is my code:

#include "FastLED.h"
 #include <math.h>

    #define NUM_LEDS 32
    #define BRIGHTNESS 10
    #define DATA_PIN 4

    // Define the array of leds
    CRGB leds[NUM_LEDS];

    // Module Pins
    #define trigPin 11
    #define echoPin 12

    // Thresholds (in CM)
    long SECTION_SIZE = 80;
    long STOP_DISTANCE = 60;
    long WARNING_THRESHOLD = 50;
    long MAX_THRESHOLD = 375;

    long RED_THRESHOLD = STOP_DISTANCE;
    long YELLOW_THRESHOLD = RED_THRESHOLD + SECTION_SIZE;
    long GREEN_THRESHOLD = YELLOW_THRESHOLD + SECTION_SIZE;

    const int numReadings = 5;

    int readings[numReadings];      // the readings from the analog input
    int readIndex = 0;              // the index of the current reading
    int total = 0;                  // the running total
    int average = 0;                // the average

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

      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      FastLED.setBrightness(10);

      // HC-SR04 Setup
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // initialize all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
    }

    void loop() {
      long distance, lastRun;
      bool red, yellow, green;
      total = total - readings[readIndex];
      readings[readIndex] = calculateDistance();
      total = total + readings[readIndex];

      readIndex++;
      if (readIndex >= numReadings) readIndex = 0;

      distance = abs(total / numReadings);

      yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
      red = distance <= RED_THRESHOLD;
      green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

      if (red) {
        setRed();
      } else if (yellow) {
        setYellow(distance);
      } else if (green) {
        setGreen(distance);
      } else {
        setGreenStandby();
      }

      Serial.print(distance);
      Serial.println(" cm");
      FastLED.show();
      delay(1);
    }

    void lightItUp(const CRGB& pColor, const CRGB& sColor, uint16_t travel) {
      uint16_t travelFix = travel * (NUM_LEDS/SECTION_SIZE);
      uint16_t leftStop = travelFix/2;
      uint16_t rightStop = NUM_LEDS - leftStop;
      for (int i = 0; i < NUM_LEDS; i++) {
        if (i < leftStop || i > rightStop) {
          leds[i] = pColor;
        } else {
          leds[i] = sColor;
        }
      }

      FastLED.show();
    }

    long calculateDistance() {
      long duration;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      return (duration/2) / 29.1;
    }

    void setGreenStandby() {
      return fill_solid(leds, NUM_LEDS, CRGB::Black);
    }

    void setRed() {
      return fill_solid(leds, NUM_LEDS, CRGB::Red);
    }

    void setGreen(long distance) {
      long travel = GREEN_THRESHOLD - distance;
      return lightItUp(CRGB::Yellow, CRGB::Green, travel);
    }

    void setYellow(long distance) {
      long travel = YELLOW_THRESHOLD - distance;
      return lightItUp(CRGB::Red, CRGB::Yellow, travel);
    }

I believe your mistake is in this part of your code:

  yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
  red = distance <= RED_THRESHOLD;
  green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

  if (red) {
    setRed();
  } else if (yellow) {
    setYellow(distance);
  } else if (green) {
    setGreen(distance);
  } else {
    setGreenStandby();
  }

In particular, you are defining three boolean variables independently and then switching based on their values.

Assuming you are seeing the right values output on serial monitor (like 90 cm, 60 cm, etc...), which is something I'm unsure of as I'm not getting how you are determining the distance, then the following should be easier to follow/understand:

if (distance > GREEN_THRESHOLD) {
  setGreenStandby();
} else if (distance > YELLOW_THRESHOLD) {
  setGreen(distance);
} else if (distance > RED_THRESHOLD) {
  setYellow(distance);
} else {
  setRed();
}

You have only one variable determining the led strip configuration, no need to go to 3 and then try to reduce again ;-)

Please note that your YELLOW_THRESHOLD is defined as 140, if you don't ever see a message in the serial monitor greater than that value you don't have a chance of seeing any colour other than red.... I'm asking because you mentioned I also want a longer distance greater than 1 meter that might imply your sensor is unable to go farther than 1 meter...

With the code above I'm checking the distance in a greater to smaller order: the first matching is the only one activated and it's impossible for the distance variable to match more than one condition. Generally speaking, simpler is better.


NodeMCU Arduino set PWM Frequency to specific frequency I am using NodeMCU and I program it using Arduino IDE, I need to change the PWM frequency of a port, in Arduino I used to change the frequency using timers registers like that:

TCCR1B = (TCCR1B & 0xF8) | 1 ;

How can I change the frequency of a digital pin using some function like that:

analogWriteFrequency(pin, 31250);

So that the code will looks like that:

#ifdef __AVR__
TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
#else
analogWriteFrequency(pin, 31250);
#endif
analogWrite(pin, 128) ;

Thanks.

PWM frequency is 1kHz by default. Call analogWriteFreq(new_frequency) to change the frequency.

source


Why does the LEDs affect Analog Input? So I'm working for a project to control RGB Led Strip using microphone or sound sensor with Arduino Nano. I'm using 5050 RGB Led Strip around 120 LEDs, and I control them using simple transistor circuit to each channel R, G, and B, then I connect the base of the transistors to the resistors and PWM Outputs of the Arduino. And then I'm using KY-038 Sound Sensor (I'm using the Analog Output pin) and connect it to Arduino A0.

The problem is when I didn't connect the LEDs, the microphone worked correctly. I processed the analog input, put filter and threshold. When I connected the LEDs, the reading of the A0 is disturbed by the transition of the LED (for example from 0% PWM to 50% PWM or ON). As the result, my analog read detected it as a voltage swing and recognize it as a sound, and trigger the LEDs, then oscillating without any external sound. If I disconnected the LEDs, it worked correctly, for example I change it to Arduino Built-In LED, it turned on according to the external sound.

Why does this happen? I don't think they share the same timer, and I also use proper Power Supply and Capacitor to provide the enough power.

My project is similar to this project.

I think it is because of power consumption.
If the LEDs consume lots of power, the LED on Arduino(typically mini red LED) will be off or faded.
So before you connect the  LEDs, check the  mini red LED which is on Arduino and after connection the LEDs, check ones again.
If the red LED is faded or off, the problem must be power consumption.
Connect 12v or 5v to vin to powering the Arduino, and also to LEDs
The important thing is you should not connect LEDs to Arduino 5v.


How do I supply either (1) dual voltage or (2) negative voltage? Sorry in advance if this question already exists--I tried to search but my keyword knowledge is shaky. I have created a Colpitts oscillator on breadboard using AA batteries as the power supplies. I want to implement this oscillator with an Arduino. (Once it's set up, I want to use its voltage to do some things, but that isn't part of this question.)

In the image below, I have two voltages, Vcc (positive voltage) and Vee (negative voltage). My simulations indicate I can run the oscillator either with a dual voltage (+5V and -5V), or with one negative voltage (-5V) and the other set to ground. Either provides a 100 kHz oscillation from about -5 to 2 V. So:

Is there a way to provide a dual voltage supply from the Arduino Uno?
Is there a way to provide a single negative voltage supply from the Arduino Uno?

Thanks!

You can make -5 V if you use an external power source, like in the circuit below (untested).

Connect the GND (-) from the Arduino to the +5V from the External (5V) source, than 0V will be the GND (with respect to the Arduino), but the GND of the external source will be -5V with respect to the Arduino.

I only used the resistors to get no short circuits, you can replace it by your own circuit (connecting the 5V arrow to Vcc and the -5V arrow to Vee).

simulate this circuit – Schematic created using CircuitLab


Sublime Text Compilation Issue I've tried searching for this issue but came up empty. Due to the desire to use a better IDE, I installed Sublime Text 3 and Stino. I have installed the Stino package and now have the Arduino menu inside the Sublime Text editor. I have selected the Arduino application folder appropriately. However, when I compile the simple Blink example, I'm presented with the following error. This error comes up when I attempt to compile any Arduino project. Have I forgotten to configure a setting? All videos and tutorials I've seen just follow the same steps as I have and don't seem to include any additional configuration (besides selecting the Arduino application folder).

[Stino - Start building "Blink"...]
[  3%] Creating C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o...
"C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD  -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=161 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\examples\01.Basics\Blink" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp" -o "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o"
The filename, directory name, or volume label syntax is incorrect.

[Stino - Exit with error code 1.]

As a quick update for anyone who runs into a similar issue (granted, a week later)...

I upgraded to 1.6.5 of the Arduino IDE, making sure to set my Arduino application folder appropriately, and the compilation issue has disappeared. I am able to compile and upload projects successfully.


Traffic light light system with sensors I'm trying to make a traffic light system with a ultrasonic range sensor as well as a light dependant resistor. I'm trying to make it so that the default setting is 2 seconds red light 1 second yellow 2 seconds green then 1 second yellow, this will then repeat until something else happens - I've got this working fine.

Then I want 2 different states.

One where if something comes with 10cm of the sensor then the buzzer will beep and the yellow light must blink on and off 10x with intervals of 0.1ms. When the object moves away it must then return to the default setting.

Secondly I want it when the LDR detects that the light has dropped below a level the red light will turn on and stay on until a object approaches the sensor. When an object is near the sensor it must then turn the red light off and turn the Green light on.

Here is all the code i have so far and i cant figure out why its not working.
Any help would be appreciated
Thanks

    #define ECHOPIN 3
    #define TRIGPIN 2
    float distance;
    long distancecm;

    int RED = 13;
    int YELLOW = 12;
    int GREEN = 11;

    int piezoPin = 8;

    int sensorpin = A0;
    int sensorvalue = 0;

    void setup() {
      pinMode(RED, OUTPUT);
      pinMode(YELLOW, OUTPUT);
      pinMode(GREEN, OUTPUT);
      Serial.begin(9600);
      pinMode(ECHOPIN, INPUT);
      pinMode(TRIGPIN, OUTPUT);
      }

    void distancesensor()
      {
      digitalWrite(TRIGPIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGPIN,HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGPIN,LOW);
      distance = pulseIn(ECHOPIN, HIGH);
      distancecm = distance/29.1/2;
      if (distancecm <=10);
        for (int j=1; j<=5; j=j+1)
        {
         tone(piezoPin, 1, 500);
         digitalWrite(YELLOW, HIGH);
         delay(100);
         break;
         }
    }

    void lightsensor()
      {
      sensorvalue = analogRead(sensorpin);
      if (sensorvalue > 500)
        digitalWrite(RED,HIGH);
        digitalWrite(TRIGPIN, LOW);
        delayMicroseconds(2);
        digitalWrite(TRIGPIN,HIGH);
        delayMicroseconds(10);
        digitalWrite(TRIGPIN,LOW);
        distance = pulseIn(ECHOPIN, HIGH);
        distance = distance/58;
        while (distance >10)
          digitalWrite(RED,LOW);
          digitalWrite(GREEN,HIGH);
          digitalWrite(TRIGPIN, LOW);
          delayMicroseconds(2);
          digitalWrite(TRIGPIN,HIGH);
          delayMicroseconds(10);
          digitalWrite(TRIGPIN,LOW);
          distance = pulseIn(ECHOPIN, HIGH);
          distance = distance/58;

       }

    void loop() {
      distancesensor;
      lightsensor;
      digitalWrite(RED, HIGH);          //RED ON
      delay(2000);                      //WAIT 2 SECONDS
      digitalWrite(RED, LOW);           //RED OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(YELLOW, HIGH);       //YELLOW ON
      delay(1000);                      //WAIT 1 SECOND
      digitalWrite(YELLOW, LOW);        //YELLOW OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(GREEN, HIGH);        //GREEN ON
      delay(2000);                      //WAIT 2 SECONDS
      digitalWrite(GREEN, LOW);         //GREEN OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(YELLOW, HIGH);       //YELLOW ON
      delay(1000);                      //WAIT 1 SECOND
      digitalWrite(YELLOW, LOW);        //YELLOW OFF
      delay(200);
      distancesensor;
      lightsensor;
      //REPEAT
      }

The photo of your circuit doesn't really show, how all the components are wired. For this you should either draw a schematic (which you can do with the schematic tool directly in the question editor) or provide a good visible wiring diagram like from Fritzing (though a proper schematic would be better).

For now I cannot see any wrong wiring, though you definitely should recheck it and add a proper diagram to your question.

For your code I will shortly sketch the functionality of non-blocking code and a state machine:

Non-blocking code: Task, that require a long amount of time (this means long for a microcontoller; seconds are long in this context), you should not use code, which blocks the whole program execution, until the task is completed. Instead you should only shortly check, if there is an action to be taken. If not, quickly proceed with other code. This enables you to do, which seems to be multitasking. For timed sequences you can use the millis() function. It returns the number of milliseconds since the program has started and overflows after 50 days. The following code saves the timestamp, when the LED was toggled the last time and checks, if enough milliseconds have passed since the last time. This way you can do something else in the meantime (like checking the state of your sensors). Also refer to the BlinkWithoutDelay example of the Arduino IDE.

unsigned long timestamp = 0;
unsigned long interval = 500;
...
void loop(){
  if(millis() - timestamp > interval){
    digitalWrite(led_pin, !digitalRead(led_pin));
    timestamp = millis();
  }
}

State machine: A state machine is code, that holds it's current state in a variable, thats mostly numeric. This variable is read at every loop cycle and used to determine, which piece of code is to be executed. In your case you would have states for "red light on", "yellow light on", "green light on", "distance lower than 10cm" and "LDR reports low light condition". Each on this gets it's own number. For convenience you should use an enum. Now on every loop cycle we use a switch case to go to the right code depending on the state. For your case you would set the state code with non-blocking behavior as described above. Then you only need transitions between the states, by setting the state variable.

enum STATE {STATE1, STATE2, STATE3};
STATE state = STATE1;
...
void loop(){
  switch(state){
    case STATE1:
      digitalWrite(led1_pin, HIGH);
      if(millis() - timestamp > interval){
        digitalWrite(led1_pin, LOW);
        state = STATE2;
      }
      break;
    case STATE2:
      // doing whatever this state needs to do and then do transition with setting state variable
      break;
    case STATE3:
      // doing whatever this state needs to do and then do transition with setting state variable
  }
}

For designing the states and transitions it sometimes makes sense to sketch them on paper. A bubble with a names is a state and then you connect these states with arrows.

Since you want to check the sensors in every state, you should do this outside of the switch statement. The measurement functions then do nothing else but the measurement and setting the state variable accordingly (so no digitalWrite() or delay() in there).


Shared Memory using SHM Library I am trying to read sensor data from a FIFO buffer embedded in the sensor (LSM9DS1), and store that data on a Teensy 3.2 board to later be put in a file. I can only read 6 bytes at a time from the FIFO.

The sensor's FIFO is read by the Teensy when an interrupt triggers an isr function. I want to store the data on the Teensy memory. Then, after the ISR store the memory, I plan to parse the data and do a few simple calculations in the loop() function before writing it to file.

What is the best way to accomplish this? I tried using a FIFO library for Arduino here, but it doesn't work with interrupts. I encountered errors with declaring it as a volatile memory type.

Could I used shared memory using the sys/shm.h library from C++? If so, how can I import this to my arduino code?

Shared memory only makes any sense in two combined situations:

You have a kernel arbitrating processes, threads and memory allocation, with process isolation
You have multiple threads or processes in your application

You certainly don't have number 1 unless you can install an operating system on the Teensy 3.1 (some RTOS may provide a SHM analogue).

As for 2 yes, it could be said you have two threads. But you don't have any form of process isolation, so what one "thread" can access the other "thread" can access.

Both the ISR and the loop() function have access to the exact same memory. Any global variables are accessible to both. You may need to inform the compiler that a variable is modified in one thread and read in another though. The simplest way of doing that is to make the variable volatile by prepending the volatile keyword to the definition.


What is the proper way to send data through http using sim908? Preamble:

I have a sim908 shield and I'm trying to send some data periodically to a server using AT commands.
For every command, I wait for the response to check if everything is working.
Actually the sketch works but, often, I noticed errors during http request.

State of the art:

Here it is the sequence of AT commands (not the entire code) into the loop:

1) Check the Network Registration and, if necessary, wait

AT+CREG?

2) Set params for GPRS connection (no user or password required)

AT+SAPBR=3,1,"Contype","GPRS"
AT+SAPBR=3,1,"APN","web.omnitel.it"

3) Get current bearer

AT+SAPBR=2,1

4) If bearer == 0,0,0,0 (not assigned) get a new bearer

AT+SAPBR=1,1

5) Init HTTP

AT+HTTPINIT

6) Set CID and URL

AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","www.someurl.com/service.php?p1=1&p2=2"

7) Execute the HTTP command (POST)

AT+HTTPACTION=1

8) Close HTTP connection

AT+HTTPTERM

Question:

Why HTTP init (step 5) or HTTP posting (step 7) often fails? What is wrong in this procedure? I'm missing something? There is a way to make the procedure more stable?

Thank you in advance :)

Important update:

If occurs an error during sending data via HTTP, is a great idea to renew the bearer (step 4)

Answers to the comments:

a) Shield has an antenna and it works. If I try to disconnect the antenna, code still  search the network (step 1) untill I reconnect the antenna.

b) Some times I have this error initializing HTTP (step 5):

  AT+HTTPINIT

  +CME ERROR: 3

Some times I have only "OK" as response posting data (step 7) instead of:

  +HTTPACTION:1,200,xxx

Or this response:

  +HTTPACTION:1,600,0

c) I have error at step 4 (AT+SAPBR=1,1) only if I execute the command when I have yet a bearer. The error in this case is:

  AT+SAPBR=1,1

  +CME ERROR: 3

For this reason I do a check (step 3)

You mention two different error messages.

1. AT+HTTPINIT fail

You get +CME ERROR 3. Which means "operation not allowed".

This can be due to an improperly closed HTTP setup.
If you get this error (or just always do before setting up), call AT+HTTPTERM to be sure that it's closed.

2. AT+HTTPACTION=1

I notice you're trying to do a POSTmessage, while your variables are in the URL (which is GET style afaik).

I've found a source that states you need to call AT+HTTPDATA with apropriate values.

  Tell the module that you will be sending 192 bytes of data and it can timeout after 10 seconds of inactivity.

After that, the device will say DOWNLOAD, and you can send the POST body.

  After this command you get the DOWNLOAD URC then you can type in 192 bytes of data within 10 seconds. The typed data is filled in a local buffer of the module and is not yet posted to the server. In the post body is the multi part form data which contains the necessary headers and data to post a file with name data.txt with 10 bytes of data.
  AT+HTTPDATA=192,10000

And after that you can send the POST message.

  Execute the HTTP POST command so that the buffer contents are POST to
  the server AT+HTTPACTION=1 OK

You will get a return message that states the HTTP code (200 'OK') and the amount of bytes received in the return message.

  +HTTPACTION:1,200,141
  This URC means that the data was successfully posted to the server and received 141 bytes of data.
  which is the server response to your HTTP POST

You can use AT+HTTPREAD to receive these bytes.

  The below command tells the module that we want to read the received data AT+HTTPREAD The below is the data
  received from the server
  +HTTPREAD:141 Successfully dumped 0 post variables. View it at http://www.posttestserver.com/data/2015/10/07/07.41.291690063480 Post
  body was 0 chars long. OK

(Scroll a fair bit down in the source, the first part is on HTTP GET: http://www.raviyp.com/embedded/194-sim900-gprs-http-at-commands)

You could also omit this by using HTTP GET since it's somewhat easier.

If all else fails, you can set up a TCP IP connection with the GSM module and manually set up the HTTP GET/POST message.


Send AND Receive through i2c / set Arduino as master AND slave For a project I'm using 2 Arduino Uno's, where Arduino#1 (master) sends raw data to Arduino#2 (slave). The slave should receive and encrypt the data and afterwards send the encrypted data back to the master. I'm building my project from the sketch found at arduino.cc.

How can I make the slave send back data, if he's the only one listening on incoming data, should both arduinos be listening to each other, and how to achieve this?

The I2C protocol is both read and write. Master/Slave depends on who initiates the communication. Typically the master will issue a read command to the slave to retrieve the results.

Cheers!


Code for one-time execution in Arduino Question: Where do I put code if I want it to execute only once per Arduino startup?

Background: I tend to use my Arduino to perform tasks that should be executed once per power cycle.  (For example, my robot should only drive forward once every time I turn it on--more than that, and it might fall off the table.)

The standard Arduino IDE "template" consists of a loop() and a setup() function.  The setup code is run once per power cycle, and the loop is re-started every time it finishes.

I see two approaches to code "1 time tasks:"

Method 1: "Loop once"

void setup() {
  //do setup stuff
}

void loop() {
  //do task

  while(1) ; //Repeat forever, preventing function from re-starting
}

Method 2: "Setup only"

void setup() {
  //do setup stuff

  //do task
}

void loop() {
  //do nothing
}

More detailed form of question:  Is one of these methods "better" from a hardware/software sense?  (e.g. is there anything "special" about the setup function, like it can only run for so much time?)
And, if they are the same from a hardware/software perspective, is there a "best practice" or standard way of writing code for these situations in the Arduino community?

I'm kind of confused by your question. You ask where you want to put once-per-startup setup functions, and then discuss the setup function. That's what the setup function is for.

As such, one-time setup functionality goes in the setup function.

FWIW, if you look in the file that calls the setup and loop functions:

#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

For all intents and purposes, the two options are completely identical. Either way, you get a empty busy-wait loop. Frankly, I'd expect the two different options to probably emit the same machine code anyways, so the whole thing is a non-issue.

Note:
if (serialEventRun) serialEventRun(); appears to be a facility to allow you to attach a function that is called upon reception of serial data, but if you do not define a function void serialEvent(){} in your code, it will compile out completely and not be present in the produced machine code.


Using SoftwareSerial to send data to itself I'm debugging a project which includes SoftwareSerial. I'm not convinced the serial connection behaves as expected, so I came up with the following simple test:

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

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

  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i=0; i <= 10; i++){
    delay(10);
    mySerial.write(i);
  }
}

I connected pin 11 to pin 1 (arduino Uno), hence forwarding the data of the software serial connection via the default (hardware) serial connection to my computer. But no data is coming through.

Am I missing something?

If you are hoping to see the results in the serial monitor, you need to read it in and send it back (so it ends up on the USB port). Like this:

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

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

  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i = 0; i <= 10; i++) {
    delay(10);
    mySerial.println(i);

    while (Serial.available ())
      Serial.write (Serial.read ());
  }
}

Now you have to connect pin 11 to pin 0 (not pin 1) because that will now be the Serial Rx pin.

I think your method failed because with Serial active the Serial hardware was trying to drive pin 1 high (ie. idle) which was conflicting with the data from pin 11.

An alternative is to not do a Serial.begin() - which therefore does not initialize the serial hardware and it doesn't conflict any more. This also works:

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

void setup() {
  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i = 0; i <= 10; i++) {
    delay(10);
    mySerial.println(i);
  }
}

Now you connect pin 11 to pin 1 as you originally wanted.

Notice I changed your mySerial.write(i); to mySerial.println(i); so you get correct data output (numbers, not control characters).


Maintaining Arduino on Ubuntu 14.04 I used to use Arduino on Windows but I changed to Linux last week and I was wondering how to have a maintained version of the Arduino terminal:

Indeed, I'm not sure my version is quite recent:

The icon seems to have lived ages without a little lifting...

Maybe I'm wrong but it seems so when I open the "Tools" option for instance...

Furthermore I tried to copy and paste this code:

//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

int speakerPin = 9;

int length = 28; // the number of notes

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

// play the tone corresponding to the note name

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

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

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

   if (notes[i] == ' ') {

     delay(beats[i] * tempo); // rest

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   // pause between notes

   delay(tempo);

}

}

And not all of it appeared in the Arduino terminal.

If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using apt-get:

sudo apt-get update
sudo apt-get install arduino arduino-core

However, this way you get a very old version (currently 1.0.5). Obviously, it is not updated too often if at all.

If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:

sudo apt-get remove arduino arduino-core
sudo apt-get autoremove

Better way is to download and install Arduino IDE yourself. This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.

Open a terminal window (e.g. by pressing CTRL-ALT-T), and run uname -m to check if you are running 32 bit or 64 bit platform:

uname -m

See output:

x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Go to Arduino Download page on Download the Arduino Software and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.

In a terminal window extract the package and move it to your preferred location, e.g. /opt. You need sudo rights to move it to /opt. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for .ino). See the example commands below for installing the latest 32 bit version as of the time of writing to /opt.

cd ~/Downloads
tar xf arduino-1.6.7-linux32.tar.xz
sudo mv arduino-1.6.7 /opt
/opt/arduino-1.6.7/install.sh

You can also start the IDE from the terminal:

/opt/arduino-1.6.7/arduino


Multiple I2C Devices connected parallel I have two Lidar Lites, connected to one APM. I have no issue with getting data from one of them, i use the code below

#include <I2C.h>
#define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.
#define    RegisterMeasure     0x00          // Register to write to initiate ranging.
#define    MeasureValue        0x04          // Value to initiate ranging.
#define    RegisterHighLowB    0x8f          // Register to get both High and Low bytes in 1 call.

void setup(){
  Serial.begin(9600); //Opens serial connection at 9600bps.
  I2c.begin(); // Opens & joins the irc bus as master
  delay(100); // Waits to make sure everything is powered up before    sending or receiving data
  I2c.timeOut(50); // Sets a timeout to ensure no locking up of sketch if I2C communication fails
}

void loop(){
 // Write 0x04 to register 0x00
  uint8_t nackack = 100; // Setup variable to hold ACK/NACK resopnses
  while (nackack != 0){ // While NACK keep going (i.e. continue     polling until sucess message (ACK) is received )
    nackack = I2c.write(LIDARLite_ADDRESS,RegisterMeasure, MeasureValue); // Write 0x04 to 0x00
    delay(1); // Wait 1 ms to prevent overpolling
  }

  byte distanceArray[2]; // array to store distance bytes from read function

  // Read 2byte distance from register 0x8f
  nackack = 100; // Setup variable to hold ACK/NACK resopnses
  while (nackack != 0){ // While NACK keep going (i.e. continue polling until sucess message (ACK) is received )
    nackack = I2c.read(LIDARLite_ADDRESS,RegisterHighLowB, 2, distanceArray); // Read 2 Bytes from LIDAR-Lite Address and store in    array
   delay(1); // Wait 1 ms to prevent overpolling
  }
  int distance = (distanceArray[0] << 8) + distanceArray[1];  // Shift high byte [0] 8 to the left and add low byte [1] to create 16-bit int

  // Print Distance
  Serial.println(distance);
}

i can get the distance fine, now have two connected, as follows

So my noob question is how to i get data from the 2, my guess is the wiring is ok.

I am using the code from https://github.com/PulsedLight3D/LIDARLite_v2_Arduino_Library

any help would be appreciated. thanks.

Connect one at a time and run the change address sketch mentioned by Yeti.

Naturally change each one (one at a time) to different addresses (ex. 0x62, 0x64, 0x66).

  i still don't know whats the address of the 2nd one

The address is what you change it to.

Then connect them all back up again and run the I2C scanner. You should see all 3 addresses.

  documents state that address changes will be gone when i power it off

If that is true, save the address for each module in EEPROM. Then use that code to change the module address in setup.

See the address in the code you posted?

#define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.

If you don't want to save the address in EEPROM just upload three versions of the sketch with a different address in each one. Note that the address must be even (eg. 0x62, 0x64, 0x66).

But it would be very simple just to read from EEPROM in setup and keep the address in a variable rather than a #define.


How do I connect an MPU6050 sensor to an Arduino MKR WIFI 1010? I've been trying to connect an MPU6050 to my MKR WIFI 1010 following these general instructions and using the I2CDev library, but I keep running into problems.
For a while the Arduino just didn't show up as connected in the IDE when all the pins were connected, which I think I've gathered was due to a lack of pull-up resistors for the SCL/SDA pins. Adding 10 kOhm pull-up resistors helped a little (in making the Arduino visible) but it would hang when trying to upload the example sketch. 2.2 kOhm resistors seemed to do the trick, where now the example sketches (MPU6050_DMP6 or MPU6050_raw) can be uploaded. They still fail to read any actual values, however. The raw sketch gives 0 for everything, and the DMP6 sketch prints
Initializing I2C devices...
Testing device connections...
MPU6050 connection failed

Send any character to begin DMP programming and demo:
Initializing DMP...
DMP Initialization failed (code 1)

Does anyone know why the sensor still fails to give any measurements? I connect VCC and GND from the sensor to VCC (3.3V) and GND from my Arduino. SCL and SDA from the sensor are connected to VCC via 2.2 kOhm resistors and to the SCL and SDA pins of the Arduino (12 and 11). And INT from the sensor is connected to digital pin 2. (I tried this on a couple other pins like 0 and 1 since it seems from the tech specs that 2 is not an External Interrupt pin, but that didn't change anything.)
The sensor and examples worked without any extra effort on my Arduino Uno, but unfortunately I fried that with a 12V power supply by accident. I'll probably just get another Uno, but I'm curious why this didn't work, if I'm missing something about I2C or the MKR WIFI.
I'll also note that I had to add
define #BUFFER_LENGTH 64

to wire.h in order to get sketches including I2Cdev to compile (following these instructions).

The sensor was indeed broken, and I had no problems after ordering a new one.


character on 16X2 LCD is not visible properly i am using 16x2 LCD with arduino nano for my project.

when i connect arduino nano with usb power supply from pc or any mobile changer adapter then all the character on LCD is visible properly. But when i connect it with 5V regulated power to arduino nano than character on LCD is not visible properly (characters are visible and project is running fine but pixel which needs to be hidden are also little darker so it characters aren’t visible properly)

i have connected Vee pin of LCD with ground for maximum brightness.

Disconnect Vee from GND and wire it up properly with a potentiometer. It doesn't set the brightness - it sets the bias point for displaying the different pixels in the matrix.


HTTP Post not working I am wanting to POST some data from Arduino to WebService (written in .NET), intending to save some temperature data to MS SQL Server.

My code in arduino is:

void PostarDados(String dados, String chamador) {
  if (client.connect("mysite.com.br",80)) {
    client.println(chamador);
    client.println(F("Host: mysite.com.br"));
    client.println(F("Content-Type: application/x-www-form-urlencoded"));
    client.print(F("Content-Length: "));
    client.println(dados.length());
    client.println();
    client.println(dados);
  }
  if (client.connected()) client.stop();
}

When sending to Serial instead of client, I am obtaining the following text:

POST /webservice.asmx/SetValoresTempUmidade HTTP/1.1
Host: mysite.com.br
Content-Type: application/x-www-form-urlencoded
Content-Length: 39

Chave=1&Temperatura=23.30&Umidade=42.20

I have enabled HTTP POST in web.config to make HTTP POST possible (I can successfully invoke webservice from browser):

  <location path="Webservice.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
    </system.web>
  </location>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

I have also set ScriptMethod to my webservice functions:

<WebMethod()> <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Sub SetValoresTempUmidade(Chave As Integer, ByVal Temperatura As Double, ByVal Umidade As Double)
    Dim ctx As New DataClassesDataContext
    Try
        Dim A As New TBL_DADO
        A.CHAVE_INICIO = Chave
        A.DATA = Now
        A.TEMPERATURA = Temperatura
        A.UMIDADE = Umidade
        ctx.TBL_DADOs.InsertOnSubmit(A)
        ctx.SubmitChanges()
    Catch ex As Exception
    End Try
End Sub

Finally, I am trying to get some response from server using the following code (not receiving anything):

while (client.connected()) {
  while (client.available()) {
   buffer[counter++] = client.read();
  }
}

Explained that, I have two questions:

What am I doing wrong?
How could I debug this?

Using

byte server[] = {XX, XX, XX, XX}; //IP
if (client.connect(server,80)) {

instead of

if (client.connect("mysite.com.br",80)) {

worked


Arduino controlled relay for certain duration of time I am using a relay on my Arduino Uno and i want it to be on LOW for a calculated interval of time, let's say ftime=7 seconds, and after that i need it to be set as HIGH (no power through relay). My code below makes no changes to the relay state. How would that be possible? I tried to use "delay()" too (which i know that is generally a bad idea), but had no success.

 unsigned int interval = ftime*1000; //ftime in ms
do
  {
  digitalWrite(Relay1, LOW);
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Also, if i try without:

digitalWrite(Relay1, HIGH);

relay is LOW (motor running) but it never returns to HIGH obviously.

you need to update the timeElapsed variable inside the while loop:

 unsigned int interval = ftime*1000; //ftime in ms
 unsigned long startTime = millis();
do
  {
      digitalWrite(Relay1, LOW);
      timeElapsed = millis() - startTime;
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Another way is to create a state machine make startTime a global and update the logical state (and the pin) when the time is elapsed.

unsigned long startTime;
bool relayLOW = false;

void loop(){

    if(relayLOW && millis() - startTime > interval){
        digitalWrite(Relay1, HIGH);
        relayLOW = false;
    }
    if(!relayLOW){
        bool closeRelay= //decide if relay needs to be triggered
        if(closeRelay){
            startTime = millis();
            digitalWrite(Relay1, LOW);
            relayLOW = true;
        }
    }
}


Is the arduino nano 33 IOT schematic wrong? As am i was copying the schematics of the arduino nano 33 IOT from the Official arduino schematic i noticed something was wrong in the schematic, specifically in the PRTV5V component

Here is a snip on the schematic

It would seems that the pin numbering on the PRTR5V is wrong. Here are snippits from the PRTR5V Datasheet

The sample schematic does look like the same of the arduino but if you look at it using the pin number it is different.For example on the arduino schematic pin 2 is at the middle of the two diodes, while on the datasheed pin 2 is before the diodes.

Now which one should i follow? Did arduino intentionally pin it that way ?

It is correct. You are looking at the wrong datasheet.

This is the correct one:

https://assets.nexperia.com/documents/data-sheet/PRTR5V0U2X.pdf


PWM doesn't work with my sketch I have a weird problem. again. This time it's the PWM. I have used PWM before and I used to work the way I am doing it now. But now it just wont work. The Fading sketch from example works. When I compile a code with the similar code it doesn't work. Everything with respect to compilation is same.

The code that works:

int ledPin = 3;    // LED connected to digital pin 9

void setup() {
  // nothing happens in setup
}

void loop() {
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
  for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
}

The code that doesn't work.

#define FAN1 3
#define FAN2 5

void setup() {
  //EMPTY
}

void loop() {
  int speed1 = 25;
  int speed2 = 127;
  analogWrite(5, speed1);
  analogWrite(3, speed2);
  delay(10000);
}

Why doesn't the second code work?

EDIT 1:

By not working I meant No output on Second Code and Expected Output on First one. Currently I'm using ISIS for simulation and Oscilloscope to view the output along with a L239D with motors attached.

In the first code the motor starts and stops as expected, with the expected PWM Waveform.

In second code, nothing. No waveform, no motor movement.

One omission from your code which might be causing the problems is the fact that you haven't set the pinMode. You need to set the pins as OUTPUT in setup()

#efine FAN1 3
#define FAN2 5

void setup() {
    pinMode(FAN1, OUTPUT);
    pinMode(FAN2, OUTPUT);
}

void loop() {
  int speed1 = 127;
  int speed2 = 25;
  analogWrite(FAN1, speed1);
  analogWrite(FAN2, speed2);
  delay(10000);
}

I am curious to know why you declared FAN1 and FAN2, but didn't use them - I'd recommend changing the analogWrite statements to use them instead of referring to the pin numbers directly.

Also, the way you're using the pin and speed means that you're using speed2 for FAN1 and vice versa, I've switched these in my example so FAN1 and speed1 go together.


Programming ATmega328p on external board with FT232R I am making a 100W AC-DC linear power supply, for which I want to show output Voltage and Output current on LCD display. I already used shunt resistor and voltage resistor to bring both values to analog pins on my ATmega328P in DIP socket, which has an Arduino bootloader on it. I want to programm my ATmega328P on the board without taking it off everytime and putting it into Arduino UNO board to just programm it and put it back, so how can I integrate a programmer onto board?
I intend to use the FT232R ic, which I think would work more than fine for this application.
On finished product I want to have a USB connector on the case just to update/correct the software.

I suggest use ICSP(In circuit serial programming) feature of the Atmega 328 chip. Grab the .hex file from the arduino IDE and a USB ISP external programmer to write the program to the chip. Here you will have to use a 6 pin header on your custom board to take out the pins which are used to program the atmega.


Is it possible to exit a loop on the change of an input state? I would like to exit a particular loop if the state of an input changes from LOW to HIGH. This is the current loop:
void brakeFade() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
for(int j=10; j<=255; j+=1) {
  pixels.setBrightness(j);
  pixels.show();
  delay(5);

}
}
I need that loop to exit if
(digitalRead(brakeFeed) == LOW)

Changes to HIGH during the loop.

figured it out:
void brakeFade2() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
}
for(int j=10; j<=255; j+=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(j);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
  }

}


Arduino Delivering less power I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to  Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then  directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly.

I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting.

I am using following code

// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int p1 = 13;
int p2 = 12;
int p3 = 11;
int p4 = 10;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
    pinMode(p1, OUTPUT);
  pinMode(p2, OUTPUT);
  pinMode(p3, OUTPUT);
  pinMode(p4, OUTPUT);
  digitalWrite(p1, 0);
  analogWrite(p2, 0);
  analogWrite(p3, 0);
  analogWrite(p4, 0);

  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

   digitalWrite(p1, HIGH);
  analogWrite(p2, 250);
  analogWrite(p3, 255);
  analogWrite(p4, 255);

  delay(333);
}

Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max.  Eg, see table 29.1 in the Atmega328 specs.

Although some sources rate a high-speed 716 coreless dc motor at 40 mA, other sources rate it at 100 mA.  In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.

Edit: Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:

  Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.

For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries.  Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length.  As a generic designation it has been used for several different motors, some of which produce less power.  For example, in thread #1710948 on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.

Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk.  The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side.  Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.)

Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others).  On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group.  If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply.  (Again, I don't know if this will make any difference at all in how well things work.)  Refer to Table 30-1 footnotes for details.

As noted in Gerben's comment, having flyback-diodes for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.

Edit 2: Regarding “which diode, FET to use and where [to] learn about them”, electronics-tutorials.ws is an accurate and helpful presentation about FET digital circuits.  In particular, see the section called “An example of using the MOSFET as a switch”.

Which FETs to consider depends in part on your electronic-circuits fabrication skills.  Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter.  However, some people find SMD parts difficult to work with.  In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size.  (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.)  If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).

Some typical logic-level-input SMD FETs are shown in mouser.com's online catalog.  Note that in that list, RDS_on decreases a bunch as unit price increases slightly.  For example, the FDN359BN would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents < 100 mA.  Voltage drop running a 40 mA motor should be about 4 millivolts.

Some typical SMD Schottky diodes also are shown in mouser.com's online catalog.  I think even the cheapest of these would work ok.  Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.


How to use a rotary encoder on NodeMCU with Arduino code? I have a standard 5 ping rotary encoder (3 pins for encoder, 2 pins for button).
I'm trying to get a working code that manages to read the rotary encoder.

I began with the code I found here: http://bildr.org/2012/08/rotary-encoder-arduino/

My problem is that the interrup method never being called.
I read that all the GPIO pins on NodeMCU support interrupts (except D16).
Here's my code:

volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

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

  pinMode(D0, INPUT);
  pinMode(D3, INPUT);

  digitalWrite(D0, HIGH); //turn pullup resistor on
  digitalWrite(D3, HIGH); //turn pullup resistor on

  attachInterrupt(D0, handleInterrupt, CHANGE);
  attachInterrupt(D3, handleInterrupt, CHANGE);
}

void handleInterrupt() {
  int MSB = digitalRead(D0); //MSB = most significant bit
  int LSB = digitalRead(D3); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded; //store this value for next time
}

void loop() {
    Serial.print("Encoder: ");
    Serial.println(encoderValue);
    delay(1000);
}

Different RotaryEncoders work in different ways. Mine connects the two outputs sequentially to the Gnd or + inputs, depending on the rotation direction. The resultant phase changes need to be detected and decoded by the processor.
I took your code and ran it on a LoLin NodeMCU using my 5-pin RotaryEncoder.
I connected (NodeMCU to RotaryEncoder):

D0 to Clk;
D3 to DT;
GND to GND; and
3V to +.

I ran the code, and it worked: the printed value went up when I rotated it in one direction, and down when it rotated in the other. The "bounce" was terrible though - getting just a single increment or decrement for one "detent" was difficult; I typically got 2-4.
Because of my encoder, I was able to remove the two digitalWrite(..., HIGH); lines and it continued to work. Perhaps that's what your problem is? Did you connect the + input? You mention the two switch pins: perhaps there's only one switch pin, that connects to the Gnd pin?

EDIT: The code!
So I went away and wrote a RotaryEncoder polling library, rather than the interrupt code that the original question was based on. The idea is that you can poll a rotary encoder (relatively) infrequently, and stil "catch" the transitions as it rotates. Of course this won't work if you poll it too slowly - your mileage may vary!
But here are three files:

The header and library source for the RotaryEncoder module; and
An example usage of the module.

RotaryEncoder.h:
//
// RotaryEncoder.h
//
// This library manages a Keyes KY-040 Rotary Encoder by sampling the
// appropriate pins when requested. It is NOT interrupt driven, so you'll need
// to sample often.
//
// The encoder has five pins in a 0.1" row, so you can directly plug it into
// an Arduino's data-pin sockets. The sequence of pins matches the order of
// parameters in the constructor - use ascending (or descending) numbers for
// ease.
//
// If you pass in NoPin for gnd, vcc, or sw (the switch), then that parameter
// is ignored. You'll need to organise those pins yourself! Of course, NoPin is
// not valid for dt or clk.
//

#ifndef RotaryEncoder_h
#define RotaryEncoder_h

class RotaryEncoder {

public: // Typedefs and enums

   typedef byte Pin;

   typedef signed char OptPin;

   enum Pins : OptPin {
      NoPin = -1
   }; // Pins

public: // Methods

   // Define which pins to use for the various functions.
   // If Optional Pins are "NoPin", then they won't be initialised
   RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk);

   // Start RotaryEncoder with optional maxBias (call Rebias() periodically)
   void Begin(byte maxBias=1);

   // Returns true if switch is currently pressed
   bool Switch() const;

   // Returns 0 for no change, +ve for clockwise, -ve for counter-clockwise
   int Get();

   // Call this periodically to reduce the bias
   void Rebias(int delta=1);

private: // Variables

   const OptPin gndPin;

   const OptPin vccPin;

   const OptPin swPin;

   const Pin dtPin;

   const Pin clkPin;

   byte maxBias;

   byte bias;

   bool clk;

   bool dt;

}; // RotaryEncoder

#endif // RotaryEncoder_h

RotaryEncoder.cpp:
//
// RotaryEncoder.cpp
//

#include <Arduino.h>
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk) :
               gndPin(gnd),
               vccPin(vcc),
               swPin(sw),
               dtPin(dt),
               clkPin(clk),
               maxBias(1),
               bias(1),
               clk(false),
               dt(false) {
} // RotaryEncoder::RotaryEncoder(gnd, vcc, sw, dt, clk)

void RotaryEncoder::Begin(byte maxBias) {
   this->maxBias = maxBias;
   if (gndPin!=NoPin) {
      pinMode(gndPin, OUTPUT); // Let's power the device,
      digitalWrite(gndPin, LOW);  // Power -ve with 0
   } // if
   if (vccPin!=NoPin) {
      pinMode(vccPin, OUTPUT); // ,with both - and +
      digitalWrite(vccPin, HIGH); // Power +ve with 1
   } // if
   if (swPin!=NoPin) {
      pinMode(swPin, INPUT_PULLUP); // They pushed it!
   } // if
   pinMode(dtPin,  INPUT); // One half
   pinMode(clkPin, INPUT); // The other half
} // RotaryEncoder::Begin(maxBias)

bool RotaryEncoder::Switch() const {
   return swPin!=NoPin ?
          digitalRead(swPin)==LOW :
          false;
} // RotaryEncoder::Switch()

int RotaryEncoder::Get() {
   bool clkNew = digitalRead(clkPin);
   if (clk!=clkNew) {
      clk = clkNew; // Clock's changed; sample data
      bool dtNew = digitalRead(dtPin);
      if (dt!=dtNew) {
         dt = dtNew; // Data's changed; remember it!
         if (clk) {  // Only pay attention to Clk Low-High
            int temp = bias;
            bias = maxBias;
            if (dt) {
               return -temp;
            } // if
            else {
               return +temp;
            } // else
         } // if
      } // if
   } // if
   return 0;
} // RotaryEncoder::Get()

void RotaryEncoder::Rebias(int delta) {
   if (bias<=1) {
       return;
   } // if
   bias -= bias>delta ? delta : bias-1;
} // RotaryEncoder::Rebias()

RotaryBlinker.ino:
//
// RotaryBlinker
//
// This example changes how fast the built-in LED blinks by using the
// RotaryEncoder library.
// It starts with an intermediate value (80h).
// * If you rotate it left, it slows down (then it jumps to the fastest).
// * If you rotate it right, it speeds up (then it jumps to the slowest).
// The jumps are because there is no logic to handle wrap-around - an exercise
// for the reader!
//
// Also note that a bias feature has been included. The faster you turn the knob, the
// exponentially quicker the rate changes. This is done by setting a fast rate on
// every detent, then when the millisecond has changed it re-biases the knob lower.
//
// To handle the knob correctly, it needs to INCREASE the time interval when
// dialling LOWER - hence you'll see a negative number in the code.
//
// It also checks for the switch. If it's pressed, it simply turns the LED full on.
//

#include <RotaryEncoder.h>

// Choose pins that are convenient for the RotaryEncoder's pins
#if defined(ESP8266)

const byte LED = D5;                   // No built-in LED! Choose... this one!
const unsigned baud = 115200;
const RotaryEncoder::OptPin GND = -1; // Use GND pin
const RotaryEncoder::OptPin VCC = -1; // Use V+ pin
const RotaryEncoder::OptPin SW  =  D4; // Switch
const RotaryEncoder::Pin    DT  =  D3; // Data
const RotaryEncoder::Pin    CLK =  D2; // Clock

#elif defined(ADifferentBoard) // Put the board's definition here

// And then change these assignments
const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#else // Arduino Uno default

const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#endif // Boards

// Tell library which pin does what. Note Optional Pins can be -1
RotaryEncoder encoder(GND, VCC, SW, DT, CLK);

// Setup the board for these definitions
void setup() {
    Serial.begin(baud);
    pinMode(LED, OUTPUT); // Want to see it working

    encoder.Begin(10); // Start, with a re-bias of 10
} // setup()

bool ledON = false;  // Current LED state
byte repeat = 0x80;  // How quickly to restart, in ms
byte count = repeat; // Count down 'til next time!

unsigned last = 0;   // Last time millis() was recorded

void loop() {
    // Have switch override pulsing - turn it hard ON
    if (encoder.Switch()) { // Hard override!
        ledON = false; // Pretend LED is now OFF
        digitalWrite(LED, HIGH);
    } // if
    else {
        int value = encoder.Get(); // Returns positive for clockwise turn
        repeat += -value;   // We want to INCREASE time to slow down blinking
        if (value!=0) {     // Did it change?
            Serial.print(value);    // Print latest value
            Serial.print('=');
            Serial.println(repeat); // Print new result
        } // if
    } // else

    // Is it time to blink the LED again?
    unsigned latest = millis();
    if (last!=latest) {
        last = latest;
        encoder.Rebias();    // Re-bias encoder, to decelerate rotation
        if (--count==0) {    // Reached zero yet?
            ledON = !ledON;  // Yes! Toggle LED
            digitalWrite(LED, ledON ? HIGH : LOW);
            count = repeat;  // Count for next time
       } // if
    } // if
} // loop()


How to choose a transmit pin in the IRremote library for an Arduino Uno? I am looking for a way to choose a pin on the Arduino Uno. This pin will be used to send the signal of an IR LED. I am using the IRremote library.

e.g.

Below is the IR send demo which uses pulse width modulation pin 3 to send the IR signal. I want to change that pin to any other pin.

Any pointers will make me very happy thanks.

/*
 * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
 * An IR LED must be connected to Arduino PWM pin 3.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 3; i++) {
        irsend.sendSony(0xa90, 12);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

As the pin does not appear to be able to be defined when creating an object from the IRsend class, it seems as if you will have to modify the IRremote library itself.

I recently had the same problem with the USB Host library, see Change select pin of USB Host library. It is annoying when you can't define the pin(s), that a particular library uses, yourself... However, the authors of the library probably have their reasons for doing so.

Looking through the various headers of the library, I found in boarddefs.h on lines 134-138:

// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
// ATmega48, ATmega88, ATmega168, ATmega328
#else
    //#define IR_USE_TIMER1   // tx = pin 9
    #define IR_USE_TIMER2     // tx = pin 3

So, the line to change, for the Uno, would seem to be line 138 in boarddefs.h

    #define IR_USE_TIMER2     // tx = pin 3

However, it is not, as that merely states that for the Arduino Uno IR_USE_TIMER2 is used...

Looking further down to where the Timers are defined, you will see the section for Timer 2, on line 146. In that section the transmit pin, for a number of versions of the Arduino, is defined as TIMER_PWM_PIN on lines 189-197:

#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \
|| defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \
|| defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \
|| defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \
|| defined(__AVR_ATmega164P__)
#   define TIMER_PWM_PIN  14             // MightyCore
#else
#   define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc
#endif                                   // ATmega48, ATmega88, ATmega168, ATmega328

You will have to change this line in the library, Line 196 in boarddefs.h:

#   define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc

You could try changing the 3 so that you can use another pin. It might work. For example to use pin 5, en lieu of pin 3, change the 3 to a 5, like so:

#   define TIMER_PWM_PIN  5              // Arduino Duemilanove, Diecimila, LilyPad, etc

Be careful not to choose a pin that is used by something else, AND I think that the pin will need to be PWM capable.

Note that the definitions that are in boarddefs.h used to be in RemoteInt.h, in earlier versions of the library. See this comment at the very top:

// This file contains all board specific information. It was previously contained within
// IRremoteInt.h

So, make sure that you have the latest version of the IRremote library.

The above hack should also work for the Mega2560 as is uses the same timer, Timer 2, see lines 68-71:

// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //#define IR_USE_TIMER1   // tx = pin 11
    #define IR_USE_TIMER2     // tx = pin 9

Other boards are also defined in this file. If you have another type of board, the timer may be different, but the process to find which line to change would be very similar...


How many UNO pins have internal pull up resistors? As the title implies.
thank you in advance.

All of them. It's a standard feature on all IO pins in the AVR range.


Complete Bread board arduino I bought a ATmega328 microcontroller and burn the bootloader. Now I want to upload code directly from pc to the microcontroller on bread board. I have max232 ic for the communication but I recently knew that I need a serial port rather usb to connect max232 to pc. There are many usb to serial converter available on the market but can I make my own? One more thing is there any other way burn program from arduino ide to microcontroller via USB on bread board without having the arduino board. Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

There are many usb to serial converter available on the market but can I make my own?

Yes, but if you need to ask how then you're not ready to undertake the task.

  One more thing is there any other way burn program from arduino ide to microcontroller via usb on bread board without having the arduino board.

Yes. The IDE doesn't care how you connect to the MCU, only that it has the appropriate bootloader for the programming method.

  Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

ArduinoISP will let you use an existing Arduino as an AVR ISP programmer. ISP does not require a bootloader, nor does it require a serial (UART) connection.


Arduino tone frequency isn't always precise I'd like to play an asynch 'beep' sound (2.5kHz, pin 8) on an Arduino Mega with several other modules connected. I write them here, just for the record: SDCard reader and RFID reader through SPI bus, RTC through I2C, GSM module through hardware Serial 1. And I use PWM on two other pins (11,12) for controlling LEDs brightness.

It works well, however, sometimes (1 of 10) the beep frequency is about half-tone higher.

The code itself is good, because I use a constant in the tone() function call for specifying the frequency.

Does anybody have an idea what can influence the tone's PWM frequency such way, maybe on hardware level?

As far as I know, tone() implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.

Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.


Using Arduino Micro With 12V Buzzer I have an interesting situation.  I wonder if anyone can help?

I have:

4x Arduino Micros loaded with the basic Blink sketch
5x 12 volt buzzers
A desk full of completely fresh Duracell AA and 9v batteries

If I connect (using VIN and GND) any of the Arduino Micros to either a 9v battery, or a 12v network of 8 AA batteries, then they run the blink sketch, and the appropriate LED flashes on the Arduino as expected.

If I connect any of the buzzers to either a 9v battery, or a 12v network of 8 AA batteries, then they buzz as expected.

If I connect both a buzzer and an Arduino in parallel to either a 9v battery, or a 12v network of 8 AA batteries, then the Arduino works fine, but the buzzer makes barely an inaudible whimper.

If I connect only a buzzer to the Arduino and battery, it works fine.  If whilst the buzzer is buzzing I connect the Arduino, then on every ON or OFF of the blink sketch LED, the buzzer gets quieter and quieter until it can barely be heard.

These buzzers are rated to work at 25mA, so it really astounds me that they can't be run off a battery together with an Arduino.

Any help would be appreciated!

Thanks

Dave

Attach your voltmeter across the battery, and measure the available voltage when different things are attached; or attach it in series, and measure current draws.  You probably will find that a 9V battery's voltage is under 8 volts when a mix of multiple Arduinos and buzzers is attached.  That voltage may be too low to activate the buzzer.

A powerstream.com web page called 9V Alkaline tests shows how rapidly a 9V battery's voltage drops when heavy currents (more than a few dozen milliamps) are drawn from it, and a batteriesinaflash.com web page includes the following diagram that shows battery voltage quickly falling below 8.5 V in its first minutes of life when 27 mA is drawn from it.

For some models of Arduino, eg the Uno R3, various posts on the web list currents from 25 mA up to 45 mA, depending on LED and sleep settings.  Currents for the Duemilanove from 10 mA up are reported.  The Arduino Micros in your tests probably use a little more current than Pro Mini boards (which have no USB), and although it's unlikely they will use as much or more current than the buzzers, they still may drag the voltage down to a level where the buzzers won't work.

If your system needs to be battery powered, consider using separate batteries for different devices, to avoid problems like you saw.  Alternatively, use heavier-duty batteries, eg good-sized lithium-polymer units.  Also review posts about decreasing Arduino power usage via sleep, disconnecting the power LED, and using large capacitors to buffer power surges.

Edit: Given that voltage measurements show enough voltage being available, the suggested use of capacitors or inductors to isolate circuits may be a good idea.

When adding a capacitor, locate it physically close to the power-using board or component.  For electrolytic  capacitors, attach the capacitor's + terminal to the high side, eg to the +5, +9, or +12 side, and attach its - terminal to ground.

When adding ferrite beads, wrap the supply wire through the bead several times, if there's room.  The picture below illustrates the idea.

An electrolytic capacitor across a circuit acts as a voltage reservoir.  It also gives high-frequency signals an easy path to ground, reducing interference.  A ferrite bead or other inductor impedes high frequency signals, again reducing interference.


IRremote library and Moteino Does somebody know if the IRremote library is compatible with Moteino boards?

If not, do you know a cheap solution to build a IR-remote controllable via wireless?

You need two spare digital pins to use the IR-library. These pins can be set to whatever you like. Pins D3 to D7 are free on the Moteino so the library will be OK to use if you connect the IR LED and receiver to two of those pins.


int on Uno more than 16 bit? So I'm playing with a TFT screen and trying to understand the colourspace encoding.  I wrote a quick for loop to show colours from 0 to FFFF and to print the value of colour being displayed:

for (int q=0; q<0xFFFF; q+=0x80) {
  tft.fillScreen(q);
  tft.setCursor(0, 0); tft.println(q, HEX);
  delay(2);
}

I was surprised to find values greater than FFFF being displayed - which suggest that int is more than 16 bits.  It's running on a Uno.

What has happened?

(PS I now understand RGB565 encoding, so this is off-topic)

I guess you're seeing some big numbers starting with FFFF...?

What you are seeing is not big numbers - it's misrepresented numbers.

You have an int. That's not a "16-bit number", it's a 15-bit number plus a sign bit.

When you print it the variable is promoted to a long and the sign bit is extended.

That long is then further mapped (cast) into an unsigned long to print it as hexadeximal (there is no negative in the hexadecimal representation on Arduino), and that extended sign bit is seen as a string of F.

For example, the value 0xABCD stored in an int is:

 1 010 1011 1100 1101

I broke off the first bit because that is the sign bit in a signed integer.  The actual decimal value of that is -21555.

Now when that gets cast to a long the sign extension copies the leading sign bit to all the other 16 bits to the left of it, resulting in:

1 111 1111 1111 1111 1010 1011 1100 1101

Because of the way that twos complement works, that string of bits still represents -21555 in decimal.

However, cast it to unsigned long for printing as HEX and you can see how you would end up with some big numbers.  It would give you:

FFFFABCD

So you can see that a 16 bit signed value can end up being printed as 8 hex digits, and all because of the way the print() function in the Arduino API works.

When working with unsigned values you really should be working with an unsigned variable - especially if those unsigned values (0 - 65535) fall outside the range of the signed variable type (-32768 - 32767).  Switch to using uint16_t and you will be able to both store and represent the values correctly.

You might find it useful playing around with this site to learn how different variable types represent and store the data within them as binary.


Using an Android bluetooth terminal to change preset states on 8x8 LED matrixes I'm trying to create eyes for a project, and while I have been able to properly program the different expressions, and have them triggered by commands from the COM3 terminal, I have not been able to make any commands from the Bluetooth Terminal on my phone work.

Details:

Mega2560

2x 8x8 LED Displays - MAX7219

HC-05 Bluetooth Transceiver - default Baud - 9600

Using LEDControl.h, SoftwareSerial.h

This is the loop on my device, when I type the commands A, B, etc. into the COM3 terminal it works just fine, but the same commands on the phone are just interpreted as ASCII, even when I put parentheses around them.

void loop()
{
  // Feed any data from bluetooth to Terminal.
  if (EEBlue.available()){
  Serial.write(EEBlue.read());
  }
  if (Serial.available())  //verifies if there is serial data available
  {
    char cmd = Serial.read();

    if(cmd == 'A') {
      display_eyes(eye_neutral_l, eye_neutral_r);
    }
    if(cmd == 'B') {
      display_eyes(eye_shock_l, eye_shock_r);
    }
    if(cmd == 'C') {
      display_eyes(eye_love_l, eye_love_r);
    }
    if(cmd == 'D') {
      display_eyes(eye_suspicious_l, eye_suspicious_r);
    }
    if(cmd == 'E') {
      display_eyes(eye_happy_l, eye_happy_r);
    }
    if(cmd == 'F') {
      display_eyes(eye_hurt_l, eye_hurt_r);
    }
    if(cmd == '1') {
      display_eyes(eye_mad_l, eye_mad_r);
    }
  // Feed all data from termial to bluetooth
  EEBlue.write(Serial.read());
  }
}

Your problem is, that you read from the EEBlue serial interface, but you are just echoing it over Serial and don't do anything with it. The display code is only executed, when the commands come through Serial.

The simplest way is to copy the code in the if(Serial.available()) statement into the if(EEBlue.available()) statement and changing the read to use EEBlue. Of course you should delete the existing EEBlue.read() from this statement.

But that way would mean to have double the code to maintain. It is cleaner to first read data from either serial interface and then process it. Something like this:

if(Serial.available()){
    cmd = Serial.read();
} else if(EEBlue.available()){
    cmd = EEBlue.read();
}

// insert the code to check the cmd variable for the expected values and act accordingly

cmd = 0; // Resetting the cmd to prevent multiple executions of one command


how can i fix the error ? stk500v2_getsync(): timeout communicating with programmer I bought this Chinese Arduino Mega 2560 16AU.

This was the first time to deal with Arduino boards. When I try to upload a sketch I always get this error:

stk500v2_getsync(): timeout communicating with programmer

I successfully burnt a bootloader to it using an Arduino uno,
but the same error is there.

Finally I discovered the the loop test is not working, and only the LX LED flashes once  when I enter a letter in the serial monitor.

It's our old friend the CH340G again, isn't it?

You've been sold a dud, I'm afraid. The USB chip used there is dead. It happens a lot with those cheap Chinese boards. You should still be able to use the board with an external FTDI adapter by wiring it in to TX->RX, RX->TX and DTR->RESET (via a 100nF capacitor) with power and ground connected of course.

There is also a slim chance that the CH340G may interfere with the TX/RX pins, in which case you may need to remove it. Simply cutting the pins on it with an xacto knife then removing the stumps with a soldering iron and tweezers would do the job.


How to use ATtiny pins that are usually 'reserved' for chip programming? How to program an ATtiny45 to use the pins 1, 5, 6, 7 (i.e. PB5, PB0, PB1, PB2) as input or output?

pinMode(5, OUTPUT);
pinMode(0, OUTPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
digitalWrite(5, HIGH);
...

These pins are usually used to program the ATtiny itself, so how to avoid a conflict?

Of course, I could just avoid these 4 pins, but then as there are also pins for VCC and GND, there would be only 2 pins left: PB3, PB4!

Question: how to use the pins as input/output that are usually used for ATtiny programming?

Linked question:

Should I connect pins 1, 5, 6, 7 of the ATtiny to the programmer
Or should I connect pins 1, 5, 6, 7, as well as 8 and 4 (VCC and GND) of the ATtiny to the programmer?

If the second bullet is correct, when connecting VCC and GND, won't it make the ATtiny run the previously uploaded code?

You can just normally use all pins except for the reset pin (pin 0). When you want to program the Attiny, you just connect the programmer. It will reset the Attiny through the reset pin and put it into ISP programming mode. At that point your code hasn't run.

Note: If you want to program the Attiny while it still sits in its circuit, you have to be careful, that the connected circuit does not disturb the ISP communication. The safest way is to disconnect the Attiny from its circuit and then program it.


Motorcycle Battery Powering Arduino UNO Folks

I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.

I am wondering if this circuit will work fine.

C1 - 1000uF 50V;
C2 - 1000uF 25V;
D1 - 1N4001 ;

Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.

Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
Rin should be V/I = V_drop_max/I_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
If you use the 6V output system I recommend below then you could allow closer to 3V drop in Rin.
If Imax is 100mA then Rin = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally  Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if Rin is used. Without Rin the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.
The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.
9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).
Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.
One superb version of this regulator is the LM2931-N [Data sheet here] - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.
The datasheet description states:

Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.


How do I count time in seconds? I have a statement:

if(control > 100 && control < 130)
{

  //count time 30 seconds and open pin1 for 3 seconds.

}

How can I count 30 seconds and open a pin for 3 seconds?

A non-blocking version is often needed as there is often other tasks to be performed during the wait. The "blink-without-delay"-pattern is a solution but unfortunately it becomes tedious to use with several time periods and logic.

The Timemark library helps abstract the pattern and hide a lot of the details. The below sketch uses two timemarks and a simple state-machine to help reduce complexity.

#include <Timemark.h>

Timemark turnOnWait(30000L);
Timemark turnOffWait(3000L);

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      turnOnWait.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (turnOnWait.expired()) {
      digitalWrite(pin, HIGH);
      turnOffWait.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (turnOffWait.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

Two timemarks are used for clarity. It is possible to use a single timemark and reinitiate it with a new time limit.

#include <Timemark.h>

const uint32_t TURN_ON_TIMEOUT = 30000L;
const uint32_t TURN_OFF_TIMEOUT = 3000L;

Timemark timemark;

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      timemark.limitMillis(TURN_ON_TIMEOUT);
      timemark.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, HIGH);
      timemark.limitMillis(TURN_OFF_TIMEOUT);
      timemark.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

The Scheduler library allows the blocking version (delay) to be used. Non-blocking is achieved by context switching on yield() or delay(). Below is a rewrite using this style:

#include <Scheduler.h>

const int pin = 4;
int control = 0;

void setup()
{
  ...
  Scheduler.start(setupController, loopController);
}

void loop()
{
  ...
  delay(1000);
}

void setupController()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loopController()
{
  ...
  if ((control > 100) && (control < 130)) {
    delay(30000L);
    digitalWrite(pin, HIGH);
    delay(3000L);
    digitalWrite(pin, LOW);
  }
  else {
    delay(100);
  }
}

Cheers!