How to make two wheels turn only for a particular amount of time? I am trying to make a robot turn (dc motors are being used) back 180 degrees. So I used an l289n for it and made one wheel turn clockwise and vice-versa.
But as I wan't it to make only a 180 degrees turn, I wanted to set an amount of time for it to turn.  Is there any other way to do the same thing, if yes, please tell, if no, help me...

Use the delay() function.

Pseudo code as follows:

1) Turn clockwise motor on;
2) Turn counterclockwise motor on;
3) delay(<time>);
4) Turn CW motor off;
5) Turn CCW motor off.


Comparing a char with the symbols '.-' I'm using the Arduino software to create a Morse code decoder using the  serial monitor.

I enter a Morse code such as .- as a text string and it's displayed in the LCD as a alphanumeric text. So if I enter .- into the serial Monitor, A is displayed on the LCD. But it only works for single symbols, not the dot and dash together.

Is there a way to make the if statement as seen below accept both the dots and dashes together?

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  lcd.begin(16, 2);

 Serial.begin(9600);
}

void loop()
{
  char schar;

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

    Serial.write(schar);

    if (schar== '.-' ){
      Serial.write('A');
      lcd.print('a');
    }
  }
}

Your first problem is that there is no way for schar to contain two characters in the first place; Since schar is declared as a char, it can only contain one character.

You need to make a String out of the serial input. Serial.read() only returns one character at a time, so you will need to make sure you iterate over all the input. Then you can compare the whole String with another, and see if both characters match at once. Just look at this code to see different ways of manipulating Strings: http://arduino.cc/en/Tutorial/StringComparisonOperators

Notice that string literals use double quotes, not single quotes like characters.

Also, be aware of the fact that string and String are different things. lowercase 's' is an array of characters, capitol 'S' is the class that has those useful string comparison member functions. The class is more resource intensive, but I think in your case the readability and convenience are worth it.


is it possible to convert a 328 design to use a 32U4? I have several projects that use simple 328 based arduinos that I built myself, similar to the familiar "arduino on a breadboard" projects that I'm sure everybody has seen. They have just the bare minimum, no ftdi, etc.

Is it possible to drop in the 32U4 without modifying the circuits, or would I have to do a bunch of work to the circuits to get them to work with the 32U4 chips, and if so what are the general steps?

Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin.
Also the 32U4 seems to have a lot more peripherals.

So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though.

eg SPI on portB, uart on portD

But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly.

Datasheets are easy to find. Good Luck!


How to disable Due USB power? I need my Arduino Due to work only from external power supply, not from USB power. Is there any way to modify the circuit to allow this? I still need to keep USB communication, but it should happen only when external power is on. Thanks

Disabling USB power is slightly tricky, as the incoming USB power is not only used for potentially powering the system, but it is also used by the various USB interfaces to indicate the presence of a connection.

The best way, looking at the schematics of the Due, would be to remove one or both MOSFETs that switch the USB power - that's T1 for the native port and T2 for the ATMega interface.  That will isolate the USB power from the 5V system while keeping it connected to the VBUS pins of the relevant microcontrollers.


What to use to Drive: 16 Segment LED, 4 Digit, Common Anode (4 sets) I'm trying to make an F/A-18C UFC like this:

Now a while ago I bought 6 x "4 digit 16 segment" z, which happen to be common anode (DataSheet)
What i am looking for is a way to drive all 4 using the minimum of wires - I guess I prefer I²C (IIC) but will work with what ever I can use

Note: I tried something with a HT16K33 IC, but apparently that will only work with Common Cathode

Thank you, and please let me know if you need more info, or suggestions to clarify my question

It might be easier to just get a new common cathode led display or get the whole board from Adafruit https://learn.adafruit.com/14-segment-alpha-numeric-led-featherwing


Additional boards manager option is missing from Arduino IDE I am new to Arduino. For the project I am trying to do, I want to install the ESP8266 extension. But the additional boards manager URL option is missing from the Arduino IDE. What should I do to add the extension?

You need to download and install a recent version of the Arduino IDE from:

http://www.arduino.cc/en/Main/Software

When you install the Arduino IDE using apt-get you get a very outdated and non-standard version, which does not have the Boards Manager feature. The reason for this is that the license documentation of the Arduino IDE does not currently meet the required standards for the package manager:

https://github.com/arduino/Arduino/pull/2703


My two slave SPI setup on arduino not working correctly I am trying to connect a DPS310 and an ADXL345 to my Arduino using 4 wire SPI. When the individually tested (i.e. each has its own script), the output is correct, however when the scripts are combined the ADXL output is garbage, but the DPS functions.
What we expect to see:
Temperature = 24.14 *C
Pressure = 857.88 hPa
X: -4  Y: 4  Z: 29

What we actually see:
Temperature = 24.14 *C
Pressure = 857.88 hPa
X: 0  Y: 0  Z: 0    // and does not change when tilted

When the DPS310 line is commented out, the ADXL works fine (this line is indicated in script)
The whole script (with the faulty line indicated):
#include <SparkFun_ADXL345.h>
#include <Adafruit_DPS310.h>

// ADXL obj
#define ADXL345_CS   9 // SPI pin
ADXL345 ADXL = ADXL345_CS; // Instantiate obj with CS pin
int x = 0, y = 0, z = 0;

// DPS obj
#define DPS310_CS   10 // SPI pin
Adafruit_DPS310 dps; // Instantiate obj (pin is set in setup)
sensors_event_t temp_event, pressure_event;

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

   // ADXL SETUP
   digitalWrite(ADXL345_CS, LOW); // START COMM
   Serial.print("ADXL345: ");
   ADXL.powerOn();
   delay(50);
   ADXL.setRangeSetting(16);
   ADXL.setSpiBit(0);
   ADXL.set_bw(ADXL345_BW_12_5);
   ADXL.setInterrupt(0x84, true);
   ADXL.setAxisOffset(0, 0, 5);
   ADXL.readAccel(&x, &y, &z);
   if(x != -1 && y != -1 && z != -1) {
     Serial.println("[PASSED]");
   } else {
     Serial.println("[FAILED]");
   }
   digitalWrite(ADXL345_CS, HIGH); // END COMM

   // DPS SETUP
   digitalWrite(DPS310_CS, LOW); // START COMM
   Serial.print("DPS310: ");
   if (! dps.begin_SPI(DPS310_CS)) { /////////////////PROBLEM LIES HERE//////////////////
      Serial.println(" [FAILED]");
   }
   Serial.println(" [PASSED]");

   dps.configurePressure(DPS310_64HZ, DPS310_64SAMPLES);
   dps.configureTemperature(DPS310_64HZ, DPS310_64SAMPLES);
   digitalWrite(DPS310_CS, HIGH); // END COMM
}

void loop() {
    digitalWrite(ADXL345_CS, LOW);
    ADXL.readAccel(&x, &y, &z);
    digitalWrite(ADXL345_CS, HIGH);

    digitalWrite(DPS310_CS, LOW);
    dps.getEvents(&temp_event, &pressure_event);
    digitalWrite(DPS310_CS, HIGH);

    Serial.print("Temperature = ");
    Serial.print(temp_event.temperature);
    Serial.println(" *C");
    Serial.print("Pressure = ");
    Serial.print(pressure_event.pressure);
    Serial.println(" hPa");

    Serial.print("X: ");
    Serial.print(x);
    Serial.print("  Y: ");
    Serial.print(y);
    Serial.print("  Z: ");
    Serial.println(z);

    delay(50);
}

I think the fault might lie in the classes written for these devices, for instance maybe they were written for single SPI device or have different frequencies/modes? (I'm probably wrong though XD). I have not yet tried to setup the SPI for each device manually (programming commandment: do no reinvent the wheel), so any help would be greatly appreciated.

The ADXL345 uses SPI_MODE3 and DPS310 the SPI_MODE0. The libraries for these devices don't use SPI transactions, but set the settings only in begin(), so they can't be used together.
Your options to solve this is either to put one sensor on software SPI or to put one or both sensors on I2C.
The ADXL345 can be used as I2C device. Its library supports I2C with the constructor when no parameters are provided. Does your module have an option to wire it to I2C?
The Adafruit library for DPS310 has built-in software SPI, so you can use it with any set of pins. And it too supports I2C.


Adafruit_Arcada' does not name a type; I am trying to program an adafruit pygamer (which says it's compatible with Arduino). I have added the ZIP folder for the library into the library folder om my PC where all of my folders are supposed to be stored, one thing I managed to find out for a start was that the library folder for the library itself that was installed from GitHub contained a dash in the filename so I replaced that for an underscore. The actual error message that seems to come up now is this:
'Adafruit_Arcada' does not name a type; did you mean 'Adafruit_SPITFT'?

This error comes up from when I try to use the:
#include "Adafruit_Arcada.h"

Adafruit_Arcada arcada;

lines
Within the library folder that I want to try and use there are the code examples within the library folder inside the examples sub-folder
I have tried following a step by step guide into one potential way of trying to solve this problem by looking at a tutorial by adafruit on how to step by step install zip folder libraries. Something tells me though that this error that I am getting is to do with one of the .h or .cpp files within the library itself.
The link for the library itself is here: https://github.com/adafruit/Adafruit_Arcada
In addition, when I look in the Adafruit_Arcada.h file I can actually see that there is no Adafruit_Arcada class but there is an Adafruit_SPITFT one. I know this point might seem like a bit of a no-brainer but I just thought it would be useful to try and find out what could potentially be going on and provide evidence of what I have already tried to do.
When I changed the Adafruit_Arcada arcada; to Adafruit_SPITFT arcada; (thinking this could potentially resolve the issue because within the Adafruit_Arcada.h file there is a class called Adafruit_SPITFT and notAdafruit_Arcada`), this brought up another error which was the following:
simpletest:2:17: error: no matching function for call to 'Adafruit_SPITFT::Adafruit_SPITFT()'

There are some instructions at:
Pygamer setup
That need to be followed in order to permit the Arduino IDE to work with the Pygamer.  It's not clear that you have followed any or all of these instructions.
I recommend that you carefully follow ALL the steps and then start with the simple example to test that you are building and uploading properly.
Then move on to the Adafruit example that uses the Arcada library.


Char buffer for serial input: char str[2] vs char* str = (char*) malloc(2) I am using software serials on my Arduino nano to read data from my esp01 in functionality testing for the software serial. I simply make the esp01 to send a string "OK" to an Arduino's software rx serial port (in this case pin 9) , and then the Arduino prints it on the monitor via its hardware serial (USB).
I've found that when I allocate space for the string in Arduino using char str[2], the message seems to be correct. However, with char* str = (char*)malloc(2), there appear to be an unkown character tai
ling the string "OK"
Below is the code I use
#include<SoftwareSerial.h>

SoftwareSerial s(9,10);
void setup() {
  pinMode(2,OUTPUT);
  Serial.begin(9600);
  s.begin(9600);      // link to esp01
}

void loop() {

  if(s.available() > 0){
    char txt[2];
    int indx = 0;

   // read input
    while(s.available() > 0 && indx <=SIZE-1){
        char buff;
        buff=  s.read();
        txt[indx] =  buff;
        Serial.println(indx);
        indx++;

    }
   // bink an LED for debugging
   if((String)txt == "OK"){
    digitalWrite(2,HIGH);
    delay(500);
    digitalWrite(2,LOW);
    delay(500);
   }

   //reset index
   if(indx ==2){

     Serial.println(txt);
     Serial.print("Size of string:");
     Serial.println(sizeof(txt));
    indx = 0;
   }
  } // if(s.available())

}

here is the print-out of the serial monitor

That tailing square is the myster for me.
Any help would be grateful!!
Boris

First, a few general notes:

The difference between char str[2] and
char* str = (char*) malloc(2) is irrelevant to you problem. It
changes the place where the array is stored, the meaning of
sizeof str, and malloc() will blow up your RAM if you call it
repeatedly and forget to free().
In your code, sizeof(txt) is the constant 2: the actual size in
bytes of the array txt, irrespective of how much relevant data it
holds.
You want txt and indxto remember their contents across calls to
loop(). You should either make them global or qualify them as
static.
Avoid the String class if at all possible. Here, since you use it
only to compare two strings, you can use the traditional
strcmp() function instead.

Now, the bulk of my answer is just about expanding on what has already
been said about properly terminating strings.
A string is a variable-length list of characters. Whenever you are
dealing with a list that has a variable length, you need to somehow keep
track of this length. There are two common ways to do so:

either you store the length in a variable,
or you put a sentinel value (a value that would be invalid within
the list) after the last element to mark the end of the list.

Both methods are valid, and I am going to illustrate both of them below.
However, in the case of strings, the C++ language uses method 2,
with the ASCII “NUL” character (numeric value 0) as a sentinel.
Method 1:
void loop() {
  static char txt[2];
  static size_t indx = 0;

  while (s.available()) {
    // read input
    char c = s.read();
    txt[indx++] = c;

    // report
    Serial.print("Received: '");
    Serial.print(c);
    Serial.print("', string: \"");
    Serial.write(txt, indx);
    Serial.print("\", size: ");
    Serial.println(indx);
    if (indx == 2 && memcmp(txt, "OK", 2) == 0) {
      Serial.println("Correct message");
    }

    // reset index
    if (indx >= sizeof txt) {
      indx = 0;
    }
  } // if(s.available())
}

Some things to note:

The indx variable holds the length of the string. It also happens to
be the index of the next available cell in the txt array, if any.
The string is printed using the
write(const char *buffer, size_t size) method, which accepts a size
as a second argument. Unlike print(const char *), it doesn't depend
on the string being NUL-terminated.
In order to check that we received “OK”, we have to check for both the
correct length (indx == 2) and correct contents. The contents is
checked using the memcmp() function, which can compare arbitrary
byte arrays and, again, does not depend on NUL-termination.
An important loop invariant here is idx < sizeof txt. It is true at
initialization and is restored by the “reset index” section at the end
of the loop. The “read input” section depends on this invariant to not
overflow the buffer.

Method 2:
void loop() {
  static char txt[3];
  static size_t indx = 0;

  while (s.available()) {
    // read input
    char c = s.read();
    txt[indx++] = c;
    txt[indx] = '\0';

    // report
    Serial.print("Received: '");
    Serial.print(c);
    Serial.print("', string: \"");
    Serial.print(txt);
    Serial.print("\", size: ");
    Serial.println(indx);
    if (strcmp(txt, "OK") == 0) {
      Serial.println("Correct message");
    }

    // reset index
    if (indx >= sizeof txt - 1) {
      indx = 0;
      txt[indx] = '\0';
    }
  } // if(s.available())
}

Again, some notes:

This is actually an hybrid of methods 1 and 2, as the indx variable
is still used to keep track of where to insert the next incoming
character. This just happens to be more convenient and efficient than
putting that character into its own length-1 string and using
strcat().
The array is now one cell longer, to make room for the terminating
NUL.
There is another loop invariant now: correct string termination
(txt[indx] == '\0'). This invariant has to be enforced both on
reading and on resetting.
The string being NUL-terminated, it can now be printed with print()
and compared with strcmp(). The string literal "OK" is guaranteed
to be NUL-terminated by the compiler.

This second method is generally safer because there are a lot of
functions and methods in Arduino and C++ that expect strings to be
NUL-terminated. If your strings are not, you have to be extra careful to
not use any of these string-oriented functions.


Help - Atmega328p, converting a PWM servo code from pin9 to pin6 I found a working code that uses pin9 (PB1) on my Arduino for controlling a Servo, but in my project, an ultrasonic sensor is already using that pin/timer. I want to convert the code to use pin6 (PD6), changed the registers according to the atmega's datasheet, but it doesn't work. Need help :/

The code should allow me to turn a servo using a potentiometer.

#define F_CPU 16000000 //16MHz
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdlib.h>

#define PWM_PRESCALLER 64
#define ICR_MAX (long double)F_CPU/PWM_PRESCALLER/50
#define OCR_MIN (float)ICR_MAX/37.5 // /8.75
#define OCR_MAX (float)ICR_MAX/8.7 // 37.5

volatile unsigned long adc_val=0;
volatile unsigned long counter=0;
unsigned long curr_adc=0;

ISR (ADC_vect)
{
adc_val += ADC;
counter++;
}

int main(void)
{
    DDRD |= (1<<DDD6);
    ICR1 = ICR_MAX;
    OCR0A = OCR_MIN;
    TCCR0A = (1 << COM1A1) | (1<<WGM00) | (1<<WGM01);
    TCCR0B = (1<<WGM02) | (1<<CS01) | (1<<CS00);
    ADMUX = (1 << REFS0);
    ADCSRA = (1 << ADEN)|(1 << ADATE)|(1 << ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

    sei();
    ADCSRA |= (1<<ADSC);

    while(1)
    {
        if(counter >= 1000)
        {
            cli();
            unsigned long round_val = round(adc_val / counter);
            adc_val=0;
            counter=0;
            if(abs(round_val - curr_adc) > 1)
            {
                curr_adc = round_val;
            }
            long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);

            OCR0A = (int)round(ocr);
            sei();
        }
    }
}

PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1.  Therefore you need to change the timer variables appropriately.  One mistake in your code is that you leave ICR1.  It should be OCRA if you want to use TIMER0.


Power a Raspberry Pi 3 from an Arduino Uno I would like to power my Raspberry Pi 3B using an Arduino Uno.

I have been able to do this by connecting the 5v on the Arduino to the 5 V on the Pi and connecting the GND to GND, and the Pi turns on. But I get a constant under voltage sign.

How can I get the Arduino to output the right amount of power (5 V and 2.5 A)?

You can't.

The on-board regulator of the Uno, the NCP1117, is only able to supply up to 1A before starting to dropout voltage (hence your undervoltage warning).

Even worse, because the NCP1117 lacks a proper heatsink, it will probably start dropping out voltage before reaching 1A, due to its internal thermal shutdown protection.


Get 25 kHz PWM on a 16 MHz Arduino I am trying to output a 25 kHz software PWM on at least four pins simultaneously with variable duty cycles on each pin individualy.

I've got all the actual PWM outputs via internal timers 2x8 1x16 with variable duty cycles and am looking for a way to output a 25 kHz PWM on the four pins (any pins) via an external timer if necessary. How can I do that?

At 16 MHz, your instruction cycle is 62.5 ns, and your PWM period is 40 \$\mu\$s. This is only 640 instruction cycles per PWM period.

To have any hope of doing this, the first thing you need to do is forget using anything Arduino other than the hardware. Download the datasheet for the AVR in question and start getting familiar with it. Your best bet is to use 8 bit timers to reduce the overhead of loading them.

My approach would be to use every 8 bit timer available, and divide the outputs up among the timers. Load the shorest pulse width output in the 8 bit tiemrs. Keep a 16 bit timer available to use for the PWM period. Start all the timers at once. On the first 8-bit timer interrupts, toggle the output, and reload the timers with the time between the next shorest pulse width. Rinse and repeat.

Alternatively you could run one timer, and write a little scheduler that puts the outputs in order from shortest to longest pulse width, constantly poll the timer, and toggle the bits as needed.

Both of these options have a ton of software overhead, and the pulse widths will all be semi-deterministic. Neither would be good for any application where the micro has to do anything else in a timely fashion, such as communication or drive a LCD.


ATMEGA AVcc pin - low pass filter I am a newby to the world of electronics and IC chips, and am looking to make an ATMEGA328 based board to monitor 12v batteries. The board will be powered from the batteries being monitored, with a regulated power supply taking 12v input and outputting 5v to the board.
The data sheet for the ATMEGA328 chip says that AVcc should be connected externally to Vcc via a low-pass filter. A bit of internetting tells me the low-pass filter will filter out noise above a specific frequency, and provides links to calculators that show the affect of different resistor / capacitor pairs.

My problem is that, I have no idea what frequencies I need to filter! All / any advice much appreciated.

Further info: voltage measurements will be via voltage divider circuits, amp hour consumption will be via sensors, all of which will be connected to analog pins for ADC conversion.

The filter is only needed if low noise is important to your application.
For monitoring batteries, you probably don't need the accuracy level at
which you would want the filter. For what it's worth, the Arduino Uno
doesn't have such filter: it's AVCC is connected straight to VCC.

If you really want the filter, the exact characteristics are not
critical. The datasheet suggests 10 µH + 100 nF, so this
should be a safe choice.

Edit: To answer the question in the comment, yes, it is generally
advised to use decoupling capacitors, usually something like
100 nF, even when powered from a voltage regulator.

Notice that both the VCC and the AVCC pins are very close to a ground
pin. Best practice is to use one decoupling cap for each (A)VCC/GND
pair, and to place that cap as close as possible to the pins.


Cheapest Arduino GPRS or 3G solution I am looking at creating a fleet of low power, Arduino driven devices.

I would need some kind of GPS on them all (or could triangulate through phone network?) plus a connection to the internet - just for HTTP POST requests. GPRS or GSM would do but 3G would be better.

What are the best (price is a major factor because I'm trying to do a fleet) GSM, GPRS or 3G modules that I can use with Arduinos? As I said, I need their location so one with GPS built in would be great.

EDIT:
The amount of devices in the fleet will change, so the entire network needs to be dynamic which is why having a GPRS/GSM module on each one would work so well.

If you are finding Cheapest and working module you can you SIM800L less then 4$.

aliexpress.com/item/Free-Shipping-Smallest-SIM800L-GPRS-GSM-Module-MicroSIM-Card-Core-BOard-Quad-band-TTL-Serial-Port/32708504554.html

You can find many other cheap alternative but they does not work properly.

Sim800 have good support and you can find many examples to use this with arduino.

Many other model also available in market as per your requirements.


What I should be aware before I touch my Arduino? Before you start to mess with a computer there are basic guidelines to be aware of, such as turn the power off and watch out for static electricity. What guidelines should I be aware of when I work with an Arduino board if I don't want to harm neither myself nor the board. The three kind of activity that requires touching the Arduino and what I'm asking about:

Setting up wire, component layout or breadboard.
Debugging a running setup.
Moving, mounting up the board somewhere.

Turning the power off and taking proper static precautions also applies to Arduinos.  Anorton's tip about not resting it on a conductive surface is also useful.  Some other things to keep in mind:

Double check the polarities of any connections you make.
Keep a consistent wiring color code.  Use red for power and black for ground.
Calculate the expected current through all components before you apply power.  Check the datasheet to make sure it's within safe limits.
Calculate the heat dissipation for higher power components like power supplies and motor drivers.
Connect and test one small part at a time, instead of in one big bang.
Make sure the parts you buy expect the same voltage, or perform the appropriate conversion.

For keeping people safe:

Know where the fire extinguisher is.
Don't put cords where people can trip on them.
Use a proper stand to hold your soldering iron, and keep pets and small children away.
If your project has a propeller or something physically dangerous, build failsafes and kill switches into the system.
Be careful to charge any batteries properly, and not let them overheat.
Be careful what you touch while troubleshooting.  Arduinos usually don't deal with very high voltages, but inductors and capacitors can build up higher charges than you expect, and hold it after power is removed.


Can the 'Adafruit Non-Latching Mini Relay FeatherWing' be used with an Arduino microcontroller such as an Arduino Mega 2560? Can this relay found here:

https://www.adafruit.com/product/2895

Be used with an Arduino Mega? The description given seems to specify that you should hook it up to their dedicated 'Featherwing Board' but it's the only relay available on their site. Looking at the pins it has it seems it should hook up to an Arduino with no problems. Has anyone here had the chance to use this relay with an Arduino microcontroller? I asked them about this on their forum but I haven't received a reply yet.

PS: I want to use it to connect a 'Strobe Siren 12VDC' and the relay I was looking to get is out of stock at my local shop.

https://store.nerokas.co.ke/index.php?route=product/product&product_id=1398
https://store.nerokas.co.ke/index.php?route=product/product&product_id=1679

Yes.

There's not a lot more to be said really.

It's a relay, and they provide a MOSFET and associated circuitry to drive it cleanly.

Just connect power and ground to the Arduino, along with the "Signal" pin to the GPIO pin of your choice, and away you go.

Note that the relay is a 3.3V relay, so you must power it by the 3.3V pin, not the 5V pin.


What electronics should I study to create something like a fridge temperature monitor? I would like to be able to design an Arduino circuit for a fridge monitor that would have a temperature sensor, a small speaker to emit a sound when the temperature changes past a threshold and an LCD screen showing the current temperature.

I have found a few examples online, but I would like to know why components like capacitors and transistors are used in their circuits so I'd be able to design similar circuits myself.

I found this list of electronics topics:

Basic Theory
Basic Passive Components
Passive Circuits
Discrete Active Components
Active Circuits
Integrated Circuits
Digital Logic
Analog
Signals
Outputs
Inputs
Digital Electronics

Some of these things, like digital logic seem unnecessary in such a project, but obviously some others are useful, but I don't know which. I'd like to know what it would be useful to study so I can understand the reasons for the circuit design of something like a fridge monitor.

A fridge temperature monitor (or any system that talks to world using some data) will include a sensor (temperature sensor like LM35), a controller (to do calculations, arduino ofcourse) and an output (display, like LCD). The topics you should be aware of, are digital electronics, basic passive components (working of resistor, capacitor etc). And a little arduino programming and lots of logic.


SerialUSB on Arduino Due I'm starting fiddling with a Due but I can't seem to be able to communicate over USB with it. Here is my code:

int bauds = 9600;

void setup() {
    SerialUSB.begin(bauds);
}

void loop() {
    if (SerialUSB.available())
        serialUSBEvent();
}

void serialUSBEvent() {
    String str = SerialUSB.readString();
    SerialUSB.write(str.c_str());
}

As you can see, I try with the bare minimum but my output consoles (2 COM port for the 2 usb connections, just in case I messed up which is which) stay blanks, whatever I send them...

Have you tried resetting the board after sending the program? Or after having opened the terminal?

A few days ago I didn't have any results using SerialUSB, and today I have. The program has been sent trough the programming port, and SerialUSB is with native port. Uploading my program trough native port, it didn't worked until I reset!


Avrdude can't connect to butterfly programmer I'm trying to upload my exported HEX file by avrdude using this command

/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem1421 -b57600 -D -Uflash:w:/Users/user_acc/Documents/Arduino/at_command_A6/at_command_A6.ino.with_bootloader.leonardo.hex:i

But instead of loading the file it's stuck on connecting to programmer.

Output: https://scr.hu/rYNzzm
https://paste.ubuntu.com/p/74p37fGYPN/

The output from ArduinoIDE is exactly the same and it finds the programmer without the problem and loads the file.

/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem124 -b57600 -D -Uflash:w:/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/arduino_build_78519/at_command_A6.ino.hex:i

Output: https://scr.hu/M72NaV

Can somebody help me? :)

I found a post of somebody with a similar issue. His solution fixed my issue!

https://stackoverflow.com/questions/46813157/avrdude-command-line-cant-connect-to-programmer-for-leonardo


Slowly decreasing the speed on a steppermotor over time I am currently working on an elevator for my examsproject in school.
It's a quite simple simulation of a lifesize elevator.
I'm currently using a steppermotor for the elevatorchair and it's set with a certain speed.

However, in a real elevator, the speed would slowly decrease as it's progressing towards it's destination for a more pleasant ride for the passengers. I'd like to make the same simulation.
I was thinking of using the millis to periodically increase the delays over time, but I don't know whether alternative methods could be used for better results.

millis() sound like a good way to go.

Check the estimated time until arrival (stopping), and in steps (you define yourself) you changen the (PWM) speed of the stepper motor.

Note, also for accelerating you can use the same step schema but reversed.

There are other ways, but I think those will be too complicated, like setting a (hardware) timer for the next speed change. Changing the speed in ms-accuracy will be more than enough.

Do not use delay, since you still want to be responsive for pressed buttons, and (safety) sensors.


No such file or directory compilation terminated I tried a simple blink for my fingerprint sensor which is GT-511C1R, but I have experienced of having an error.

  FPS_Blink.ino:12:26: fatal error: FPS_GT511C1R.h: No such file or directory
  compilation terminated.

I downloaded the whole library but still same error.

Please learn how to install a library from here. And see if error is coming or not.


Toggle Button For LED Strip not executing properly I have been using a library to control a LED Strip with buttons. My current code does not execute properly. It skips the if statement and just runs the code in a loop with no regard to the button and I'm uncertain why. I'm using an Arduino Uno with an LPD8806.

#include "LPD8806.h"
#include "SPI.h" // Comment out this line if using Trinket or Gemma
#ifdef __AVR_ATtiny85__
#include <avr/power.h>
#endif

int nLEDs = 160;

// Chose 2 pins for output; can be any valid output pins:
int dataPin  = 2;
int clockPin = 3;

// First parameter is the number of LEDs in the strand.  The LED strips
// are 32 LEDs per meter but you can extend or cut the strip.  Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);

int inPin = 4;
boolean lastState = LOW;//storage for last button state

void setup(){
   pinMode(inPin, INPUT);//this time we will set the pin as INPUT
   Serial.begin(9600);//initialize Serial connection
   #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
   clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
   #endif

   strip.begin();
   // Update the strip, to start they are all 'off'
   strip.show();

 }

void loop(){

   if (digitalRead(inPin) == HIGH && lastState == LOW){//if button has just
   been pressed
   // Start up the LED strip
        theaterChase(strip.Color(127, 127, 127), 50); // White
        delay(100);
    } else if(digitalRead(inPin) == LOW && lastState == HIGH){
        digitalWrite(dataPin, LOW);
        digitalWrite(clockPin, LOW);
    }
    lastState = digitalRead(inPin);
    }

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
         for (int j=0; j<10; j++) {  //do 10 cycles of chasing
              for (int q=0; q < 3; q++) {
                   for (int i=0; i < strip.numPixels(); i=i+3) {
                      strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (int i=0; i < strip.numPixels(); i=i+3) {
      strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
  }

If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:

There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:

There are other possible techniques as discussed on this page.

One is to change:

   pinMode(inPin, INPUT);//this time we will set the pin as INPUT

to:

   pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT

Then wire the switch to ground, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.


Operating / pin voltages ATTiny chips I would like to set up a project with an ATtiny chip, such as the ATtiny84 or ATtiny85, in which I interface the microcontroller directly with an XBee for both wireless serial communication, as well as monitoring a digital signal from the Xbee (digital input to the ATtiny). As the Xbee chips can handle only 3.3V and will be damaged at higher voltages (such as 5V), I was wondering whether I can simply power the entire project at 3.3V so that all digital inputs and outputs will be at that voltage?

Yes.  As given in the datasheets, normal ATtinyX4/X5 chips can run with a supply between 2.7 and 5.5V inclusive, whereas the low-power versions can run between 1.8V and 5.5V. Mind the speed restrictions when running at lower voltages though; see the "Electrical Characteristics" section of each datasheet to determine the maximum characterized speed for a given voltage.


Remove unused boards from Arduino IDE In the current project I'm programming simultaneously an UNO board and a Leonardo one.

Switching back and forth between the two boards in the Tools menu takes too much time because of the other 18 boards that I do not own anyway.

Is there a way to remove those boards from the Tools menu?

After some more investigation of the IDE folder, I found a text file called boards.txt in the following path.

 [Arduino Path]/hardware/arduino/boards.txt

EDIT: Be sure to make a copy of the file in case you mess up the following part.

Between two series of '#' characters there will be all the information on a specific microcontroller (e.g uno.name=Arduino Uno). Deleting every line of text between the two '#' series will have the desired effect of removing the board from the Tools menu.


Triggering the push button on the analog input of the L293D motorshield I'm trying to drive a 12v dc motor using three push buttons, one to turn clockwise, the other counter-clockwise and the other to stop the motor completely.

However the code below is not working, apparently it feels like I'm doing something wrong in the code on the connect buttons on the analog part of the engine shield L293D.

The Arduino is powered by a 9v battery and motor shield **L293D with an external power.

#include <AFMotor.h>

    AF_DCMotor motor(1);

    int val;

    #define btnleft A0
    #define btncenter A1
    #define btnright A2

    void setup()
    {
      pinMode(btnleft, INPUT);
      analogWrite(btnleft, HIGH);
      pinMode(btncenter, INPUT);
      analogWrite(btncenter, HIGH);
      pinMode(btnright, INPUT);
      analogWrite(btnright, HIGH);
    }

    void loop()
    {
     val=digitalRead(btnleft);
       if(val!=1)
        {
        Serial.print("LEFT: ");
        motor.setSpeed(255);
        motor.run(FORWARD);
        delay(3800);
        }

     val=digitalRead(btncenter);
       if(val!=1)
        {
        Serial.print("CENTER");
        motor.setSpeed(255);
        motor.run(BACKWARD);
        delay(3800);
        }

     val=digitalRead(btnright);
       if(val!=1)
        {
        Serial.print("RIGHT");
        motor.run(RELEASE);
        delay(3000);
        }
    }

As noted in Nick Gammon's comment, digitalWrite(btnleft, INPUT) (etc.) would make a lot more sense than does analogWrite(btnleft, INPUT) (etc.).

Edit: INPUT is a constant defined in wiring.h (as in following extract), and is intended for use in pinMode() calls that set an IO pin's mode to one of INPUT, OUTPUT, or INPUT_PULLUP.  It's inept to use it in a call of either digitalWrite() or analogWrite().

    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1
    #define INPUT_PULLUP 0x2

Note that digitalWrite to an input-mode pin leaves the pin in input-mode, while an analogWrite to an input-mode pin changes the pin to output-mode.

When you want a pin to be input-mode with pullup, it is simpler to use INPUT_PULLUP as the mode parameter, rather than using two separate calls.  That is, instead of saying pinMode(pin, INPUT); followed by digitalWrite(pin, HIGH);, just say

pinMode(pin, INPUT_PULLUP);


Measuring .7 volts on pin 2 and 0.0 on the rest when setting all pins low Having my Arduino Nano 328P disconnected from any circuitry and setting all pins to pinMode(OUTPUT) and writing LOW to (almost) all the pins, when I connect my multimeter to every output pin and the Arduino ground, I measure 0.7 volts on pin 2 and 0.0 volts on 3 to 19. Here I mean the pin numbers on the edge of the Nano, not the processor pins.

For my project it worked out fine because I needed those 0.0 and not the 0.7, but I'm afraid it suddenly might not be pin 2 that's 0.7 in the future and my circuit would fail.

  Why is there this one pin giving 0.7 instead of 0.0 and how can I make sure or argue that it will only be pin 2 that gives 0.7?

EDIT as per request, the full test code is below.

void setup() {
  for (int i=1;i<20;i++){
  pinMode(i, OUTPUT);
  }
}

void loop() {
  for (int i=1;i<20;i++){
    digitalWrite(i, HIGH);
  }
    delay(3000);
    for (int i=1;i<20;i++){
    digitalWrite(i, LOW);
    }
    delay(3000);
}

For future reference, thanks to Majenko: these values fall within the expected voltage output range of 0-0.9V, and you cannot be certain it will stay this way. See the datasheet page 313.


Is a solenoid piston strong enough to lock a water tubling? My question is about hardware that i'll control with my arduino... Not Arduino itself (So I don't know if I'm in the right section ... :s)

My project is to create a cocktail machine at the cheapest price.

I was wondering if this kind of solenoid piston would be strong enough to seals a plastic pipe like this one ?

My idea from now is to use only 1 water pump (as this one) and connect all the pipes from the bottles with some Y and control which one is giving the liquid by controling pistons that are going to compress the tube.

I'm open to all advices you could give me and new ideas ... I saw that there's also solenoid valves ... But I only find it in 12V ... Does it exist in 5V ?

The pump you are looking at is to powerful for you application: 350 liters/hour, or little less than 5 ltr/min. It will fill a 250 ml glass in about 3 seconds!

The solenoid cost you $5 a piece, but you still need a valve and a way to attach solenoid, valve and tubing.

Also, your idea means liquids will get mixed inside the tubes. And nobody wants a trace of whiskey in his Vodka Screwdriver.

You must visit The Inebriator, a cocktail mixing machine. His design have one tube for every bottle pouring liquid into the glass.

As they note, they have in version 2.0

  Switching mixers from a pressurised system with valves to using pumps
  – This slows the pouring, but vastly simplifies the machine as a
  whole. We have a capacity for 16 pumps

They don't use valves, but pumps. I recomend a peristaltic pump ($7 on Aliexpress), like this:

They don't touch the fluid, easy to mount, and are a very precise delivery mechanism, like in this video https://youtu.be/GdTUIwj5ros, showing an Arduino controlling a pump to 1ml precision:


Recommendations for limit switches for Arduino I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my turntable makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.

Any suggestions on which limit switch I should get?

Thanks so much in advance!

A $2 microswitch with a roller would be OK for a million revs or so.

You would put a little ramp on the diameter and use it to trigger the switch.

Non-contact magnetic or optical could be better for more cycles or faster operation.


Shutdown the LED of my GY-85 sensor I would like to shutdown the LED of my GY-85 (gyroscope) component. Is it possible?

According to this schematic, no. The LED is connected directly to power.

You will need to physically remove the LED to turn it off.


Parse HTTP Request Arduino I am sending a HTTP Request to my WiFi module http://192.168.4.1/STA/ID=HelloWorld/Pass=Testin123

How can I parse above string in Arduino. First I need to check for STA, if it exists, continue to scan the string. Put Value of ID, in this case HelloWorld should be store in String data type SSID and Value of Pass, in this case Testin123 should be store in String data type Pass.

How can achieve above using ARDUINO code! Please help.

Your incoming string, as Gerben has mentioned, will actually be more like:

GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1

My personal preferred method is to use strtok() to split the string up.  I'd use a two-pass method for this.

First split the string up into three parts - one GET, one the request, and the third the request type (though you don't need to use that for anything).  Assume the string is in C string incoming:

char *get = strtok(incoming, " ");
char *request = strtok(NULL, " ");
char *rtype = strtok(NULL, " ");

The request is now pointed to by the *request pointer and the string has been sliced up in-place.  So now you can do something similar with the request, this time splitting on / instead of space:

String SSID;
String Pass;

if (request != NULL) {
    char *part = strtok(request, "/");

    bool seenSTA = false;
    while (part) { // While there is a section to process...

        if (seenSTA) {
            if (!strncmp(part, "ID=", 3)) { // We have the ID
                SSID = String(part + 3);
            } else if (!strncmp(part, "Pass=", 5)) { // We have the password
                Pass = String(part + 5);
            }
        } else if (!strcmp(part, "STA")) {
            seenSTA = true;
        }

        part = strtok(NULL, "/");
    }
}


Use registers as parameter? I'm writing a helper class to manage timers, and I'm writing a lot of code like

if (timer == 1)
        ICR1 = icr;
    else if (timer == 3)
        ICR3 = icr;
    else if (timer == 4)
        ICR4 = icr;
    else if (timer == 5)
        ICR5 = icr;

Is there a better way to store these registers?
e.g. an array

timers {
{ ICR1, TCCR1A, OCR1A, OCR1B },
{ ICR2, TCCR2A, OCR2A, OCR2B }

etc.

to be accessed like

timers[1][0]

for ICR1.

And ultimately, how would I assign a value? e.g.

*timers[1][0] = 100;

UPDATE:

I solved the problem with

volatile uint16_t* ICRs[5];
ICRs[1] = &ICR1;
ICRs[3] = &ICR3;
ICRs[4] = &ICR4;
ICRs[5] = &ICR5;

*ICRs[1] = x;

registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.

assuming that ICRi is of 8-bit types - they are NOT to be sure:

uint8_t *ICRs[4];  //isr pointers

//initialize the icrs
ICRs[0]=(uint8_t *)&ICR0;
ICRs[1]=(uint8_t *)&ICR1;
...

*ICRs[i]=icr; //assign value to ICRi

note: that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.


What is this? Looks like a sensor I got an Arduino kit from my dad.
But inside this box is a thing, maybe a sensor. But I can't find what it is.
Anyone recognize this 'thing' on the picture?

Appears to be a touch sensor that can be found on various on-line retail web pages:

http://www.satistronics.com/

https://www.arduiner.com/

Also, the back may have a URL as this one does:

...however, the URL appears not to function.


Can't get OC1B (pin 10) to output I'm trying to get this program to use channel B for the output waveform using the phase correct PWM mode and using OCR1A as the top. With a 50% duty ratio I'm attempting to  get a 10 Hz freq. I'm able to adjust the OC1A (Pin 9) if I set TCCR1A to 0x43; but nothing comes from pin 10. Code:

include "avr/io.h"

void setup()
{
 DDRB = 0x6; //set pins 9 and 10 as output

 /*set operation Toggle mode; WGM13:0 = 1011 phase correct PWM
CS12:0 = 101 prescaler = 1024*/
 TCCR1A = 0x23;
 TCCR1B = 0x15;

 OCR1A = 0x187; //391 for 50% duty cycle
 TCNT1 = 0; //clear counter and update OCR1A
}
void loop()
{ }

You are using Timer/Counter 1 in Fast PWM Mode with TOP set to OCR1A:
OCR1Aonly describes the number to what it counts up so, 0…391 in your case.
You have to define the duty cycle with OCR1B. 50% would be 195.


Will a simple RC filter work with my mechanical rotary encoder, or do I need a Schmitt trigger? I bought some incremental rotary encoders online  https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf

The spec sheet for those suggests a filter circuit for the outputs of the encoder that looks like this:

Adding that filter reduces, but doesn't eliminate, spurious signals from the encoder. I wanted to avoid adding Schmitt triggers or other solid state components since I don't have a lot of room left on my proto board for an IC, but I'm beginning to think I will have to add something with hysteresis since any filter that reduces jitter will also slow the rise time/fall time for the output of the encoder and keep it in the "gray area" between LOW and HIGH for a digital signal for too long.

Is there a way to wire these encoders and/or software that lets you read from them with simple passive filtering and/or software rather than adding something like a latch or Schmitt trigger for debouncing?

Having just chased a problem using a software based debounce for several days, what I'll add is that for the encoders I was using (green no-name Chinese ones), if you put 10mA though the contacts then the signal is a LOT better.   So change the 10k to 470 Ohms.

Or if using 3.3V use 330 Ohms.  Solved all my problems.


Nextion Dual State Button I am having an issue with my Nextion display. I have uploaded the following code via Arduino IDE to my Arduino MEGA 2560.
My Nextion Editor shows the button as ID:9 on page0 named floor. I am not entirely sure if the code below is correct. I had one issue where the upload from the laptop to the Mega wouldn't finish, but I managed to bypass that issue by disconnecting the Nextion and swapping RX and TX cables from Nextion while the upload was in progress. Not sure how else I would fix that issue? (If anyone has any ideas haha)
All that is meant to happen is when the dual button state is changed, the onboard LED_BUILTIN is set to HIGH and if in its second state, is set to LOW.
CODE
#include "Nextion.h"

NexDSButton bt0 = NexDSButton(0, 9, "floor");

int ledPin = LED_BUILTIN;

char buffer[100] = {0};

NexTouch *nex_listen_list[] =
{
    &bt0,
    NULL
};

void bt0PopCallback(void *ptr)
{
    uint32_t dual_state;
    NexDSButton *btn = (NexDSButton *)ptr;
    dbSerialPrintln("b0PopCallback");
    dbSerialPrint("ptr=");
    dbSerialPrintln((uint32_t)ptr);
    memset(buffer, 0, sizeof(buffer));

    if(dual_state)
    {
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }
}

void setup(void)
{
    nexInit();

    bt0.attachPop(bt0PopCallback, &bt0);

    dbSerialPrintln("setup done");
    pinMode(ledPin, OUTPUT);
}

void loop(void)
{
    nexLoop(nex_listen_list);
}

My issue is that the MEGA is identifying the touch event (as the TX LED on the MEGA flashes) however it is not turning on the MEGA's onboard built-in LED.
Any help would be greatly appreciated!

This is part of the code I have been using for an extraction fan, The button text is tested and if the button matches the command the fan is turned on or off and the button text is changed accordingly. Hope this helps.

void b19PopCallback(void *ptr) //Extraction Fan
{
  NexButton *btn = (NexButton *)ptr;
  memset(buffer, 0, sizeof(buffer));
  btn->getText(buffer, sizeof(buffer));

  if (strcmp(buffer, "ON"))
  {
    //COMES BACK AS A FALSE (0) IF BOTH STRINGS MATCH
    digitalWrite(b_motor, LOW);
    strcpy(buffer, "ON");
    btn->setText(buffer);
  }

  else
  {
    digitalWrite(b_motor, HIGH);
    strcpy(buffer, "OFF");
    btn->setText(buffer);
  }

}


Call class B from Class A I have two classes in my sketch that are independent of each other (a serial output and an LCD display) A simplified structure of my code is as follows:
class A
{
  public:
   int x;
   void afoo()
   {
     x=1;
   }
   void afoo2
   {
     x=ClassB.bfoo+1;
   }
};

A ClassA;

class B
{
  public:
    int y;
    void bfoo()
    {
      y=ClassA.afoo+2;
    }
};
B ClassB;

However, if I don't comment out  class afoo2 I get the following error:

exit status 1
'ClassB' was not declared in this scope

I'm guessing that this is because I haven't yet created B ClassB while class is being defined. Is there a way I can do what I'm intending here?

You can't see non-static member variables in a class like that.  The closest is to make it static, which means you get one and only one copy of the variable across all instances of your class:

class ClassB;
class ClassA {
    public:
        int x;
        void foo();

};
class ClassB {
    public:
        static int bfoo;
};

void ClassA::foo() {
    x = ClassB::bfoo + 1;
}

However I suspect that isn't what you want. I suspect you actually want to see the bfoo value stored in class instance B - so you need to tell you classA instance A what and where B is. To do that you will have to pass it when constructing or during some other setup phase.  If you want A to know B and B to know A you can't easily do it during construction, so you will have to do it at a later stage:

class ClassB;

class ClassA {
    public:
        ClassB *B;
        int fooa;
        void begin(ClassB *b) {
            B = b;
        }
        void foo();
};
class ClassB {
    public:
        ClassA *A;
        int foob;
        void begin(ClassA *a) {
            A = a;
        }
        void foo();
};

void ClassA::foo() {
    fooa = B->foob + 1;
}

void ClassB::foo() {
    foob = A->fooa + 1;
}

ClassA A;
ClassB B;

void setup() {
    A.begin(&B);
    B.begin(&A);
}

void loop() {

}


Arduino I2C Wire.onReceive hangs after a few loops I have an Arduino Leonardo (master) and a Polulu A-star 328 PB(slave). I intend to use the slave to actuate some servos. I've modified the code from https://www.arduino.cc/en/Tutorial/MasterWriter to also blink the builtin led of the slave and it hangs after a few loops. Without the blink, it works fine. With blink, it hangs after a few loops.

Master:

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting
  x++;
  delay(2000);
}

Slave:

#include <Wire.h>

void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Wire.begin(8);                // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600);           // start serial for output
}

void loop() {
delay(100);
}

void receiveEvent(int howMany) {
while (1 < Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
}
int x = Wire.read();
Serial.println(x);
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}

Serial monitor:

x is 16
x is 17
x is 18
x

Any idea what's causing it and what can I do to further debug it or fix it?
Thank you!

After a bit of tinkering, I noticed that removing the delay() call in the slave fixed it and there were no more hangs. Also, when using the Servo library to move a servo instead of blinking the led, Servo.write() hangs while Servo.writeMicroseconds() doesn't. I'd mark the answer that has an explanation for this strange behavior.


What is the meaning of [type]* for arrays? I've seen * used with arrays in some programs but not in others. The page on arrays doesn't mention it at all, but I often see it near functions when values are being passed.

Where would I find more information on this?

You are asking about Pointers -
 https://www.tutorialspoint.com/cprogramming/c_pointers.htm.


Is there a cheap relay that can control voltage from stuff like bulb lights with a 5 V control output? I need to power a light bulb or something like 110 V or 220 V at normal amperage for TV or something at that range like a fan...

My micro-controller is an Arduino with 5 V out and 12 V max out trough transistor switch.

To my understanding a stepper motor drive could be a viable option to enable the relays... I can even control current, right?

Up to 8 channels

Could this work better?

You can use a 5V Solid-State Relay module to control light bulbs. They cost $4-6 from US-based suppliers and $1-3 from a Chinese supplier. Just hook up the supply to the center pin and the load to either the NO or NC pin. Supply 5V to the module and wire a digital pin to the module to control it.


Send multiple int values from Python to Arduino using pySerial I'm trying to send 3 ints in the range of 0-180 from Python to the Arduino Uno device using pySerial (py3K). I have managed to send 1 int by using python's struct lib (not sure if it's the best or fastest way but it works).

However I'm failing to send more than 1 and every example online seems to stop at 1.

Here's the simplified code. The task is to send servo0-servo4 to the Arduino and apply those values to the corresponding servos.

Python Code

import serial
import struct
import time

bge.arduino = serial.Serial('/dev/ttyACM0', 9600)

# let it initialize
time.sleep(2)

# send the first int in binary format
bge.arduino.write(struct.pack('>B', 45))

Arduino code

#include <Servo.h>
Servo servo0;
Servo servo1;
Servo servo2;

void setup(){
  Serial.begin(9600);
  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  if(Serial.available()){
    int message = Serial.read();
    // control the servo
    servo0.write(message);
  }
}

I guess I'll answer my own question for anyone else having this issue. What I did was:

Python:

# write to arduino as raw binary
bge.arduino.write(struct.pack('>BBB',45,90,180))

Arduino:

#include <Servo.h>

Servo servo0;
Servo servo1;
Servo servo2;

// create array
int incoming[2];

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

  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  while(Serial.available() >= 3){
    // fill array
    for (int i = 0; i < 3; i++){
      incoming[i] = Serial.read();
    }
    // use the values
    servo0.write(incoming[0]);
    servo1.write(incoming[1]);
    servo2.write(incoming[2]);
  }
}


Merge two Arduino projects (change build process) I'm working on a big software project consisting of several Arduino sketches.
I have one Arduino project providing general functionality, such as TCP/IP communication, parsing queries, handling errors, and some more. This part is fundamental for several devices, which extend this fundamental part by specific functionalities. E.g. one device needs to read temperature sensors and manage a loop to control the temperature and has its own sketch. Another device is driving a servo motor and measuring sun light and also has its own sketch. (And there are some other devices with specific sketches.)

I want to maintain the fundamental part in ONE sketch and the specific parts of the different devices each in OTHER sketches, so I can code both separately.

The problem is, those specific parts can not be compiled if not merged with the fundamental sketch, as this provides basic functions. So if I compile any specific part, I want the fundamental part to be added to the specific one and afterwards the whole code should be compiled.

Is there a way to manipulate the makefile used by the Arduino IDE? Then I could use whatever I want (bash or Python script) to merge in the desired way first.

Assuming that each separate hardware device (ESP32?) must run self-contained with both the fundamental parts, and the use-specific parts, then you would do well to separate out the fundamentals into a library, and then include that library in each use-specific sketch.

The Adafruit Unified Sensor Driver would be one project that shows this. Each of the sensor libraries based on this driver must #include the unified sensor driver library, and that provides some basic properties and interfaces, while each sensor's individual code handles the specifics for communicating to/from that particular unique hardware device.


ATmega32u4 bootloader Hey all this would be my first encounter needing to burn the Arduino IDE bootloader onto a blank ATMega32u4 that I bought from Digikey.

What all do I need to buy in order to program the bootloader for that chip? In the manual for the 32u4 it says it comes with a bootloader but I'm guessing its not the arduino bootloader?

Is the pinout for the ISP all that I would need in order to upload the Arduino bootloader?

I've seen this post:

but I wont be using the through-hole design.. its going to be the surface mount SMD kind so i wouldn't be able to put that on a breadboard.

So would it be as simple as breaking out the ISP pins on the 32u4 and just hooking those up to a Arduino Duemilanove board even if its not the same ATmega chip (As in copying the atmega32u4 arduino to the Duemilanove and then transferring that to the 32u4?)?

The ATmega32U4 already comes programmed with a bootloader that allows programming via USB; once you've added the basic hardware for a USB connection you should be able to use AVRDUDE, FLIP, etc. to upload firmware to the device.

Having said that, putting an ISP connection as per AVR042 is highly recommended regardless.


Arduino Due - wireless programming via Xbee I would like to integrate an Arduino Due into a project, which probably will evolve over time and will need some re-programming. Instead of having to disconnect and pull out the Arduino Due out from the enclosure, I was wondering whether it can be set up for wireless programming via an Xbee in a similar way as for the Arduino Fio (like described here: http://arduino.cc/en/Main/ArduinoBoardFioProgramming).

Has anyone tried that already or succeeded doing that?

Theoretically, it is possible I have not tried to do it on an Arduino but I did work something similar with a pic controller. Usually, when we program the board with the firmware file we break the firmware file and send it as multiple packets over the serial com port to be written to on a certain flash memory location on the controller.
In your case, you can try an experiment by using 2 XBee modules that are connected together with the appropriate channel and network ID settings wirelessly. connect one XBee to your computer using a serial to USB cable. On the Arduino side, you have to connect to power it and use the second XBee to connect to it on the UART port. This way the XBee acts as a simple wireless data transfer channel to send and receive data wirelessly (if I am right this should be achievable in the transparent mode on XBee).
One thing to note is to check the Arduino schematic to see how exactly the data over USB is sent to the controller. If it is on UART then this should work straightforward if not then you may have to figure out something else for it.


Can I hook up a compass directly to my GPS module? I have a Parallax PMB-688 GPS module I'm using with an Arduino and was wondering if I could hook up a compass directly to my GPS. The GPS has an RX port which I hypothesized a compass could be attached to but I don't know if the GPS would be able to comprehend the compass data alone or if I would need to hook it up to the Arduino separately. Please let me know if you have done this or know whether or not it will work. Thanks,

Chris

Unfortunately this will not work. If you take a look at the documentation for the module (here and here) you'll see that the RX pin is just there to receive commands for doing things like changing the baud rate and the protocol. The GPS wouldn't be able to comprehend the compass data.


Running a DC motor for a set amount of time I am trying to run a DC motor for 100ms and then turn it off completely. Here is my code any suggestions on why it might not be working?
My Code
const int pirPin = 9;
const int motorPin = 2;
int switchState = 0;
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(motorPin , OUTPUT);
  pinMode(pirPin, INPUT);
}
void loop() {
  while (digitalRead(pirPin) == HIGH) {
    digitalWrite(motorPin, HIGH);
    delay(100);
    digitalRead(pirPin) == LOW;
    break;
  }
}

#include <Arduino.h>

const int pirPin = 9;
const int motorPin = 2;
int switchState = 0;
// the setup routine runs once when you press reset:
void setup()
{
 // initialize the digital pin as an output.
 pinMode(motorPin, OUTPUT);
 pinMode(pirPin, INPUT);
}
void loop()
{
 while (digitalRead(pirPin) == HIGH)//this part of the code gets executed if the pir
 //pin is read high
 {
   digitalWrite(motorPin, HIGH);//the motor pin is set high so if a motor is connected
   //the motor will start turning.
 }
 while (digitalRead(pirPin) == LOW)//this part of the code gets executed if the pir
 //pin is read low
 {
   delay(100);// so your motor stop after running for extra 0.1 seconds
   digitalWrite(motorPin, LOW);//the pin gets low and the motor should stop turning
 }
}

I have commented all the lines
Hope this helps.


Arduino Due: JTAG and SWD do not work after pressing erase button I have an Arduino Due board. I can successfully upload code to it using Arduino upload via USB.
However I am also exploring another approach, which is to upload code via Atmel studio using an Atmel ICE and JTAG connection. Usually this works fine (the code uploads, and a simple "blink" sketch makes the onboard LED flash).
However when I press the erase button, and then try to upload the same sketch via Atmel Studio and JTAG, something strange happens. The code uploads fine:
Erasing device... OK
Programming Flash...OK
Verifying Flash...OK

But then the program on the Due does not actually execute. The LED does not start to 'blink'. If I then again upload via USB (programming port) and the Arduino IDE, the blink program does work. And when I then upload via Atmel Studio and JTAG again without pressing the erase button, everything happens as expected too (LED blinks etc).
Does anyone have any idea what might be going on? The reason I ask is because I would like to design a board using only a JTAG connection. Do you think the above problem could cause issues when using a 'blank' factory SAM MCU as well?
EDIT: the same problem applies to SWD.
Blink sketch that i am uploading:
#define led LED_BUILTIN

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(600);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(600);               // wait for a second
}

After uploading via Microchip Studio, go to the GPNVM bits section of "device programming" window. Make sure boot mode is set to "boot from flash". Also check that GPNVMBITS register is set to 0x00000002. Then press "program". The sketch you uploaded to the MCU should now work.
So it seems what happens is that pressing the erase button resets the GPNVM bits so that the MCU boots from ROM, but then Atmel ICE + JTAG/SWD does not set the boot mode back to flash after (succesfully) programming the MCU.


Is the strange problem I'm having to do with comparing floats? I have a timer interrupt that controls a stepper motor, on an UNO board. In the interrupt handler it checks the speed of the motor and compares it to the target speed. This allows the motor to accelerate to the target speed in a non-blocking way.

This is the relevant part of the interrupt handler:

ISR(TIMER1_COMPA_vect){
    if (targetSpeed > 0 || motorSpeed > 0){
        // leading edge of the step cycle
        if (leadingEdge){
            digitalWrite(STEP_PIN, HIGH);
            stepNumber++;
            // check speed and adjust if necesary
            if (motorSpeed < targetSpeed){
                motorSpeed += speedIncrement;
            }
            else if (motorSpeed > targetSpeed){
                motorSpeed -= speedIncrement;
            }

            leadingEdge = false;
        }
        // trailing edge
        else{
            digitalWrite(STEP_PIN, LOW);
            leadingEdge = true;
        }
    }
    OCR1A = minInteruptsPerStep + (minInteruptsPerStep * (1 - motorSpeed));
}

In the loop() I have a function that checks the state of motorSpeed to control other functions

if (motorSpeed == targetSpeed) {
    motorState = RUNNING;
} else if (motorSpeed < targetSpeed) {
    motorState  = ACCELERATING;
} else if (motorSpeed > targetSpeed) {
    motorState  = DECELERATING;
}

motorSpeed and targetSpeed are floats and range from 0-1, in steps of 0.1 speedIncrement is 0.001 As far I can see that should ramp the speed up until motorSpeed == targetSpeed, in 100 steps. And this mostly what happens. The speed gets to targetSpeed and motorState switches from ACCELERATING to RUNNING, as expected.. mostly. The problem is that it occasionally starts flipping between the three states, for no reason I can see--there is nothing that should modify the value of motorSpeed outside the interrupt handler, so once it stops accelerating it should be stable.

Is this because I'm using and comparing floats? Should I scale the speed variables up and use an int or even a byte?

You already know, from previous answers, why the comparison doesn't give
you the result you expect: you assumed that any multiple of 0.1 is also
a multiple of 0.001, which is true for real numbers but nor for floats.

To fix the issue, it has been suggested to you to allow for some
fussiness in the comparison. I would suggest a different approach: keep
your comparisons as they are, and instead change the way the speed is
updated in the ISR:

if (motorSpeed < targetSpeed) {
    motorSpeed = min(motorSpeed + speedIncrement, targetSpeed);
}
else if (motorSpeed > targetSpeed) {
    motorSpeed = max(motorSpeed - speedIncrement, targetSpeed);
}

With this logic, motorSpeed will always end up being exactly equal
to targetSpeed, irrespective of whether the speed change is a multiple
of the increment or not.

A common misconception about floating point numbers has it that they are
not exact. Truth is, most floating point calculations involve rounding
errors, but the floating point numbers themselves are exact numbers,
if not the numbers you expect¹. Then, when you do the assignment

motorSpeed = targetSpeed;

which the code above ends up doing at some point, you can test

if (motorSpeed == targetSpeed) ...

and it will be true.

¹ When you write “0.1” in the source code, you get the float which is
closest to 0.1, which happens to be 0.100000001490116119384765625
exactly.


How to save a state - make an arduino run a code only once/make aruduino bahave differently the next time he is on Im building a arduino based bicycle speedometer. When the code starts the user picks his bike size (which I need to calculate the radius). Then I have a state finite machine where the user taps the button between speed, time and temperature. I need to put this circuit on a battery and it needs to be mounted on a bike. But every time you plug and unplug the battery, the code runs from the beginning again, which I don't want. So every time the user turns the speedometer off then on, he needs to pick his bike size again. Is it possible to save the size he has picked so that the next time he turns it on, it doesn't come across.
So - user has his speedometer, turns it on, picks the bike size, turns it off, then sometime later turns it back on and the part for picking the bike size doesn't show up, it simply "knows" remembers what the user picked last time.
I don't know how could that work, would the Arduino run the certain code only once or is there a function for "the next time Arduino has electricity behave like this".

As one of the comments said, you will need to use the EEPROM library. When you save a variable in your code (e.g. int test = 10;) the variable along with its value gets stored in the RAM. The EEPROM is a piece of harddisk on your arduino that will remember its value when you power off your arduino.
If you implement a power-off button, simply save the state (or in your case, the wheel size) in EEPROM whenever the user inputs it. The next time you power up, you can check if there is a previous value in EEPROM and continue with that value if it exists. Otherwise ask the user for their wheel size.
You might want to implement a reset-button as well, to reset whenever you change bike or wheels. Look up a code example of EEPROM, as there are a lot online.


Unable to get output on Arduino serial communication with ESP8266 and M6E RFID reader I am unable to get the output on NODEMCU serial. NODEMCU is connected with Arduino Uno, and Uno is connected with M6E Nano RFID reader. Currently I am unable to understand that am i doing any mistake. Please let me know if any other thing you require.

NodeMCU and M6E Nano RFID reader pin configuration with Arduino Uno

NodeMCU         UNO
Vin             Vin
GND             GND
D2              2
D3              3

Code for Arduino Uno+M6E Nano RFID Reader

#include <SoftwareSerial.h>
SoftwareSerial softSerial(2, 3);

#include "SparkFun_UHF_RFID_Reader.h"
RFID nano;

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

  while (!Serial);
  Serial.println();
  Serial.println("Initializing...");
}

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  char str[sizeof(myTID) * 2 + 1];
  const char* hex = "0123456789ABCDEF";

  //Read unique ID of tag
  response = nano.readTID(myTID, sizeof(myTID));
  if (response == RESPONSE_SUCCESS)
  {
    for (int i = 0; i < sizeof(myTID); i++)
    {
      str[i * 2] = hex[(myTID[i] >> 4)];
      str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
      }
    str[sizeof(str)] = 0;
    Serial.println(str);
   }
  else
    Serial.println("Failed read");
}

Code for NODEMCU

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
SoftwareSerial NodeMCU(D3,D2);

void setup()
{
  Serial.begin(9600);
  NodeMCU.begin(4800);
  pinMode(D2,OUTPUT);
  pinMode(D3,INPUT);
}

void loop(){
  String str = 0;        // stores received byte

  if(NodeMCU.available())
  {
    // get byte from USB serial port
    str = Serial.read();
    NodeMCU.write(str);
  }
delay(30);
}

Unable to find where i am doing the mistake! Thanks in advance

You have not the same baud rate on both ends.
SoftwareSerial is not reliable at 115200. use 9600 baud
SoftwareSerial on esp8266 is not reliable.

remove Uno from the project and connect the reader to NodeMcu


How do you combine 2 different sketches together (Before you down-vote this, note that it is a "ringer" to answer a FAQ, with a self-answer.)

This question comes up all the time. How do you combine 2 different sketches together? Say I have a sample sketch for a DTH temp/humidity sensor and another sketch for a LCD sensor. How do I combine them?

This question comes up all the time. I'll explain what you need to do in general terms. Try it, and if you have problems, post a question showing your 2 starting sketches, your attempt at combining them, and detailed info on what goes wrong.

There are 3 basic parts to the main.ino file of an Arduino sketch:

The declarations:

#includes
#defines
global variables

The setup() function
The loop() function.

You need to merge those parts separately.

You should merge the subsections of the declarations together (Put all the #includes together, all the #defines together, and all the global variables together. Remove any duplicate #includes.

If there are any duplicate #defines or global variables, you need to figure out how to resolve that. If the symbol and the name are the same

The same applies to the two setup()-functions you want to merge. Also, duplicate parts usually need to be there only once (considering things like Serial.begin(...)).
Also the two loop()s are combined the same way, but if you make use of delay()s you must keep in mind that these will sum up in the final sketch, making it slower than the initial sketches were. It might also might (probably won't) work correctly. You will likely need to refactor your code to use millis() instead of delay().

After combining two sketches this way your global variables will be shared. You'll need to resolve any naming conflicts, or rename global variables that are different in your source sketches but should be the same. You may also have shared resources like sensors and LCD displays.

(Note that if the 2 sketches use the same resource for different things it gets more complicated, e.g. using the same pin for different purposes, using the same timer in both sketches, or using the same interrupt. Those things will require analysis and case-by-case changes.)


Can an interrupt function call a regular function? If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?

Yes, you can. You just have to make sure your function is reentrant.
If it accesses no memory beyond its parameters and (non static) local
variables, you should be fine. If it accesses global variables, hardware
registers, or static locals, it is unlikely to be, and only detailed
analysis will tell you for sure.

Beware also of the library functions you call: some of them are not
themselves reentrant and should therefore be avoided. See for example
the manual of strtok(), which explicitly addresses the
reentrancy problem.


Is it possible that function will get a parameter that can be int OR char? I'm trying to create a function that enters a key/value into a JSON file.

But, since value can be an int or char, I don't want to create 2 functions for each type.

Is there a way ?

void setValue(char *key, char* value){
        StaticJsonDocument<512> tempJDOC;
        tempJDOC[key]=value;
}

EDIT1

#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (char *key);

template <class T>
void setValue(const char *key, T value);
//void setValue(const char *key, char *value);

};
#endif

EDIT2

#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define LOG_LENGTH 4
#define DOC_SIZE 512

template <class T> // . <---- line added
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (const char *key);
void removeValue(const char *key);
// void setValue(const char *key, char *value); <--- comment out
void updateArray(char* array_key, int val);
void printFile();
void setValue(const char *key, T value); <---- Added

};
#endif

and in .cpp file :

void myJSON::setValue(const char *key, T value){
        StaticJsonDocument<512> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
        myJSON::PrettyprintJSON(tempJDOC);
}

In C++ you can create a template function. (The ArduinoJson [] operator is a template too.)

#include <ArduinoJson.h>

StaticJsonDocument<512> tempJDOC;

template <typename T>
void setValue(const char *key, T value){
  tempJDOC[key] = value;
}

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

  setValue("a", 5);
  setValue("b", "xyz");

  serializeJson(tempJDOC, Serial);
}

void loop() {
}

the compiler will create function based on this template for every different type you use as second parameter in your sketch


How to include userid, pass to WifiClient connect() api These are my remote server credentials that I want to connect from my local device.

Server  m12.cloudserver.com
User    <myname>
Password    <mypassword>
Port    19999
_ or
api_key 5678909876-009-00d

I want to use the WiFiClient client() API as shown, but where or how do I include the User credentials ? so that I can make a successful connection to the remote server from my device connected over Wifi.

Cut and paste from my Arduino code.

const int httpPort = 19999;
if (!client.connect("m12.cloudserver.com", httpPort)) {
 Serial.println("connection failed");
 return;
}

WifiClient provides low level tcp connection. Your server seems to be implementing a REST API interface. Thus you need to construct HTTP headers (GET, POST, etc.) manually as a string. Then you can add your credentials. Before doing so, try to use your server, I mean call api's with the program named Postman. Postman runs on Chrome browser. Postman can compose such headers for you. Then you can insert them into your arduino code.


Problem with while loops while detecting frequency of a signal I just started to use the unusual part of Arduino language (avr) like interrupts, accessing registers, etc in Arduino IDE. I wrote a program to calculate the frequency of a digital signal using external interrupts.

The following code is to calculate timeperiod of a digital signal, the output of the color sensor (TCS3200) which depends on the color filter choosen via S2 and S3 pins, as in the code. That is, color sensor produces 50% duty cycle square pulses of frequency dependent on the power of the light incident on it. So when sensor faces red color, output signal's frequency in red color mode (by setting S2, S3 pins) is more than the frequency in blue and green modes. Thus we can detect the likeliness of the color which it faces w.r.t  R,G,B.

When this code is uploaded in the Arduino, it failed to print the values as expected in the serial monitor i.e. its stuck in while loops. But when Serial.print(e) statement in the while loops are uncommented, it is able to print the required time periods. I am unable to figure out the problem here, which is making Arduino to be inside the while loop when no statements are in it.

// INT0 interupt is used i.e. digital pin 2
int ti=0,tim=0,e=0,S2=4,S3=5;

void Interruptinit() //initializing interrupt INT0
{
  cli();
  EICRA =  0x02; //Control register
  EIMSK =  0x01; //Mask register
  sei();
}

void setup()
{
  pinMode(2,INPUT);
  digitalWrite(2,HIGH); //enabling pull up register
  pinMode(S2,OUTPUT);
  pinMode(S3,OUTPUT);
  Interruptinit();
  Serial.begin(9600);
}

ISR(INT0_vect)
{
  tim=micros()-ti;
  ti=micros();
  e++;
}

void loop()
{
  digitalWrite(S2,0); digitalWrite(S3,0); //switching over red filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e) //waiting till interrupt is addressed 2 times
  ;
  Serial.print("red:");
  Serial.print(tim);

  digitalWrite(S2,0); digitalWrite(S3,1); //switching over blue filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" blue:");
  Serial.print(tim);

  digitalWrite(S2,1); digitalWrite(S3,1); //switching over green filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" green:");
  Serial.println(tim);

}

Whenever you modify non-local variables in an ISR, it's important that they are declared as volatile. This tells the compiler that the contents may change unexpectedly, ensuring it doesn't use out-of-date cached copies somewhere else. If you don't do this, the code can behave in unpredictable ways, such as outputting the wrong value under some circumstances.

Since the variables are bigger than 1 byte, it's also necessary to disable interrupts around non-ISR code which uses them (e.g. in loop()). This is because interrupts could be triggered at any time, potentially half way through an operation which reads/writes them.

You can use noInterrupts() and interrupts() to disable/enable interrupt handling.


Arduino Not Working as Intended when using barrel jack I am using an Arduino to control some mechanical components in a project I have. It controls a motor, two servos, a valve, and a compressor. When plugged into the computer, everything works fine and perfectly. However, when I power it through the barrel jack using our power supply, some weird things happen. First of all, our servos, which are powered through the Arduino, stop working. All the other components work except for them. Secondly, at the end of the code we have a 5 second delay. Using the computer it works fine. When powered with our supply the delay doesn't seem to happen at all. Any ideas?

i agree with majenko, maybe you know how to fix it but if you do not know here is a site with good information to make you're own  5 volt Regulated source.

http://www.rakeshmondal.info/IC-7805-Voltage-Regulator

sorry for my bad english and good luck. :D


Programming Arduino with FTDI via Tx and Rx pins How program Arduino with a FTDI cable/breakout_board via pins 0 (Rx) and 1 (Tx)?

In case the USB to UART chip (16U2 or other) is broken, you can program Arduino with a FTDI instead of 16U2 or other chip.

What are the connections to reset the Arduino microcontroller automatically when sketch is upload?

It's exactly the same as for a breadboard Arduino.  That is, connect the DTR pin of your breakout board through a 0.1uF capacitor to the RESET pin. TX and RX then connect to the RX and TX pins of the Arduino respectively, along with of course the ground connection.


FIFO overflow - reading IMU MPU6090 and GPS uBlox NEO-6M at once I am trying to read data from uBlox NEO-6m (I need just speed, just part of the code):

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup(){
ss.begin(GPSBaud);
}

void loop(){
if (ss.available())
    {
      gps.encode(ss.read());
      gps_speed = gps.speed.kmph();

    }
}

And in the same time I read data from MPU6090 using this code (gps code is integrated in it):

http://nevit.blogspot.de/2014/07/arduino-mpu-6050-pitch-roll-with-2.html

When I try to read data separately it works but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error ..

I tried to lower MPU data rate to 20Hz from 100Hz but it didn't work. I use Arduino UNO.

I am not so much skilled.. Any idea? Is it even possible to do it like this?

When I try to read data separately it works, but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error .

Yes, you have to be careful about the loop structure and "blocking" to "wait" for a new GPS speed report.  SoftwareSerial also blocks everything else during each received character time.

Just check for GPS characters and update the speed if a complete sentence was received, then do "other things" (e.g., use the IMU data).  Here is a NeoGPS version of your example:

#include "NMEAGPS.h"
#include <NeoSWSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

NMEAGPS gps;

// The serial connection to the GPS device
NeoSWSerial ss(RXPin, TXPin);

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

void loop(){

  // Read GPS characters and see if a new fix is available
  if (gps.available( ss )) {
    gps_fix fix = gps.read();

    //  A fix is available once per second, but the GPS may not know
    //  the speed value, perhaps because the satellite reception is
    //  poor or the unit is just starting.  Check the valid flag.

    if (fix.valid.speed) {

      // Update the gps_speed.  Other parts of your
      //   program can use it whenever they want.
      gps_speed = fix.speed_kph();
      Serial.println( gps_speed );
    }
  }

}

NeoGPS is smaller and faster than other libraries and can be configured to only parse the fields you really use.

Your original sketch uses 6884 bytes program space and 349 bytes of RAM.
The NeoGPS version can be as small as 4802 bytes program space and 150 bytes of RAM. Significant savings!

For the software serial library, I would suggest using AltSoftSerial on pins 8 & 9, if you can move the GPS.  It is much more efficient, and does not disable interrupts for long periods of time: SoftwareSerial will block for ~1ms, and eternity for a 16MHz Arduino.  This is probably interfering with the IMU interrupts.

If you can't move the GPS to pins 8 & 9, you might try another library I maintain, NeoSWSerial.  It is much more efficient than SoftwareSerial, and it works on any two pins.  NeoSWSerial will "play nicer" with the IMU interrupt code, but it can still be affected if the IMU interrupt code takes too long.  NeoSWSerial should not affect the IMU interrupt code.  I used it in the above sketch, along with a debug print.


Possible to have different torque levels on MG966R servo with Rotary Potentiometer? I want to apologise first and foremost, and say that I am very new to Arduinos!

I wanted to control the torque on a MG966R servo so that I can separate it into 4 different torque levels. I read that by adjusting the input voltage, you can run the servo at different speed, hence, i was thinking if I could incorporate a rotary potentiometer to adjust the speed of the servo.

Also wondering if changing angle stepsize of MG966R servo will affect torque in anyway?

Thanks all!

Generally it is not easy to control the torque of a standard servo, since mostly they aren't meant for that. A servo has an internal controller, which will read the input PWM signal and control the geared motor, so that the desired position will be reached. And to get there, the most servos will use the maximum torque. Also the torque of a servo motor depends on more variables, for example speed and type of load (See here for more information about this.

  I read that by adjusting the input voltage, you can run the servo at different speed

That's not really true. Most servos only support a rather small voltage range, where they will work. You can get more torque, if you use a higher voltage, but it is not a simple linear relationship, since the torque depends on way more variables. One way may be to always drive the servo to it's current maximum torque and change this maximum torque by changing the input voltage inside the working range. Though this might not get you 4 torque levels, that are different enough for you.

  Also wondering if changing angle stepsize of MG966R servo will affect torque in anyway?

It is unclear, what exactly you mean by "stepsize" here. If you mean to control the speed of the servo: Yes, it will affect the torque, but not in a linear way. And this greatly depends on the load, that you apply.

In the answer to this question, sensing the current of the servo is suggested as a measurement of (applied) torque. If you use a feedback loop with this, you might be able to control the (applied) torque. I haven't done this kind of thing, so I'm not sure, if this can really work.

That said, you should again think about wether a normal servo is really the best way to go here, since it controls electronics, that you don't control yourself. For example you may use a geared DC motor, which you can directly control without any other electronics getting in your way.


How can I get Serial.print to print a variable thats a char? I'm trying to write a function as part of my code, and the function basically has to write the name of a parameter, but I can't get it to print properly to the screen. Here is what I've got:

void dataprint(char parameterName, float dataNum, char unitName);
{
 Serial.print(",");
 Serial.print(parameterName);
 Serial.print(",");
 Serial.print(dataNum);
 Serial.print(",");
 Serial.print(unitName);
}

In the actual program part I have something like this:

char temp = "temperature";
float t = tempsensor.readTempC(); // just some number that comes from sensor
char unit = "C";
dataprint(temp,t,unit);

Right now in the serial monitor I get a question mark or something like that instead of the name I have saved in parameterName or unitName. I want this function to print the same way something like this would show up:

Serial.print(",");
Serial.print("temperature");
Serial.print(",");
Serial.print(c);
Serial.print(",");
Serial.print("C");

Thanks in advance for any help.

To make your code work, you must use character array pointers. A "char" holds only one character, while "char*" can point to a string.

char foo = 'a';
char *bar = "string with lots of stuff.";

So the full code to implement your example is:

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

void dataprint(char *parameterName, float dataNum, char *unitName)
{
  Serial.print(parameterName);
  Serial.print(",");
  Serial.print(dataNum);
  Serial.print(",");
  Serial.println(unitName);
}

void loop() {
  char *temp = "temperature";
  float t = 123.4;
  char *unit = "C";
  dataprint(temp,t,unit);

  while(1)
  {
    //do nothing
  }
}

Which prints the following to the serial port:

temperature,123.40,C


Transmitting multiple values to the arduino, and Interpreting them with minimum delay I am building an underwater robot, which can move Up/Down, Forward/Reverse, controlled by a Joystick.
The situation is like this :
USB Joystick is connected to a PC, PC is connected to an Arduino via tether cable (Ethernet), and motors of the robot are connected to the arduino.
The joystick I am using is having 2 sticks, and I have decided to use 1 stick to control the UP-DOWN movement (Actually, I'm using only 1 axis of that stick for this.) and the 2nd stick to control the LEFT-RIGHT movement.
My question is, Whenever the user manipulates both the sticks simultaneously (To achieve diagonal motion, for example), The joystick will send 2 signals, one after the other, one for each stick. Keeping in mind the limited receiver buffer size of the arduino, how do I program the arduino, such that it can understand the difference between linear motion signal and diagonal motion signal?
I am highly motivated to program this on my own. I just need an Intuition for this.
A thought came to my mind is, to use the following strategy:
For my Up-down stick value, I add a character such as 'U', followed by the integer joystick value. For E.g. I send "U4" to go up at speed 4. With some twitching, I can even send down signal with the same preceding character U.
Similarly, for Forward/Backward, I send "F3" to go fwd/bkwd at speed 3. And for diagonal, I send something like "T5" to go diagonally at speed 5.
My concern with this is, I will transmit 2 characters from the PC to Arduino. Will the arduino be able to read such 2 characters, interpret them and act accordingly, without the noticeable lag? Or is there any other better way?
This also makes me wonder, how commercial robots (such as Commercial Drones) handle such situations?
The movements the robot will make needs to be quick. There should not be "visible" lag, That is, the user should not feel that the Robot is responding after a couple of seconds.

I don't know about commercial drones, however your 'protocol' seems to be quite efficient, as it uses 4 bytes to send 2 values (e.g. U3F5) for Up with speed 3 and Forward with speed 5.
Let's assume values from 0-7. Then you can send them both in 8 bits/one byte:
H H H H V V V V
Where H is the horizontal speed (from -8 (000) to +7 (111), in total 16 possible values.
For the vertical speed you can do the same.
So within one byte you send both speeds (meaning also there is no lag).
In case you need more accuracy, than send two bytes: one byte with horizontal and one byte with vertical speed. Depending on the sending/receiving speed I doubt there is any lag.
Even with your protocol I doubt there is a lag, but the above is more efficient.
I'm sure even more efficient algorithms can be created, probably by using the difference with the previous value (like sending delta values).
Another algorithm that can be created, assuming there is a big chance that only one of the two directions is changed (either horizontal or vertical is) and having a high accuracy
D V V V V V V V

Where D is the direction (0 = horizontal, 1 = vertical) and V is the value/speed (-64 to +63, 7 remaining bits).