Implementation help with difference equation Implement the below difference equation
Y[n]=04142y[n-1]+0.2929(x[n-1])
Assuming an implementation
sampling frequency of 8khz
any help with code would be great :)

I assume what you want is a digital filter. Each time you collect a
sample x[n], you feed it to the filter, and the filter returns the
corresponding y[n] given by
y[n] = 0.4142 y[n−1] + 0.2929 x[n−1]
In order to compute this result, the filter has to remember the previous
value of its input (x[n−1]) and of its output (y[n−1]). You need two
variables for storing this information, which I would call x1 and
y1. Note that the filter doesn't need to remember anything older than
that, so there is no use in storing more data. No need to create arrays
for storing the whole x and y sequences. Since the values have to be
remembered between calls to the filter, they have to be global
variables. Alternatively, they can be local to the filter provided they
have the static qualifier.
Once you have those two variables, you just have to apply the formula to
compute y[n]:
static float x1, y1;  // x[n-1], y[n-1]
float y = 0.4142 * y1 + 0.2929 * x1;

There is just one more thing to take care of before returning y: the
variables x1 and y1 have to be updated in order to hold the
current values of the filter's input and output. This way, next time
the filter is called, the values will have the previous values, as
expected. The whole filter is then
/*
 * Single pole low-pass filter.
 * transfer function:   H = 0.2929 / (z - 0.4142)
 * recurrence relation: y[n] = 0.4142 y[n-1] + 0.2929 x[n-1]
 */
float filter (float x) {
    static float x1, y1;  // x[n-1], y[n-1]
    float y = 0.4142 * y1 + 0.2929 * x1;
    x1 = x;
    y1 = y;
    return y;
}

A few notes:

x1 and y1 are implicitly initialized to zero. This is common
practice, but a fact you should be aware of. If it doesn't fit your
needs, add an explicit initialization to the definition of the
variables.

If you need multiple instances of the same filter, storing the state
as static locals would not work. Instead, the filter should take a
pointer to a “state object” as an extra parameter. If you want to do
this the “object-oriented” way, the pointer would be called this.

Why use x[n−1] instead of x[n]? This just adds an artificial delay to
the filter without affecting its low-pass performance. When designing
low-pass filters, it is common to prefer short delays, everything
else being equal.


does EEPROM.write() only writes changed data? Do I understand the code in EEPROM.cpp / write() correctly, that val is only written to the EEPROM, if val differs from the current EEPROM contents at the given address?

And if the answer is yes, what is commit() doing?

From library Library, see fragment:

  EEPROM.write does not write to flash immediately, instead you must
  call EEPROM.commit() whenever you wish to save changes to flash.
  EEPROM.end() will also commit, and will release the RAM copy of EEPROM
  contents.

Probably to prevent too many writes into the same page (mostly EEPROM is divided in pages), the write stores it into some temporary buffer and the commit actually writes it to EEPROM. This decreases the number of writes, and since the number of writes has a maximum, the lifetime of the EEPROM is increased.

Update: Majenko's comment mentions no EEPROM is used, but flash, see below.


Saving Arduino output to a text file in append mode I used the code below to save output from an Arduino Uno to a text file.

The problem is whenever I run the code the old data in the text file is deleted.

I don't want the old data to be deleted, what should I change?

import processing.serial.*;
Serial mySerial;
PrintWriter output;
void setup() {
   mySerial = new Serial( this, Serial.list()[0], 9600 );
   output = createWriter( "data.txt" );
}
void draw() {
    if (mySerial.available() > 0 ) {
         String value = mySerial.readString();
         if ( value != null ) {
              output.println( value );
         }
    }
}

void keyPressed() {
    output.flush();  // Writes the remaining data to the file
    output.close();  // Finishes the file
    exit();  // Stops the program
}

There are a couple of ways to append to a text file.

You can either read the entire file in a temporary variable, then append the new data to it and then write to file.

you can implement using printWriter instead like mentioned here:
https://processing.org/discourse/beta/num_1267767630.html

Let me know if it works.


Communicating with I2C DAC (LTC2631) Firstly, let me say that I'm new to using I2C devices, especially with Arduino. I have an 8-bit DAC (LTC2631) that I'm trying to control with an Arduino Uno. I thought I would be able to use the standard Wire library protocol to talk to it, but I'm not getting any response. Here's what I've tried:

#include <Wire.h>

void setup() {

    Wire.begin();
}

void loop() {
    Wire.beginTransmission(0x11); //specify device's address

    Wire.write(150); //send a test value

    Wire.endTransmission();
}

Am I missing something obvious? Or are not all I2C devices compatible with  Wire?

Software:  Wire should be fine.  Of course, you usually will want libraries for each device.  This particular ADC is designed for automotive use and I could not find a specific library for it so you are correct that you will need to speak with it directly.  Here is the DATASHEET

I2C Hardware:  On the Arduino Uno, SDA is A4 and SCL is A5.

One thing you almost always have to do with I2C is to provide a 10K pull-up to +5 on each pin (SDA and SCL) - I use a small breadboard whenever I use I2C, so I have power, ground, A4 and A5 available for pullups and multiple devices.

The reason for this is that the I2C bus is active-low.   It signals by pulling the pins low in sequence to communicate.

If you already had the DS3231 RTC module on the same bus, which apparently you do not or you would not be asking this question, then you do not need your own pull-ups because the RTC includes them internally.

It might be easier for you to use a different I2C ADC such as the ADS1115.

Here is a generic search that shows the module:

https://smile.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=i2c+adc

Here is a generic search which shows the software side:

https://www.google.com/search?q=arduino+ads1115+ADC+library+download


Connection of a DS18B20 on a Arduino pro mini I'm actually trying to connect a DS18B20 sensor to a homemade board build with a ATmega328P processor running with a power of 3.3V and at 8 Mhz.

In order to get the address I wired the board as the following schematic on the pin 5 of my board.

To power the sensor and the pull up resistor I use the VDD output of my board which provides 3.3V.

For the code part I uploaded this:

// This sketch looks for 1-wire devices and
// prints their addresses (serial number) to
// the UART, in a format that is useful in Arduino sketches
// Tutorial:
// http://www.hacktronics.com/Tutorials/arduino-1-wire-address-finder.html

#include <OneWire.h>

OneWire  ds(5);  // Connect your 1-wire device to pin 5

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

void discoverOneWireDevices(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  Serial.print("Looking for 1-Wire devices...\n\r");
  while(ds.search(addr)) {
    Serial.print("\n\rFound \'1-Wire\' device with address:\n\r");
    for( i = 0; i < 8; i++) {
      Serial.print("0x");
      if (addr[i] < 16) {
        Serial.print('0');
      }
      Serial.print(addr[i], HEX);
      if (i < 7) {
        Serial.print(", ");
      }
    }
    if ( OneWire::crc8( addr, 7) != addr[7]) {
        Serial.print("CRC is not valid!\n");
        return;
    }
  }
  Serial.print("\n\r\n\rThat's it.\r\n");
  ds.reset_search();
  return;
}

void loop(void) {
  // nothing to see here
}

When I make it run on an Arduino Uno card I can get the address of the sensor but when I make it run on my card I only obtain this:

  Looking for 1-Wire devices...

That's it.

Anyone got a idea why it's working on an Arduino Uno but not on my card?

I finally made it work, thx @domen.

I looked at the other part of the schematic and found I was using the wrong pin - I have two LDO and the one I was using was deactivated for sensor.

Thanks all for your help.


Get the distance to non perpendicular surface So I'm using the HC-SR04 modules to get the distance to objects, the problem is that if it's not a perpendicular surface I dont get any reading, and I assume that the reason is that the ultrasounds get reflected in another direction, so they don't come back to the sensor. What's the way to get over this issue?

Thanks in advance

You mean to say that you get proper reading when the surfaces are FLAT?
Ultrasonic sensors have this property that the waves emitted from then are only 15 degree from the line of sight, but this means that you can surely calculate distance of objects having a curved shape. The only condition is the object should be directly in a straight line


Use Low Power Arduino with Solar Panel I am trying to create an arduino system with radio-transmitters and radio-receivers. The system runs from a rechargable battery that is charged with a solar panel. I am using a 1.1W 6V solar panel.

My problem is that I don't know how to make such a connection and I don't know what batteries to choose to power the arduino, assuming that I need it to run for 5-7 days without solar power and that the solar panel is good enough to recharge the batteries while they power the arduino. We are also assuming that the solar panel has 8 hours of sunlight.

To the arduino are connected the following sensors:

Flame Sensor
Light Resistor x2
Smoke Sensor
Radio Transmitter
Radio Receiver
DHT11 Temperature & Humidity Sensor

I am also looking to see if I can power down most sensors and power them on later if an event occurs. So probably all the sensors could be sleeping except the DHT11 and the Radio Receiver. Preferably though, if at all possible, the rest of the sensors should be on, if we can handle 5-7 days without the solar panel. I don't know if more information is needed but I'd be pleased to help out in the comments, or provide more information by editing the question. :)

You have far too many variables and unknowns there. Primarily you need to know what the average current draw for your circuit is. Secondly you need to decide how long the solar powers are allowed to take to recharge the battery. You have to think not only about runtime but also charge time. The charge time dictates the maximum capacity of the battery, and that then dictates the runtime of the Arduino. So here's some napkin maths to illustrate:

Assuming you want the battery to charge from almost flat to full within 8 hours, and with a 1.1W 6V solar cell, that gives you a peak of 183mA.

Assuming the Arduino circuit takes 83mA on average (let's give ourselves nice round numbers here) that leaves 100mA peak for charging the battery.

If you're charging at, say, 0.2C, that gives a full charge in 5 hours. 100mA / 0.2C = 500mAh capacity (at peak sunlight and current).

At 500mAh capacity and 83mA average current draw that would give you (0.5/0.083) 6 hours of runtime without the solar panels.

So that's just not going to work.  It'll be dead by morning.

Now assume that you can turn off everything for 99% of the time.  That effectively reduces our average current draw to 0.083*0.01 = 830µA. Let's plug that into the same reasoning as above.

Current draw = 0.00083A
Incoming peak current = 0.183
Available charge current = 0.183-0.00083 = 0.18217
Charge at 0.2C = 910mAh.
1Ah battery would charge in about 5.5 hours of peak sunlight.
1Ah would last about 1200 hours, or 100 days.

None of this takes into account varying light levels or light incidence angles. As a rule of thumb, take the light as averaging 50% over the course of the 8 hour period. You will only get 1.1W when the angle of incidence is 90° to the solar panel. At all other times it will be reduced. So if we reduce the current from 183mA to, say, 100mA, the charge capacity changes to:

Incoming peak current = 0.100
Available charge current = 0.100-0.00083 = 0.099
Charge at 0.2C = 496mAh
A 500mAh battery would charge in about 5 hours.
A 500mAh battery would run for about 50 days at 830µA average current.

So you see everything really hinges around the current consumption of the Arduino. How much current it consumes dictates how much is available to charge the battery, which in turn dictates the size of battery you can support, which dictates the amount of current you can draw for your desired runtime, which in turn dictates the amount of charge current available, which determines the size of battery you can support, which dictates ... etc.  You get the idea.

You can support larger batteries, of course - I illustrated this at 0.2C charge rate (that's 20% charge per hour to give a 5 hour charge time). As long as the net charge over time increases (so during the periods between the 5-7 days of complete darkness you gain more charge than is expended during the dark period - something which has not been specified) then it should function fine.

Also note that your battery voltage should be below your solar panel voltage. A 6V solar cell would be able to charge a 4.5V lead acid battery (assuming low dropout schottky protection diodes). Also the capacity of the battery depends also on what you determine your "cut-off" voltage to be. That's how low the battery voltage is allowed to go before your system is determined to be unworkable. This could be at a point where the battery is in danger of being damaged by over-discharge, or at a point where your circuit no longer receives enough voltage to function (which could be linked to oscillator frequency on ATMega chips), etc. For this reason it is often better to choose a board that is designed to run at a lower voltage (3.3V) and use high efficiency switching regulation to get the most out of your battery. A 5V Arduino is seldom a great choice.

Finding that right balance is now entirely up to you.

And, in answer to your other question, yes there are ways to turn things on and off. You can "sleep" the Arduino. You can use high efficiency power circuits. You can add power switching circuits (P-MOSFETs) to switch power on and off to other modules. All things can (and mostly should) be done to save power when running on batteries.


Connect a sensor to Arduino without knowing much info about the sensor I am planning to buy a formaldehyde sensor and I would like to connect it to an Arduino Uno board (and later to a Raspberry). As far as I know, the sensor comes in a small box/bag without any other external components (e.g. amplifiers etc.). So I will end up having in my hand a sensor with two copper terminals for connection (see image below):

Is it possible to connect this to an Arduino board without having a connection scheme? If yes, where do I connect the two terminals of this sensor to the 5V, GND and the A## ports? Also, how to translate the voltage coming from the sensor to ppm (parts per million) only by having general specifications from the manufacturer and not some kind of table of conversion? Also, would I need an external component for this? If yes, which component?

I know that this question sounds very stupid, but so far I've used sensors that come with a code on Seeed Grove with a clear description and I assumed that the code is there because there is a link between the producer of a certain sensor and Groove. Thank you!

FYI: The producer writes some things about the sensor but that doesn't help me a lot:

  This sensor is of the two-electrode electrochemical type, operating by the
  diffusion principle and as such requires no external sampling hardware. In
  the presence of formaldehyde gas a small direct current is produced; the
  sensor requires no power supply of its own but this current requires
  amplification to make it readable using external data collection
  equipment.

You have linked to the datasheet of the sensor.

In the datasheet, look at the "Application Circuit" section. You must build this circuit. The sensor produces a very small electric current, and the application circuit is high-gain amplifier to translate that very small electric current to a varying voltage you can sample with the Arduino ADC.

Note on the circuit, the wire labled "To ADC" -- that is the part which you connect to your arduino.

As for calibration, the datasheet itself notes that the process is non-trivial, or that they can perform a calibration, for an additional fee, at the time you order a batch of sensors. Presumably their calibration will include the precise resistor values used to set the gain of the amplifier, and also an equation to associate PPM values to the analog voltage provided at the "To ADC" wire.

As for reading the circuit diagram (schematic), you may already know resistors and capacitors. For the other items, search online for the part numbers given, to find out what they are.

The datasheet also notes that the application circuit is available pre-built from the sensor manufacturer. You may want to contact them to determine how to purchase one for yourself.

Most electronics products have a datasheet that explains all you typically need to know about the device, such as it's operating parameter minima and maxima, typical values, typical outputs, etc. This sensor is no different, except that the calibration procedure is not described in great detail due to the complexity.


MKR1000 - Connecting to Pubnub I don't know if it's a stupid question but I need some help.
I am trying to follow this tutorial and I want to connect my arduino to PubNub. In the tutorial it says that I have to 'open PubNub.h and switch the comments for the Ethernet and WiFi lines' with some code provided there. But, when I open the file PubNub.h the only thing in there is this:

/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#include "PubNubDefs.h"

class PubNub PubNub;

I'm quite new to this so I don't know much. I hope someone can help. Thank you in advance!

It appears the tutorial is now outdated and the PubNum library does not need the changes described in the tutorial.

The PubNub library has an example titled PubNubWifi101 which shows the client type being set with a #define before including the PubNub headers:

#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

I don't have a MKR1000 to test with, but I was able to compile the example from the tutorial by adding that single #define after the #include <WiFi101.h>.


GPS module not working with sensor I am connecting my Soil Moisture Temperature Sensor SHT10 with GSM Module SIM900A and GPS GY-GPS6MV2. Individually, all components work properly and give proper values. But when I interface all three components with Arduino, only Temperature sensor seems to work and GPS does not give any values.
Even If I connect only SHT10 and GPS with Arduino Uno (without GSM), only SHT10 gives values but GPS doesn't.

My code is:

#include <AltSoftSerial.h>
#include <TinyGPS++.h>
#include <SHT1x.h>

AltSoftSerial gpsSerial (11,12);

TinyGPSPlus gps;

#define dataPin 6
#define clockPin 7
SHT1x sht1x(dataPin, clockPin);
float TEMP, HUMID;

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

void loop()
{
TEMP = sht1x.readTemperatureC();
HUMID = sht1x.readHumidity();
Serial.println(TEMP);
Serial.println(HUMID);
gps_value();
}

void gps_value()
{
while(gpsSerial.available())
{
gps.encode(gpsSerial.read());
}

if(gps.location.isUpdated())
{
Serial.println("Latitude: ");
Serial.println(gps.location.lat());
Serial.println("Longitude: ");
Serial.println(gps.location.lng());
Serial.println("Altitude Feet: ");
Serial.println(gps.altitude.feet());
Serial.println("Horizontal Dilution of Precision: ");  //lower the better
Serial.println(gps.hdop.value());
Serial.println("");
}
}

What is happening here ?

Datasheet of SHT10

You could have used SoftwareSerial instead of AltSoftSerial.Since you are using AltSoftSerial please go through its library file to check how you need to deal with it.
For Software Serial you need to use predefined Rx , Tx pins of Arduino rather than defining any other pins of it for Rx,Tx
for connecting those to Rx Tx of tempterature sensor.
For GPS try to define any 2 pins of Arduino as Rx Tx so that you can connect them to Rx Tx of GPS.Hope this helps you.


Traffic lights using timer My traffic light code for the Arduino doesn't run. I was wondering if anyone could point out where my issues lie. The red and green LEDs should be on for 15 seconds and the amber on for 5 seconds.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint-gcc.h>
/*15 second interrupt*/
#define INTERRUPTS 975

/*
 * col = current colour of light.
 * 'g', 'a', 'r', 'o'
 */
volatile uint8_t count;
volatile char col;

ISR(TIMER0_OVF_vect)
{
    count++;
    if (count >= INTERRUPTS){
        if (col == 'g'){
            /*switch to amber*/
            col = 'a';
            /*reset counter*/
            count = 0;
            /*timer counter to 171 as we only need 85 clicks for 5s*/
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if(col == 'a'){
            col = 'r';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000100;
        } else if (col == 'r'){
            col = 'o';
            counter = 0;
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if (col == 'o'){
            col = 'g';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000001;
        } else{
            return;
        }
    } else{
        if(col == 'g' || col == 'r'){
            TCNT0 = 0;
        } else if(col == 'a' || col == 'o'){
            TCNT0 = 171;
        }
    }
    return;
}

int main(void)
{
    /* normal mode */
    TCCR0A = 0b00000000;
    /* prescaler = 1024 */
    TCCR0B = 0b00000101;
    /* enable overflow interrupts */
    TIMSK0 = 0b00000001;
    TCNT0 = 0;
    sei();
    /*Initialise output*/
    DDRD = 0b11111111;
    count = 0;
    col = 'g';
    PORTD = 0b00000001;
    while (1){
    }
}

#define INTERRUPTS 975

volatile uint8_t count;

if (count >= INTERRUPTS){

count is an 8 bit integer, so the maximum value of it is 255. Therefor count will never be bigger of equal to 975.

Use volatile uint16_t count; instead.

PS instead of messing with the TCNT0 register, I'd use 2 different values of INTERRUPTS to change between 15 and 5 second intervals.

Something like if( count>=975 || ( (col=='g'||col=='r') && count>=325 ) ){


if I add a .cpp file, Serial becomes unusable I am using the mega 2560. When I just use .ino and .h files, if I use Serial, it works fine, without even using:
#include <SoftwareSerial.h>

However, when I add a .cpp file I start getting 2 errors, one is solved by adding the aforementioned include, the second one, after adding it, is :
'Serial' was not declared in this scope

I know I can declare it manually and use the RX/TX pins, but I would like to be able to use the default Serial so that I don't have to occupy more pins. Especially since it works file w/o the .cpp file. Can anyone explain to me why this happens? Is it because I specify a C++ file so the compiler changes?

A CPP file isn't an Arduino file. It doesn't know about anything Arduino-esque unless you tell it about it.
The simplest way is to just add, at the top of the file:
#include <Arduino.h>


Servo motors not working when called upon using I2C So I'm using this movement() function inside the slave Arduino Uno, which basically handles two stepper motors and one servo motor. When I call this function through the Serial.read() of the Arduino Uno, it works perfectly, both the steppers and the servo.

I have a master Arduino Mega interfaced with the Uno (mentioned above) when I send a wire message from the Mega to Arduino to run the movement() function in the Uno, the steppers work fine, but the servo does not work. Although, again I mention that when the function is called upon using the Serial.read() of the Uno, it works absolutely fine.

I'm using an Adafruit motor shield on the Arduino Uno as well.

OK so this is the Uno (slave code)

void setup() {
  servo1.attach(9);
  Serial.begin(9600);
  Wire.begin(5);
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}

void loop() {
  //other stuff
}

void receiveEvent(int howMany) {
  while(Wire.available()) {
    char c = Wire.read();
    int From = Wire.read();
    int To = Wire.read();
    int x = 0;
    movement(From,To);
  }
}

int movement(int from,int to) {
  int X_From = from / 10;
  int X_To = to/10;
  int Y_From = from % 10;
  int Y_To = to % 10;
  /* First we have to get the motor position and move the motor to the from position */
  /* === START === */
  int diff_X = X_From - motor_X;
  int diff_Y = Y_From - motor_Y;
  int Y_Value = abs(diff_Y * Y_Steps);
  servoDown();
  if(diff_X != 0) {
    if(diff_X > 0) {
      /* Positive value means the X_Axis motor will move in the forward direction */
      int X_Value = abs(diff_X * X_Steps);
      X_Forward(X_Value);
    } else if(diff_X < 0) {
      /* Negative value means the X_Axis motor will move in the backward direction */
      int X_Value = abs(diff_X * 400);
      X_Backwards(X_Value);
    }
  }
  if(diff_Y != 0) {
    if(diff_Y > 0) {
      Y_Forward(Y_Value);
    } else if(diff_Y < 0) {
      Y_Backwards(Y_Value);
    }
  }
  Serial.println("Motor movement done");
  /* === END === */
  motor_X = X_From;
  motor_Y = Y_From;
  int diff_X_2 = X_To - motor_X;
  int diff_Y_2 = Y_To - motor_Y;
  int Y_Value2 = abs(diff_Y_2 * Y_Steps);
  servoUp();
  if(diff_X_2 != 0) {
    if(diff_X_2 > 0) {
      /* Positive value means the X_Axis motor will move in the forward direction */
      int X_Value2 = abs(diff_X_2 * X_Steps);
      X_Forward(X_Value2);
    } else if(diff_X_2 < 0) {
      /* Negative value means the X_Axis motor will move in the backward direction */
      int X_Value2 = abs(diff_X_2 * 400);
      X_Backwards(X_Value2);
    }
  }
  if(diff_Y_2 != 0) {
    if(diff_Y_2 > 0) {
      Y_Forward(Y_Value2);
    } else if(diff_Y_2 < 0) {
      Y_Backwards(Y_Value2);
    }
  }
  motor_X = X_To;
  motor_Y = Y_To;
  Serial.println("piece movement done");
  return 1;
}

void servoUp() {
  for (i = 100; i >= 0; i--) {
    servo1.write(i);
  }
}

void servoDown() {
  for (i = 0; i < 100; i++) {
    servo1.write(i);
  }
}

This is the master Mega Code:

void setup() {
  Wire.begin();
}

void loop() {
  //check if a condition appeared from sensor and then send the data to Uno to run the movement function through sendData()
  sendData(From,To);
}

void sendData(int From,int To) {
  Wire.beginTransmission(5);
  Wire.write('f');
  Wire.write(From);
  Wire.write(To);
  Wire.endTransmission();
}

Any suggestions what's wrong?

If you are using Servo library, which uses timer (and so interrupts) for manipulating the servos then you may have the problem, that from loop it works (as interrrupts are enabled), but from interrupt (ISR) it does not work, because while serving interrupt (from I2C) all other interrupts are (temporary) disabled.

In receiveEvent() you are inside interrupt serving, so other interrupts are disabled and so anything, what depends on interrupts does not work, until you leave the function.

So it is the more probable cause, why your servo does not move, while called from receiveEvent(), while it moves, if called from loop()

And you wait inside the interrupt routine, until all Wire input is read fully and then while the (slow, as it probabely involves mechanical components like motors or servos) movement(from,to) ends (if it can even end with interrupts disabled).

The solution would be to do all movement(..) in the loop and int the receiveEvent() just store the already aviable values and put them into some static volatile variables, when transfer ends together with mark, that some change was done.

static volatile int from;
static volatile int to;
static volatile int changed;

void loop() {
int my_from,my_to;
  if (changed) {
     noInterrupts();  // critical, time-sensitive code here
       my_from=from;
       my_to=to;
       changed=0;
     interrupts(); // enable interrupts, so I2C, servo and such can work again
     movement(my_from,my_to);
  }
}
void receiveEvent(int howMany)
{
  if(Wire.available())
  {
    char c = Wire.read();
    from = readInteger();
    to = readInteger();
    changed = 1;
  }
}

Not totally perfect (mainly reading the Wire, which I would just tak as much as is ready to some buffer and decode it only when buffer is sufficiently full and syntactically correct, but if would make the idea here more complicated), but should work much better, than the current version.

Better version of `receiveEvent can look like this:

char buf[20];
int buf_pos;
void receiveEvent(int howMany)
{
  while (Wire.available()) {
    buf[buf_pos] = Wire.read();
    buf_pos++;
    if (buf[0] == 'f') { // starts with known command
      if (buf_pos>= sizeof(char)+2*sizeof(int)) { // have all data already collected
        from=0;
        for (i=0;i<sizeof(int);i++) from=from<<8+buf[sizeof(char)+i];
        to=0;
        for (i=0;i<sizeof(int);i++) to=to<<8+buf[sizeof(char)+sizeof(int)+i];
        changed = 1;
        buf_pos=0;
        } // end of buf_pos>= ...
     } else { // not started with 'f' (or anything it should know) - throw all transfer away as bad
        while (Wire.available()) Wire.read();
        buf_pos = 0;
     }
}


Unable to initialize W5100 using Arduino Pro Mini I am unable to initialize a W5100 module using an Arduino Pro Mini. I try setting the MAC and IP addresses but read invalid values thereafter.

Here is the Arduino program along with the output:

void setup() {
    uint8_t mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    uint8_t local_ip[] = {192, 168, 1, 100};
    Ethernet.begin(mac, local_ip);
    printMacAddress(); // OUTPUT: FF:FF:FF:FF:FF:FF
    printIpAddress(); // OUTPUT: 255.255.255.255
}

void printMacAddress() {
    uint8_t mac[6];
    W5100.getMACAddress(mac);
    Serial.print(mac[0], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":");
    Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":");
    Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[5], HEX); Serial.println();
}

void printIpAddress() {
    IPAddress ip = Ethernet.localIP();
    Serial.println(ip);
}

I read in some blog posts that the Arduino may initialize before the W5100 initialization is completed so others recommend manually resetting the W5100 after Arduino initialization.
So I connected the W5100 reset pin to the Arduino digital output 4 and reset the W5100 during setup using the following code.

const int W5100_RESET_PIN = 4;
pinMode(W5100_RESET_PIN, OUTPUT);
digitalWrite(W5100_RESET_PIN, LOW); // Activate reset pin by asserting low
delay(5); // Wait for 5 msec
digitalWrite(W5100_RESET_PIN, HIGH); // Deactivate reset pin by asserting high
delay(300); // Wait for W5100 to initialize[/code]

I observed the W5100 resetting because the module LEDs flashed off and back on each time I manually reset the Arduino. However this does not fix the W5100 mac/IP initialization issue.

How should I troubleshoot this issue?

Here are pictures of the assembly.
https://imgur.com/a/h4TWx

Here is an overview of the W5100 module.
http://arduino-info.wikispaces.com/Ethernet

One of the Ethernet examples shows you should test the result of the begin function call, like this:

// start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

Try displaying the return value from begin to see if that initialization succeeded.


Inputting list of data Sorry if this question has been asked but I can't seem to find an answer because I don't really know if I'm phrasing the question correctly.

I'm trying to control a grid of LED to light up in a specific sequence that is based on a long list of data (and loops over time). Is there any way to bring in the data automatically? (vs individually coding the digitalWrites and delays) I think I found a reference project a few days ago but I lost it.

Thanks!

Your question is vague so I have made some assumptions, I hope they are right.

The first is I have assumed you are relatively in experienced at programming, I hope that's right otherwise the rest of this may seem patronising.

You have a number of LEDs arranged in a grid (lets say 3x3 to make life easy).
You are asking is there an alternative to doing this:

// Step 1
digitalWrite (LED1, HIGH);
digitalWrite (LED4, HIGH);
digitalWrite (LED8, HIGH);
delay (100);
digitalWrite (LED1, LOW);
digitalWrite (LED4, LOW);
digitalWrite (LED8, LOW);
// Step 2
// And so on...

Yes there are, and there are many, I think this is probably going to be the easiest to start with.

Coding the data in a 2D array.

An array is a fixed length list of values of the same type.  One obvious use for an array is to hold the pin numbers for you LEDS, rather than having LED0 through to LED8.

#define LED0 2
#define LED1 3
// and so on

Alternative array version

//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = {2, 3, 4, 5, 6, 7, 8, 9, 10};

I have declared the array as const because the values in it aren't going to change.  The array is going to hold integers (because that's what digitalWrite() takes as a pin number) and there are 9 of them.  Rather than use the literal 9 I have defined a constant because I know that value is going to be used elsewhere in the code and this means it is easier to change the number of LEDs.

So how does this help you?  Well you can define an array of 'steps' and each step has a list of which LEDs are switched on.  As your code loops through the steps it turns the specified LEDs, waits and then turns them off.  The simplest way to encode the data would be for each 'step' element to be an array of Boolean values (each true value indicates a light that should be on during this step).  I have chosen Booleans because it will use the least amount of space, which is always an issue on an Arduino.  Depending on the number of steps and LEDs you may need to look at alternative storage methods, like just the LEDs that are on, but it will do for now.

const bool theSteps[MaxSteps][MaxLEDs] =
{
    {false, false, false, false, false, false, false, false, false}
  , {false, true , false, false, true , false, true , false, false}
  , {false, false, true , true , false, false, false, true , false}
  , {true , false, false, false, false, true , true , false, false}
};

You still have to code the data within the program, but its much smaller

//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

const bool theSteps[MaxSteps][MaxLEDs] =
{
    { false, false, false, false, false, false, false, false, false }
    ,{ false, true , false, false, true , false, true , false, false }
    ,{ false, false, true , true , false, false, false, true , false }
    ,{ true , false, false, false, false, true , true , false, false }
};

#define StepDelay 100

void setup()
{
}

void loop()
{
    for (int onOff = 0; onOff < 2; ++onOff) // Turns the LED on and off
    {
        for (int step = 0; step < MaxSteps; ++step)
        {
            for (int led = 0; led < MaxLEDs; ++led)
            {
                if (theSteps[step][led])  // If the LED should be on
                {
                    digitalWrite(LEDPins[led], (onOff < 1) ? HIGH : LOW);
                }
            }
        }
        if (onOff < 1)
            {
                  delay(StepDelay);
            }
    }
}

I'm afraid I haven't tested any of this code (it might not even compile) but the theory is right and it should give you a shove in the right direction.


RF remote control using VirtualWire on ATtiny85 running at 8MHz on internal oscillator I'm trying to make an RF remote control using ATtiny85 running at 8MHz on internal oscillator, this cheap RF 434MHz transmitter module (like the one below), and VirtualWire lib, but had no success so far.

So, before I go any further, is it possible to use VirtualWire with ATtiny85 running at 3.6V and 8MHz with its internal oscillator? If so, how?

I've found a few scattered sources of information on the Net about it, but couldn't make much sense of it.

I have build ATMega328 versions of the receiver and transmitter using VirtualWire without any major problems. Both modules talk to each other will very little data drop out. Now, when I tried to replace the ATMega328 transmitter with a smaller version using the ATtiny85, I'm having problems.

Here are the symptoms:

The major one seem to be that when I add the VirtualWire include, my sketch seems to slow down a lot. So I figure it's a timing issue. But I'm not sure what the problem is.
I put a scope on ATtiny85 pin 6 (PB1) but I don't see anything being transmitted. I think I've messed up with the pin names.
I can make the LED blink and also can read the buttons without problems.

Here are the schematics and the board design for the remote controller:

The board is currently powered by 2 AA NiMH batteries that are currently at 2.6V. I can make the ATtiny85 blink with that voltage. I plan to power the RC with a 3.6V CR2 lithum battery.

Here are more details of my development enviroment:

Arduino IDE 1.05
I'm using ATtiny cores from here
I'm programming the ATtiny85 using an Arduino UNO R3 as ISP, without problems (it's working as I can make the ATtiny85 blink an LED).

And here's my code:

#include <VirtualWire.h>

#define VCC_PIN  A1
#define BTN_PIN  A2
#define LED_PIN  A3
#define TXD_PIN  PB1

#define BLINK_UP_TIME  25

#define BUTTON_NONE  0
#define BUTTON_1     1
#define BUTTON_2     2
#define BUTTON_3     3
#define BUTTON_4     4
#define BUTTON_5     5
#define BUTTON_6     6

void setup()
{
  pinMode(BTN_PIN, INPUT);
  pinMode(TXD_PIN, OUTPUT);
  pinMode(VCC_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

  // leave RF transmitter off for now
  digitalWrite(VCC_PIN, LOW);

  // Initialise the IO and ISR
  vw_set_tx_pin(TXD_PIN);
  vw_setup(2000);    // Bits per sec

  // let the user know we are alive: heartbeat
  blink(3, 50);
  delay(1000);
}

uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

void loop()
{
  byte button = ReadButtons();
  if (button != BUTTON_NONE) {
    // transmit button pressed
    digitalWrite(LED_PIN, HIGH); // Flash a light to show transmitting
    digitalWrite(VCC_PIN, HIGH); // turn tranmitter on
    delay(10);
    buf[0] = button;
    vw_send(buf, 1);
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(LED_PIN, LOW); // turn off LED
    digitalWrite(VCC_PIN, LOW); // turn tranmitter off
  }
  delay(100);
}

byte ReadButtons()
{
  unsigned int buttonVoltage = analogRead(BTN_PIN);
  byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn
  if      (buttonVoltage < 10)   {    button = BUTTON_1; }
  else if (buttonVoltage < 200)  {    button = BUTTON_2; }
  else if (buttonVoltage < 400)  {    button = BUTTON_3; }
  else if (buttonVoltage < 550)  {    button = BUTTON_4; }
  else if (buttonVoltage < 720)  {    button = BUTTON_5; }
  else if (buttonVoltage < 900)  {    button = BUTTON_6; }
  else if (buttonVoltage > 1000) {    button = BUTTON_NONE; }
  return( button );
}

So, What's wrong with my setup?

I tried those Tiny cores you are using and had a lot of problems. I switched to http://code.google.com/p/arduino-tiny/ and it seems much better. Create a second Arduino installation folder and add the arduino-tiny cores.  The pin name constants are like PIN_A0, PIN_A1,...,PIN_B1, etc. So, try that out.

I looked briefly at the VirtualWire code and there are ifdefs specifically for the Attiny85, so it should work.  Here is a derivative project with working ATTINY85 examples: http://cosa-arduino.blogspot.de/2013/03/news-virtual-wire-interface.html


Using malloc() and free() for a stack/linkedlist I know this question has been asked before, however it was asked two years ago and I have some other constraints to add.

(Previous question here) : Is using malloc() and free() a really bad idea on Arduino?

I understand that dynamically allocating and freeing memory can cause fragmentation, and without an operating system to manage the memory, this fragmentation can reach a point where no memory can be allocated because the current memory is a mess.

That being said, the only memory allocation I plan to do is for a linked list that I am using as a stack. This means that I will only even be adding or removing from one end of the linked list. In the case that the arduino malloc() implementation is 'next fit', is it safe to assume that I can use this linked list safely, since the only element I'll be removing is the next one that fit, and everything else will stay where it is?

tl;dr the two questions I'm asking:

Is the arduino malloc implementation 'next fit'? Where can I read up on this in detail?

AND

A single stack running in a 'next fit' environment will never cause fragmentation, correct?

On my answer to the question you are referencing, I state that “If
you use the heap like a stack (last in is first out), then it will
behave like a stack and not fragment.” This seems to be exactly your
usage pattern, thus you should not fear fragmentation. Of course, the
caveat written in Michel Keijzers’ answer applies: you should make sure
that no other part of your code, including libraries, is using
malloc() and free().

Just to give some evidence, the avr-lic documentation provides some
implementation details about malloc:

  When allocating memory [...] If nothing could be found on the
  freelist, heap extension is attempted. [...] When deallocating the
  topmost chunk of memory, the size of the heap is reduced.

All this can be seen in action in the source code of malloc() and
free(), which is abundantly commented and quite readable.

Edit 1: From the same section of the avr-libc documentation, we learn
about how realloc() grows a memory chunk:

  If [...] the old chunk is at the top of heap, and the above freelist
  walk did not reveal a large enough chunk on the freelist to satisfy
  the new request, an attempt is made to quickly extend this topmost
  chunk (and thus the heap), so no need arises to copy over the existing
  data.

Based on this, I would suggest you use an array, rather than a linked
list, and use realloc() to adjust the size of the array. A linked list
of n objects of size m has a memory cost n × (m+4):
each objects has an overhead of 2 bytes for the linking pointer, plus 2
bytes for malloc()'s internal bookkeeping. The cost of an array would
be only (n × m)+2.

In this case, however, it is essential that no other part of your code
uses malloc(), otherwise realloc() could end up allocating a whole
new array, which would be very costly.

Edit 2: I wrote a small test program that randomly grows and shrinks
a memory buffer. Running the test on an Uno shows that the allocated
memory chunk never changes address even though its size varies wildly.

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

void loop()
{
    static void *p;
    static size_t sz;
    sz = random(max(sz, 22) - 20, min(sz + 20, 1536) + 1);
    p = realloc(p, sz);
    Serial.print((uintptr_t) p);
    Serial.print("  ");
    Serial.println(sz);
}


Instantiate class in the constructor rather in the top end? Is there a way to define class variables in the constructor or in a method rather than at the top of the document?
I have the following code in my custom library:
#include "DHT.h"

// DHT settings.
#define DHTPIN 7 // Digital pin connected to the DHT sensor.
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.

void DhtLib::doSomeStuff() {
  dht.begin();
  float temp = dht.readTemperature();
  ...
}

I would like to be able to set the pins with a function. But for this to work I have to find a way to define the dht variable in a different place than at the top of the document within the // DHT settings.. Best would be in a method such as:
void DhtLib::begin(int dhtPin) {
  DHT dht(dhtPin, DHTTYPE);
}

This works, but only within this function. I need this to be accessible in the entire document, not just a single function.
How can I achieve that?
EDIT 1:
Entire code of the custom DhtLibrary.h file:
#ifndef DhtLibrary_h
#define DhtLibrary_h

#if (ARDUINO >= 100)
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class DhtLib {
  private:
    DHT dht;
    float readTemperatureFromDHT();
    float readHumidityFromDHT();
    float calculateHeatIndex(float temperature, float humidity);

  public:
    // Constructor.
    DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}

    // Methods.
    void begin();
    String getHumiTempJson();
};

#endif

The error with this above code is:
In file included from /home/myuser/Documents/Codes/temperature-control/slave2-arduino/slave2-arduino.ino:2:0:
DhtLibrary.h:12:5: error: 'DHT' does not name a type
     DHT dht;

There's numerous ways of doing this. The best is probably to have a DHT object as a class property and set it up with an initializer list:
#include "DHT.h"

class DhtLib {
    private:
        DHT dht;

    public:
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}
        void begin();
        void doSomeStuff();
};

void DhtLib::begin() {
    dht.begin();
}

void DhtLib::doSomeStuff() {
    float temp = dht.readTemperature();
}

DhtLib thing(7);

void setup() {
    thing.begin();
}

void loop() {
    thing.doSomeStuff();
}


Midi Timecode Fails to Send I have an ATMEGA 2560 platform running HIDUINO and a sketch based on the stock MIDI library. I'm intending to use it to convert Linear Timecode (LTC) to MTC. Got a long way through the project - LTC decoding working fine, timer configuration OK, and Midi output working fine. It's just that as soon as I try and generate MTC messages, they are being dropped before they land on the computer USB interface.

Equipment to hand: Macbook Pro running El Cap/Reaper and Protools., ATMEGA2560 MEGA R3 (With 16u2 for HIDUINO) and small audio interface circuit.

Using Timer 4 for LTC Decoding and Timer 5 for MTC generation (4 messages per LTC Frame).

Midi Monitor on the OSX box.

Sees Note on/Note off packets quite happily, but no MTC messages are registering.

I do note the TX LED is active during MTC Message generation, indicating that the sketch is actually generating messages and sending them to the 16u2 chip.

Specifically, my question is how do I get the MTC messages through HIDUINO into the computer?

https://pastebin.com/pAXyq04s

If you clone my fork of the code, I have got this working.
https://github.com/mwr9uk/mocolufa

I have generated a pull request to merge it with mainline.


Is there a way to pause Program execution? I understand that Arduino programming is procedural and not so much Object Orientated and also that the Arduino or AVR are only single core processors and any kind of "Multitasking" or "Threading" is emulated at best but I was wondering if there is a way to pause program execution in one area temporarily and give another area control? For example say we have the following class:

Class A{
   void Test();
   void ProgramLoop();
}

void A::Test(){
   for (int i = 0; i < 10; i++){
      //Lots of cool stuff going on here but need to give
      //Control to someone else say ProgramLoop()
      Sleep(10);
   }
}

void A::ProgramLoop(){
   Serial.println("In Program Loop");
}

Then in the main file:

A testClass;

void Setup(){
   Serial.begin(57600);
}

void Loop(){
   testClass.Test();
   testClass.ProgramLoop();
}

I know I could do something like:

void Loop(){
   if (!testClass.isBusy){
      testClass.ProgramLoop();
   }
}

But I am trying to find out if there is a way to control how the program execution gives control? I understand that this is more of a threading topic, thats not what I am trying to get at, I just want to know if this is possible maybe using some sort of built in function or something? Or do my programs have to "Fall Through" being ONLY Procedural?

This article gives a great example of multitasking by using FreeRTOS.

I am pasting the sample code snippet which is pretty much self explanatory.

#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

// the setup function runs once when you press reset or power the board
void setup() {

  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // Stack size
    ,  NULL
    ,  2  // priority
    ,  NULL );

  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"
    ,  128 // This stack size can be checked & adjusted by reading Highwater
    ,  NULL
    ,  1  // priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);

  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
  }
}


Multiple rgb control plus calculation help Hi me and a friend is making a computer shelf with leds in the woodwork, were using a special glue for the plexiglass in the shelf which means we're using individual rgb leds, four leds for each window (3 windows) and what I need help with is, amount of voltage, ampere, code and how to connect all this up. I've used 123d.io to sketch something up but I'm struggling with getting proper strength in the leds.

(code https://puu.sh/lI6PC/e214028b07.txt)

Aswell as some of them change colors as the picture here shows:

I'm very new at these things so I really appreciate all help and advice (and from an earlier post, reason for not using strips is purely based on the method of build, the shelf will not sit correct if the strips were in use)

It's not advised to connect leds in parallel, with only one common resistor. Slight difference in forward voltage of the leds will create big current differences. This will make some leds appear brighter that neighboring leds. It can also damage the brighter led since too much current can flow through them. So you need to add a resistor to each led, and common the other side of these resistors to the transistor.

Second bigger error is that there isn't any resistor between the arduino pin and the base of the transistor. Without it there is nothing limiting the current going into the base, which could fry the arduino pin.


How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)? I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library.

First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?
In case the answer to the previous question is "yes", then you can just cast it on the fly:
int int_val = (int)function_returning_longint();
In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution:
int int_val = function_returning_longint() >> 8; This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like int8_t and int16_t. And in your case you might have to shift by a different value than 8.

Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.


Fading led with push button I need to make for school a project. That when i hold a button it fades. But when you let go the button it needs to stop immediately. But when i you hold the button again it needs to start again with fading but the brightness needs to start from 0. I have a program but when i press again it just starts from the previous brightness. Pls help. This is my code:

int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
}
}

The main problem is you have to reset brightness to 0 when the switch is LOW. Btw, I did not test the sketch, only compiled it.

int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
  brightness = 0;    // Restart with brightness 0
}
}

Some other improvements result in:

#define LED_PIN      9
#define DELAY_TIME 100
int brightness = 5;
int fadeAmount = 5;

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

void loop() {
  int switchButton = digitalRead(2);
  Serial.println(switchButton);

  if (switchButton == HIGH) {
    analogWrite(LED_PIN, brightness);
    brightness += fadeAmount;
    if ((brightness <= 0) || (brightness >= 255)) {
      fadeAmount = -fadeAmount;
    }
    delay(DELAY_TIME );
  }
  else {
    digitalWrite(LED_PIN, LOW);
    brightness = 0;    // Restart with brightness 0
  }
}

Explanation

Always indent your code (so that { and } are clear, notice each new { increases the indentation by two spaces, each } decreases the indentation by two spaces.
For values that do not change use a #define. This prevents (in this case) a few bytes not be stored in valuable memory space. Especially if you would use arrays this is important.
You used 9 in digitalWrite(9, LOW); which was probably a mistake, always use defines wherever possible. I also would use #define DELAY_TIME 100 instead of the hardcoded 100 value.
I addes some spaces before/after values (like switchButton == HIGH). It doesn't matter if you do or not, but be consequent.
Use good variable names (switchButton is more clear than val.
Use brightness += fadeAmount; instead of brightness = brightness + fadeAmount;; this is the normal way of increasing (or decreasing/multiplying/whatever) the value of a variable.
Use ( and ) in non trivial if statements like if ((brightness <= 0) || (brightness >= 255)), this could save you hours of searching in case you ever make a mistake (in this case there is no functional change).

Good luck with your project.


How do I check if a password is right? (keypad input) Im having a problem with my arduino code.Im trying to make an alarm system with a pir sensor.So when the pir activates and the buzzer starts buzzing i want to be able to type a set password in the keypad and the buzzer should stop buzzing. since my passcode is 4-digit (1331) I wrote this code, but it`s not working.

 while(i<=4,i++)
{
char key = keypad.getKey();

pass.append(key);
}
if(pass.evaluate())
{
  digitalWrite(buzzer, LOW);
    keypad.waitForKey();
    delay(6000);
}

My idea is that the program checks 4 times for the pressed key and adds it to the guessed password (im using the password library and the password is defined as well as int i=0;)
But for some reason when I type 1331 the buzzing continues. Please help me with that project and excuse my grammar, English is not my native language.

edit:
the full code:

#include <Password.h>
Password pass = Password( "1331" );

#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int i = 0;

const byte rows = 4; //four rows
const byte cols = 4; //four columns
char keys[rows][cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
keypad.waitForKey();
digitalWrite(buzzer,HIGH);
  delay(125);
  digitalWrite(buzzer, LOW);
  delay(6000);

}

void loop() {

  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    while(i<4,i++)
    {
    char key = keypad.getKey();
    //keypad.waitForKey(); not sure if i should use that

    pass.append(key);
    }
    if(pass.evaluate())
    {
      digitalWrite(buzzer, LOW);
        keypad.waitForKey();
        delay(6000);
    }

  }
      }

Without knowing how the pass.* works, it will be impossible to pinpoint the problem.
'key' gets an ASCII value. Is that would you are expecting?
Does pass.* reset (start over) once 4 digits?
Just a guess, but I believe that *.waitForKey() does not consume the key.
The algorithm only gets the key four times; then, it checks.


Why does an Arduino UNO need two GND ports? I have really bad eyesight, so whenever I plug in the power wire and the GND wire I always double check if I'm actually plugging in to the power port not one of the two GND ports.

Why does an Arduino UNO have two GND ports, and for what application would one use both of them?

In electronics circuits, a major point in connecting two circuits and make them "talk" together is to ensure, at the minimum, that they have a common reference of voltage (typically called GND and defined as 0V voltage).

On Arduino, GND pins can be used in 2 situations:

to directly power the Arduino with an external supply which cannot be plugged to USB or power jack. In this case, the positive voltage of that external power source shall also be supplied to Vin pin.
to connect Arduino GND to your circuits.

Having 2 distinct GND pins is, I think, just a matter of convenience when you want to build prototypes but don't necessarily have a breadboard (if you use a breadboard, you will just need to connect its power rail to Arduino GND pin and use this power rail directly).


unexpected primary-expression before ';' token I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch.
 My code is :

include #include<Servo.h>
int pos = 0;

Servo myservo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  myservo.attach(9);
}
void loop() {
  if (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  if (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.

What am I doing wrong???

1) You should be using:

myservo.write(pos);

instead of

servo.write(pos);

for all of your  methods.

2) Change:

include #include<Servo.h>

to

#include <Servo.h>

This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)

*Verify that your board will work, I know Mega, Uno and Nano will function properly.

P.s. Here is the whole code in correct format:

#include <Servo.h>

int pos = 0;

Servo myservo;
void setup() {
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 myservo.attach(9);
}
void loop()
{
  if ( (digitalRead(2) == HIGH) && (pos < 180)) {
    pos++;
    myservo.write(pos);
    delay(15);
  }
  if ( (digitalRead(3) == HIGH) && (pos > 0)) {
    pos--;
    myservo.write(pos);
    delay(15);
  }
}


16 X 2 LCD display blank with Arduino Uno So I am following this tutorial to make my arduino display hello world and millis(), I got it to work for a minute, but then it stopped updating the milliseconds, and when I pushed the reset button it went blank. since then, It has been blank but I have double, triple, and qaudruple checked checked my wiring, and it is flawless. I tried it with both of my 16 segment displays, but to no avail. I have redone the wiring, but it is still blank. Does anybody know what I could be doing wrong?

I followed this diagram
this is my code:

// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

This is the result (the screen is lit up, but there is no text even when turning the potentiometer)

It is most likely that I wasn't providing enough power to the arduino, and or had the potentiometer set to the wrong point. according to this post, you shouldn't run the arduino and display off of USB, because it may not actually be providing 5 volts. So I plugged it into the wall using a DC adapter. It now works.


Arduino Nano 33 battery power/charging I have a project with an Arduino Nano 33 BLE Sense. My project is working great, but I need to transition it to battery power, and I'm having a bit of confusion about exactly what's required.

I have a small 3.7V Li-ion battery I'd like to use (similar to this one {0}) if possible.

I have read what seems to be some conflicting information, so I'd like to see which of the following are true:

I can power the Arduino directly from the 3.3v pin? I'm suspicious of this advice since on the datasheet the 3.3v pin is marked output only. There's a note on the product page that says:

  Note: for ultra low-power functionality, you should cut the 3V3 jumper on the back of the board, and use an external battery at 3V3.

Is this something I should do? It seems difficult to reverse, I'm worried I might break my project.

I can power the Arduino directly from the VIN pin? This again seems to contradict the datasheet, which says the VIN pin can only handle 4.5 - 21V. 3.7V is less than this.
I could use a Step-up DC-DC transformer - like this {1}? I'd rather not wait for shipping from China.

Furthermore, I'd like to be able to charge the battery, so if I use a charging board like this one {2}, would that just work?

I don't want to connect the battery anywhere it might not be welcome for the risk of frying anything. Any help would be appreciated.

Link references (in case ebay listings go away):

0: Lithium Ion Battery - 110mAh

1: Mini 3V 3.3V 3.7V 5V 9V to 12V Step Up Boost Converter Module Voltage Regulator

2: 4.2V 5V 1A Micro USB Li-ion Battery Charger TP4056 Protection Chip Lithium-ion

The VIN (and the USB) goes into a 3.3V switching regulator. This has a minimum input voltage of 4.5V.

You isolate the output of that regulator from the rest of the circuit by cutting that one link (which is easy to re-solder). You are then free to feed 3.3V from your own power source directly into the board.

Yes, if you provide more than 3.3V you are liable to damage the board (note that a Li-Poly can be around 4.2V when fully charged).

You need to take your battery power and feed it through a nice efficient switching voltage regulator that has a low enough "dropout" voltage to allow good use from the battery. Note that many devices "rated" at 3.3V will also work much lower. For example:

Nina-B3 series module will run at down to 1.7V.
The APDS-9960 will operate down to 2.4V.
The HTS221 will run at down to 1.7V.
MP34DT06J can go as low as 1.6V.
LSM9DS1 can run from 1.9V.
LPS22 is 1.7V minimum

So it could be good to reduce your power to 2.5V instead of 3.3V to give more life from the battery. You should check each of the components in the both the device schematic and the rest of your circuit (by reading the datasheets) to find the highest "minimum" voltage they will work on.


Unable to terminate "void loop" I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.

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

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end void loop so that TX light goes off.

The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the loop() function. Not to be pedantic but to clarify the use of loop, the simple answer is, "you can't". loop() is called from a forever loop in the C/C++ main program, function main(), so returning from it, either with a return statement or by reaching the final close } causes loop() to be called again. This is intentional as the main() function in an embedded system is never supposed to return, thus it must keep re-running the application program.

Update (since this question just reappeared on the front page, I'll add the following to my answer):

loop() reads and prints continuously. If you had wanted that code to be executed only once, you could put in setup() and leave loop() empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty loop() and remaining there until power-down.

A way to execute the loop function once is to write an infinite loop at the end of it, so loop() would never return and thus never be re-executed:

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);

  while(1)
     ;
}


7-Segment Common Anode I accidently bought a "Common Anode" 7-segment display instead of a "Common Cathode".

I understand that the polarity of the leds within the display is 'reversed'. So instead of putting the common pin on GND I have to put it to 5v (with current limiting resistor)

My questions on this are:

Can I still use only one current limiting resistor on the common pin? Instead of a resistor on every segment pin.
Can I use the pins from arduino to drive it (withouth pull-up/pull-down?) By making the signal LOW the current will flow from 5V common anode to the arduino and thus the segment wil light?
Can I still use a shift register to drive the segment led? (By inversing the outputs (in software))

Obviously I would like to have wiring more like this (but then I would ofcourse change  the GND line to a 5V line.

The wiring below is the worst-case wiring I can think of.

^ So can I avoid this, when using a Common Anode 7-segment display or am I forced to buy a Common Cathode 7-segment display?

You can use a single resistor on the common pin if you want. The problem is that lighting up multiple segments at the same time will substantially reduce the brightness of each one. You could work around that by lighting each segment one at a time in very quick succession though.

It should be possible to control the display directly from the IO pins by setting them LOW. In this configuration, they will be sinking current (rather than sourcing it). It depends on the specification of the display and on what resistor you use though.

Basically, try to keep the current below 20mA and it should be OK (assuming you're using a standard 5V Arduino). For example, if each segment has a forward voltage drop of 2V, you would want to use a resistor of around 180 Ohm.

Controlling the display directly from a shift register is probably not possible, although once again it depends on its specification. Shift registers usually aren't designed to sink enough current so you'll need something like a transistor on each output.


RGB LED using potentiometer and push button I'm currently working on an assignment which has to turn on an RGB LED using a potentiometer and button. The problem I currently have is that the button is supposed to change the color I want the LED to display (presses one time: red (pin9), again green (pin10), again blue (pin11)). As I'm changing through the ports with the potentiometer, the potentiometer will read it with as analogWrite. For example, if I move the potentiometer all the way to the left and press the button the LED will display red and move it back all the way to 0 and press the button twice the LED will stay red (do nothing). If I press it one more time it will turn off. Another example, I turn on red again, then use green and turn off blue using the potentiometer and button giving me orange. How do I make it so to accomplish all of this while using both and combining colors?
THIS IS A HW QUESTION AND NOT ASKING FOR A WHOLE SOLUTION BUT RATHER WHERE TO START BECAUSE I ALREADY GOT STUCK AND WANT TO RESTART PER SE
Edit:I solved my doubt! Thanks for the help!

You method sound a bit more complicated that it needs to. What I would do is have the button switch between three colors, and have the potentiometer change the brightness of the currently selected color.
For example, when first starting up, the red led is selected. Turning the potentiometer changes the brightness of the red led (in real time). Let's say you turn it 50%, so the red led is at 50% brightness. When you're happy with that, you press the button, and now green is selected. (Since the potentiometer is still at 50% from the red, the green led will immediately turn on at 50% brightness.) You can then turn the pot to change the brightness of the green led. Let's say you turn it all the way of to 0%. Then press the button to select the blue led. Turn it to 100% and the combined color would be a dark purple. Press the button again to select red again.
Here is some proof of concept code:

byte selectedColor = 0; // 0:red, 1:green, 2:blue
byte oldButtonState = HIGH;

void loop() {
  byte buttonState = digitalRead(buttonPin); // read the button
  if( buttonState==LOW && oldButtonState==HIGH ) // see if the button is pressed, but wasn't pressed the last time
  {
    selectedColor++; // to to next color
    if( selectedColor==3 )
      selectedColor = 0;// after blue, go back to red
  }
  oldButtonState = buttonState; // remember the buttons state for the next loop

  int brightness = map(analogRead(potPin), 0, 1023, 0, 255);

  if( selectedColor==0 )
    analogWrite(redPin, brightness);
  else if( selectedColor==0 )
    analogWrite(greenPin, brightness);
  else
    analogWrite(bluePin, brightness);
}

PS I left out the pinMode stuff in the setup.
PPS make sure the led leads are connected to PWM pin on the Arduino (they have a ~ next to them on the PCB).


How do I use SNAP protocol, correctly? I've reviewed the documentation

I'm still a little lost when it comes to applying the functions. Each of the redundancy check methods take in an unsigned char and return an unsigned char.

Shouldn't there be some sort of boolean return somewhere confirming that the data is accurate?

I've been trying to debug unsigned char* tempData = "snap" to the terminal, writing it directly to the register, according to the doc it should return h17:

  UDR0 = crc8(tempData,sizeof(tempData));

The terminal outputs '?' - as if it cannot be read.

The crc8 function calculates the Cyclic Redundancy Check (8-bit) value for the data you provide. It is then up to you to compare that calculated value with the CRC you have received.

The ? you are seeing in the serial terminal is an unprintable character. It is representing an 8-bit value that doesn't lie within the 32-127 range of normal ASCII characters, or 32-255 of the extended ASCII character set.


Detect if Serial1 and Serial2 are defined, at compile time I have my library that uses Serial, Serial1 and Serial2 to establish various logging scenarios. Library user would define the config at class constructor, using simple byte constants like 0, 1 and 2.

Problem is, Serial1 and Serial2 are not available in all board types. So when I compile my code (that compiles fine on Mega) on Uno, I get error
'Serial1' was not declared in this scope.

So I figure I need to adjust my code with preprocessor directive like #if defined, in order to include some code only if Serial1 is defined. But it wouldn't work, because Serial1 is defined later, at compile-time. So what is the accepted way to do this?

HardwareSerial.h in Arduino AVR boards core defines HAVE_HWSERIALX

example

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif


In Linux how do I start up Atmel Studio I am using Linux Fedora 20. In order to compile C programs for the Arduino, as described in the book "C Programming with Arduino" by Warwick A Smith, pub by Elektor, I have downloaded and untarred/unzipped "avr8-gnu-toolchain-3.5.1.1671-linux.any.x86.tar.gz". That's as far as I can get. Please how do I proceed from this point? Is there anything else I need or should have done?

Atmel Studio is a windows only product.
The only way to run it on linux is in a virtual machine running windows.


What is the maximum power consumption of the Arduino Nano 3.0? What is the maximum power consumption (in mW) of the Arduino Nano 3.0, when it is running in its default state (at 16MHz, no LEDs removed) and powered by an external regulated 5V supply so it bypasses the built in voltage regulator?

This will give us an upper bound on the power consumption of the Arduino Nano that can be used during estimates.

Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.

If you ONLY want to power the Arduino, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )

Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf

The USB chip draws around 15 mA depending on several things (p 18)
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf

Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led)
(5-2)/680  = around 4 mA per led.

So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4*4) = 33.4 mA

33.4 mA * 5V  = 0.167 Watts

I suspect you want to know to the total amount of power the Arduino can source, which is a bit harder to calculate.

The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf)
So 33.4 + 200 = 233.4

I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.

280 mA * 5 = 1.4 Watts

Let me know if my numbers are way off.

P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a linear regulator, like the LM7805. or maybe the LM317


How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does? MyProject.ino:

#include "MyClass.h"

void setup()
{
  Serial.begin(9600);
  // MyClass.MyStaticMethod();
  MyClass::MyStaticMethod();
}

Both uncommented lines work, but the commented (when uncommented, of course) results in this error: expected unqualified-id before '.' token.

Now, I know this is because of the incorrect scope-resolution. Yet, how come Serial manages to call static functions without the need to use :: to correction to scope-resolution.

How come MyClass.MyStaticMethod() doesn't work, but Serial.begin() does?

. is used to call a method on a class instance whereas :: is used to call a static method within a class itself.

There is no Serial class - Serial is merely an instance of the HardwareSerial class.

#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

If you want to use . then you have to instantiate your class and not use a static method:

class MyClass {
    static void myStaticMethod() {
    }
    void myMethod() {
    }
};

MyClass Fred;

// ...

Fred.myMethod();
MyClass::myStaticMethod();


Seeing consistent serial data loss over USB, have ruled out hardware and rx/tx software. What's left? I have a Lasersaur, which is an arduino-based open-source laser cutter. Part of its capabilities is raster engraving, where you etch images based on pixel data, rather than vector data. Recently I started experiencing a weird issue where I am losing some of the data that I am sending over serial to the machine, and the end of the image gets cut off. I don't believe those details are relevant to this question, but you can read my posts here for more info.

Basically, on my old Laptop B, engraving works. If I use the exact same USB hardware connection, firmware, frontend software executable, engraving settings, and image file on my current Laptop A, I see bad results. The last ~20 pixels or so of each image line are not etched in, and the only reason I can think for this is that the color data for these pixels were not sent in the first place. Notably, Laptop A used to work a few months ago when I last tried this out. So I'm pretty confident that I've ruled out hardware and rx/tx software as the possible issues.

The only difference between the two machines that I can think of that has changed since then is that I installed the Windows 10 1909 update, as well as some other software that I would have to dig back through to list out. I'd really like to not do a fresh Windows reinstall on my primary machine, but I'm close to that point.

Could something there be causing an issue? I'm out of my depth at this point, and don't know how either the operating system or another program could be affecting serial data transfer, and wouldn't know the first way to narrow it down.

Some more thoughts which may or may not be important:

There does not seem to be data corruption, only data loss. The rx/tx protocol implements some error detection (sends every byte twice and checks for equality), and I am not seeing error corruption messages that would pop out if that were the case.
There does not seem to be any randomness. The same behavior happens for images of different widths (leading me to think that the tx buffer isn't filling up), is the same for each image line, and has always been consistent.
The Arduino in the machine is an Arduino Uno R3. Compilation is done using the Arduino compiler on some custom C code (not though the IDE).

The driver board for your "Lasersaur" appears to be based around the Adafruit Trinket Pro.

That board, on Adafruit's website, is deprecated, with the following warning:

  Deprecation Warning: The Pro Trinket bit-bang USB technique it uses doesn't work as well as it did in 2014, many modern computers won't work well. So while we still carry the Pro Trinket so that people can maintain some older projets, we no longer recommend it.

So basically the USB interface is naff. It's too slow to keep up with modern computers (hence your old laptop works but your new one doesn't), and you lose data.

You should look into the possibility of upgrading the controller board to something a little more modern and capable.

For UNO R3 based boards there is another fundamental flaw: there is a 64 byte receive buffer and no flow control.  That means if you send data too fast - faster than the board can process it - data will be lost.


Why were Atmel MCUs used for Arduino? Atmel microcontrollers are not cheap compared to STM and Microchip. Why did Arduino select Atmel MCUs such as atmega328 and atmega2560 on their board out of so many alternatives?

Simply because the Wiring system that Arduino stole was written for the Atmel chips.

Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino.


EtherCard library without TCP I have connected some sensors to an Arduino Uno (but the final code should run on a Pro-Mini) with an ENC28J60 shield. The sensor code works fine - until I add EtherCard. I tried UIPEthernet first, but it's even worse. The problem is the memory footprint. The ethernet libraries are consuming so much memory that random malfunctions do occur.
So I was thinking about removing TCP from the EtherCard library, because I don't need it anyway. I only need IP, ARP, UDP, and based on that DHCP, DNS and NTP.
Has someone already done this?
Is there a stripped-down library?
The file tcp.cpp is pretty big (the biggest in this lib). Is it safe to remove all methods with "tcp" in their name?
Or is there a better solution for this situation?

My EthernetENC library based on the original UIPEthernet library by Norbert Truchsess has settings to balance performance and memory usage. These settings are in utility/uipethernet-conf.h file or can be specified as -D parameters for compilation.
UIP_CONF_MAX_CONNECTIONS is a maximum number of connected EthernetClient connections. The default value s 4. You can set it to 0 if you don't use EthernetClient TCp connections. It will save a lot of dynamic memory.
Arduino IDE doesn't have the possibility to set defines for a sketch (For example Sloeber has it). As some workaround to set the defines for different boards for Arduino IDE, you can create a file boards.local.txt next to boards.txt file in hardware package. Set build.extra_flags for individual boards.
comment by OP:

Setting uno.build.extra_flags= -DUIP_CONF_MAX_CONNECTIONS=0 in "boards.txt" in the arduino IDE folder reduced program memory usage by 2442 bytes and dynamic memory usage by 290 bytes.


Arduino Leonardo - disabling the debugger port My Sketch program is working perfectly as a specialized keyboard application on the Leonardo. I want to disable the development tools drivers from the USB, (COM PORT) leaving only the HID Keyboard drivers.  I understand I will need to use the Arduino ISP or other method to load my code.

Is there any way to disable the drivers for the development tools from the on board USB, leaving just the HID drivers?

There is no easy way, no. You have to reprogram the core to break the connection between the USB interface and the CDC/ACM driver. That means working out a new set of descriptors, deleting chunks of code, patching around the newly created holes, etc.


Power supply while using a shield Sorry if this is a dumb question, I'm new to Arduinos. I'm planning to use a MOVI voice shield with SparkFun's RedBoard Turbo (3.3v). The RedBoard Turbo requires a power supply under 6VDC, but the MOVI website recommends a power supply of 9VDC to the Arduino, because the MOVI can't have its own power supply. Will this destroy my RedBoard? Or is this safe and just something you have to do when using shields? Thank you.

The product website says: "A 7V to 16V 500mA external power supply that powers MOVI™ through the Arduino board. The power consumption of both boards is just above what the USB port can provide. If you don't have already one, this 9V adapter from Adafruit will work perfectly."

Although I have not used either SparkFun's RedBoard Turbo or the MOVI voice shield, reading the specifications, which you can find on their respective web sites, it would appear that they have incompatible power requirements.
The SparkFun's RedBoard Turbo board web page says

The barrel jack connection on the RedBoard Turbo has a lower input voltage than most Arduino development boards. Make sure that you are using a power supply below 6V. Please be aware that the RedBoard Turbo is also a 3.3V device and not a 5V one like the original RedBoard.

Whilst the MOVI voice shield PDF manual (page 7) says

What you don’t see in Figure 1 is a power supply jack. MOVI is powered through the
Arduino board that needs to be powered using an external power supply. The external
power supply should provide between 7V and 16V and at least 500mA current. During tests
we usually used either 9V or 12V. Battery packs with this specification work as well.

So the one needs less than 6V whilst the other more than 7V. I don't know if you can break the power connection between the two boards and feed the MOVI from a separate supply (9V is very common in the Arduino world) or you may have to swap your SparkFun for an Arduino that runs on 5V and uses a 9V supply.

The gotcha is that Arduino boards, their clones and code compatible boards such as the ESP32 etc fall into 2 different groups, those that run on 3.3V and those that use 5V, and you must be very careful you don't over voltage the latter.

I haven't delved into the specifications further, but you will almost certainly find that the logic levels used by the two boards are also incompatible. One will be using 0 & 5V whilst the other 0 & 3.3V. Connecting a 5V logic output to a 3.3V logic input is not conducive to long life and happiness for the latter.


Asynchronous function calls in Arduino sketch In an Arduino sketch, is there a way to make asynchronous function calls within the loop? Like listening to requests through http server and process them in a non-blocking way.

Yes and no. You're kinda vague on what you want to do. I've made this into a few different sections (mainly focused on reading sensor data... it applies to everything but that's the context I'm using):

Threads

AFAIK all Arduinos only have one core (they can do one thing at once). For most Arduino boards, hardware multithreading isn't supported. However, there are ways to implement software multithreading. The approach by AsheeshR wouldn't work well for functions that take a long time to complete (i.e. something in a library that takes a while, or a delay) because it would get jammed up by those instructions, but it would work well for short functions like pinMode(). The Protothreads library listed there might be better at this, but I don't really know.

It'd be hard to orchestrate this with HTTP, especially since you have to make

Delays

A common way for a sketch to stall is the use of a delay. This can be solved by using, in the main loop, a if statement and the millis() function that returns a time (not a clock time, but rather the time since the Arduino started). You could also do a loop within the loop to poll sensor data.

The millis() approach wouldn't work well with things that cause the whole program to stall (i.e. more delays or loops that last a noticeable amount of time). Note that 100ms IIRC is the general maximum time to make a UI not seem laggy.

Interrupts

Interrupts are a great way to keep things almost asynchronous. They run a short piece of code (that you specify) every time a pin state changes. It breaks from the loop(), and goes back where it left off once the "ISR" has been ran. I don't have much time to explain how to do this, but a quick Google search will yield a lot of results.

As far as you example, the threading section would be the most applicable. This topic is pretty vague, so you'll have to experiment with a few things and find something that works.


Sending IR (NEC)-Signals with Arduino I have an Arduino Micro where I want to control a display with IR commands. So the Arduino should send the IR commands to the display.

I have found a library "Arduino-IRremote", which I am using to transmit Commands to the display. The display works perfectly with its remote control, however I can't get it accept signals from my Arduino.

Now the special part about my setup is, that I do not use a "classic" IR transmitter. Instead i uset an IR cable, which is connected to "IR-In" of the display. So no LED - only a wired connection. The IR-cable consists of 3 wires. 2 for power supply (VIN and GND) and one is for the data connection. The wire with the data connection is connected with the Arduino PWM pin 3 (like it is said on the example in the linked library), but I tried all other pins anyway.

#include <IRremote.h>
IRsend irsend;

void loop() {

  for (int i = 0; i < 2; i++) {
    digitalWrite(RXLED, HIGH);
    irsend.sendNEC(0x004eff71, 32);
    Serial.println( "sendNEC 00 4E FF 71" );
    digitalWrite(RXLED, LOW);
    delay(40);

  }
  delay(1000);
}

004eff71 is a NEC-Command from the original remote control

Now can somebody tell me, what I'm doing wrong? The program compiles and the LED lights up, everytime it should send the NEC-command. But still the display receives nothing.
What is wrong?

It isn't working probably because the output of the Arduino isn't simply an on/off signal.

That library uses a pulse width modulated output on the Arduino to drive an LED.  When the LED is "on" the signal driving it is actually pulsing at a very high rate.

I don't know what all you'd have to change to make that work with a direct wired connection.

Another thing that might becausing problems is that without checking, you can't be sure that the signal level you are sending matches the levels that the IR receiver would normally produce.


Creating a library for arduino I found a really nice 24 bit I2C adc which was fairly cheap as well (ADS1219) but as far as I could tell there are no libraries for it so I decided to make my own. I have managed to write functions and get everything working on the arduino itself but I've been having massive issues with converting it into a library.
So I tried a very basic sketch to see if I can do something as simple as printing hello world using the library.
Here is my ADS1219.h file:

#ifndef ADS1219
#define ADS1219

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

class ADS1219{
public:
 ADS1219();
 void begin();
 void printHello();
};

#endif

And the ADS1219.cpp:

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#include

ADS1219::ADS1219{
 Serial.println("New object created!");
}

void ADS1219::begin(){
 Serial.begin(9600);
}

void ADS1219::printHello(){
 Serial.println("Hello World");
}

and my main sketch:

#include

ads = new ADS1219;

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

void loop() {
  ads.printHello();
  delay(2000);
}

but I get this really long error which basically says I've failed with creating the ads object.
I tried ADS1219 ads; as well but same error ... not sure what's wrong tbh.

Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

In file included from sketchADS1219.cpp:7:0:

ADS1219.h:14:11: error: expected unqualified-id before ')' token

   ADS1219();

           ^

ADS1219.h:12:14: error: an anonymous struct cannot have function members

 class ADS1219{

              ^

ADS1219.h:18:1: error: abstract declarator '' used as declaration

 };

 ^

ADS1219.cpp:9:17: error: expected id-expression before '{' token

 ADS1219::ADS1219{

                 ^

ADS1219.cpp:13:21: error: explicit qualification in declaration of 'void begin()'

 void ADS1219::begin(){

                     ^

ADS1219.cpp:17:26: error: explicit qualification in declaration of 'void printHello()'

 void ADS1219::printHello(){

                          ^

In file included from C:UsersOM222ODesktopadslibadslib.ino:1:0:

ADS1219.h:14:11: error: expected unqualified-id before ')' token

   ADS1219();

           ^

ADS1219.h:12:14: error: an anonymous struct cannot have function members

 class ADS1219{

              ^

ADS1219.h:18:1: error: abstract declarator '' used as declaration

 };

 ^

adslib:3:1: error: 'ads' does not name a type

 ads = new ADS1219;

 ^

C:UsersOM222ODesktopadslibadslib.ino: In function 'void setup()':

adslib:7:3: error: 'ads' was not declared in this scope

   ads.begin();

   ^

C:UsersOM222ODesktopadslibadslib.ino: In function 'void loop()':

adslib:11:3: error: 'ads' was not declared in this scope

   ads.printHello();

   ^

exit status 1
expected unqualified-id before ')' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Your problem stems from this line:

#define ADS1219

You define the macro ADS1219 as empty. From that point on all references to ADS1219 get replaced with nothing. For example:

class ADS1219{
public:
 ADS1219();
 void begin();
 void printHello();
};

becomes:

class {
public:
 ();
 void begin();
 void printHello();
};

And

void ADS1219::begin(){
 Serial.begin(9600);
}

becomes:

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

By using the same name in your header guard as your class name you screw everything else up.

I always use strict rules for header guard macros to ensure that they never conflict with anything else.  You should change yours to read something else.  I would use:

#ifndef _ADS1219_H
#define _ADS1219_H

// ... content

#endif

You are also lacking the parenthesis in the constructor implementation:

ADS1219::ADS1219{
 Serial.println("New object created!");
}

should read:

ADS1219::ADS1219(){
 Serial.println("New object created!");
}

And you don't give your ads variable a type and you don't want to use new:

ads = new ADS1219;

should read:

ADS1219 ads;


That is a perfect printout of a GPS system that can see zero satellites.

The fact that the timestamps are one second apart shows that you have correctly interfaced with the GPS device. Now, the GPS device has to 'interface' with the satellites!

Many people don't realise two things:

The GPS antenna really does need a clear view of the sky. A tiny view through a window may show one or two satellites, but you need a minimum of three, and preferaby four or more at a number of points around the sky to get a fix.
If the GPS unit has been completely powered off (called 'cold'), when it first powers on it has NO idea where anything is. It simply listens for any signal anywhere until it "hears" the current time. It can then guess where satellites might be, and listens for updates on satellite positions.

All of this listening, guessing and waiting takes time before it can start to actually lock on to satellites and start to get a fix. This time could easily be 90 seconds or more - you need to be patient. Check your GPS device specifications for "cold start" times.

Edit

I'm impressed! The GY-NEO6MV2 that you list has a cold-start of 27 seconds - but that assumes it has a clear view of the sky.


Determine difference between 3.3V and 5V shields How do you determine if an Arduino shield uses 3.3V or 5V on their pins?

Previously, I thought all Arduino shields used 5V, since that's what most  Arduinos use. However, I've been researching Arduino-compatible single-board computers like the PCDuino and Galileo, but these all seem to use 3.3V. More confusingly, they're vague about what types of Arduino shields they support. The PCDuino claims to only support 3.3V shields, but has an adapter shield to convert 5V. The Galileo has a jumper to support either 3.3V or 5V shields.

The main problem is how do you determine what voltage level Arduino shields use? I have a Seeedstudio motor shield and a Sain Smart sensor shield, and while they both take 5V power input, the docs don't mention anything about logic voltage level. How do I determine this?

You read the schematics and datasheets. The former will tell you what power supplies are connected and how, and the latter will tell you what voltages are acceptable to the devices.


My Ultrasonic sensor is only showing 4cm range? I am using an ultrasonic sensor SR04 with Arduino Uno and a sample program which I got from the library. However, my output reading is only 4 cm even when there is no object in front of it. I even used another sample program which had the same output. Is the problem in sensor or library?

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Looks to me like your powering the SR04 with 3.3v instead of 5v.


Draw polygon on LCD from GPS latitude and longitude I'm working on a personal project  (a usefully tool based on ublox GPS and Arduino Mega that can measure distance between 2 points, compute area, speed, save data on SD card)

Now I want to add new feature and when I show the area(in m^2) on LCD, I want to show the polygon built by more coordinates.

I tried all I know, I searched for solutions but without success.

How can I "scale down" coordinates to make them fit in a x,y system with max size (320*480, LCD size) ?

Over a small area lat and long are just simple Y and X coordinates respectively.

Dynamic scaling of the points is a very simple matter.  All you need to do is work out the range of each dimension - so subtract the lowest latitude from the highest, and the lowest longitude from the highest.

That gives the full X and Y dimension of your area. Then just divide those by the dimensions of your screen.  That gives you a scaling factor for each direction.

For each point, subtract the lowest longitude and latitude, and divide by the scaling factor for each direction.

If you want to be more fancy and retain the aspect ratio then you just need to work out which of the two scaling factors will allow all the polygon to remain on the screen - that is, divide and offset all your points by one factor, then by the other, and pick the smallest factor where all the points are within the area of your screen.