attiny85 reset itself instead of wakeup procedure I have a digispark attiny85, and I am using SLEEP_MODE_PWR_DOWN to sleep, and wake-up with external interrupt on pin2. I am trying to count number of interrupts received with the code below.

Problem is on every LOW signal on pin2, attiny85 reset (restart) itself instead of processor wake-up and continue where it left. I can identify this by seeing led blink 3 times(as in setup()) on every LOW signal.

Is there a limitation on this hardware? How can I only wake-up from sleep and not reset? I appreciate if you direct me an example.

#include <avr/interrupt.h>
#include <avr/sleep.h>

//modified from http://playground.arduino.cc/Learning/arduinoSleepCode

int ledPin = 0;            // LED connected to digital pin 0
int interruptPin = 1;      // LED to show the action of a interrupt
int wakePin = 2;            // active LOW, ground this pin momentary to wake up
unsigned int counter = 0;

void setup(){
  pinMode(ledPin, OUTPUT);         // sets the digital pin as output
  pinMode(interruptPin, OUTPUT);   // sets the digital pin as output
  pinMode(wakePin, INPUT_PULLUP);        // sets the digital pin as input
  digitalWrite(wakePin, HIGH);
  counter = 0;
  //do some blinks so we can identify boot & loop
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
}

void sleepNow(){

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                          // enables the sleep bit in the mcucr register so sleep is possible
    attachInterrupt(0, wakeUpNow, LOW);     // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
    digitalWrite(interruptPin, LOW);

    sleep_mode();                          // here the device is actually put to sleep!!

    sleep_disable();                       // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);                    // disables interrupton pin 3 so the wakeUpNow code will not be executed during normal running time.
    delay(250);                           // wait 2 sec. so humans can notice the interrupt LED to show the interrupt is handled
    digitalWrite (interruptPin, HIGH);       // turn off the interrupt LED

}

void wakeUpNow(){        // here the interrupt is handled after wakeup

  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
 digitalWrite(interruptPin, HIGH);
}

void loop(){
   digitalWrite(interruptPin, HIGH);
  //digitalWrite(ledPin, HIGH);            // sets the LED on
  counter++;
  delay(5000);                           // waits for a second
  sleepNow();                      // sleep function called here
}

I found this, I can confirm it is working. on digispark attiny85.

void sleepTillChg() {  // 0.02ma drain while sleeping here
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT0);                   // Use PB0 (was PB3) as interrupt pin
    // Turn off unnecessary peripherals
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    ACSR |= _BV(ACD); // Disable analog comparator

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep ... Zzzz

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT0);                  // Turn off PB0 (was PB3) as interrupt pin
    sleep_disable();                        // Clear SE bit
    sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
    // This is called when the interrupt occurs, but we don't need to do anything in it
}

credits should go
https://www.instructables.com/id/3-Minute-Game-Timer/


Can I make existing libraries use external SRAM for the Arduino I am running out of memory on my Arduino due to the libraries I am using. After I have included all the libraries I need then there is very little in the way of free memory for my own code.

If hook up some external RAM to the Arduino, is there a way I can make existing libraries use the external RAM rather than the SRAM on the arduino or will I need to alter the code in the library to do it.

If I have to modify the code is that a relatively easy thing to do?

Making a library use external SRAM is not an easy task. It can be cone, but it takes quite a bit of work.

The best start would be to abstract the SRAM into a library that provides simple access to it. Then you would need to use that new library to read and write data in the SRAM instead of accessing variables in the other libraries.

There is no way of simply mapping a variable into external SRAM - for that you need a microcontroller with an MMU  and/or an EIB.


Negative currentmA and Shuntvoltage Why is my INA219 current sensor gives a negative currentmA and Shunt voltage?  My sensor is connected in a glucose test strip connector. The current is from a glucose biosensor? Is it possible that my INA219 is damaged?

The "sign" of the INA219 shows the direction of flow of the current. Current isn't either "positive" or "negative", it has a direction. The sign is just used to represent that direction.

It's like a car. It has a speed. That speed could be in the forward direction, or the reverse direction.  It could be going 5 miles per hour forwards, or 5 miles per hour backwards. Either way, it's 5 miles per hour. However the backwards direction could be represented as "minus 5 miles per hour". It doesn't mean that you're doing a negative speed (there is no such thing), but that your speed is in a "negative direction".

This "speed" and "direction" are combined together to create "velocity", which is "speed relative to some arbitrarily chosen 'normal' direction and speed".

At this point the "velocity" can be represented as a 2D vector, with forward velocity in the + direction, and reverse velocity in the - direction.

But that's all a bit of a digression. All it means is that the "-" is meaningless if you don't care about the direction of current flow. If all you care about is the quantity of current you can discard the "-" completely.  The simplest way is:

current = abs(current);


Building a GPS-controlled Camera I've been trying to build an Arduino UNO controlled Camera using two servo motors that points in the direction of an object with a certain tag.

Here's an Example: A camera is on the sideline of a gym, and the players are running around. One player has a portable GPS piece attached to him, and the camera should point in the player's direction in order to capture the player's movements along with his background.

A few questions:
Would I use two different compasses in order to both record the direction and point the camera in this direction? Or would I use a GPS for the player and somehow convert the streaming data into compass direction(in which the camera will point)?

In a way, what combination (Player-Camera) would I use (if I need a combination), a GPS-GPS, GPS-compass, or compass-compass?

Do I actually need two location devices or just one?

Thanks,
Mark

Take a look at the uTube site of "iforce2d". Chris has a couple of GPS projects, which use a GPS and nRF24L01 transceivers to implement a "GPS tag" and he has a model car follow the tag. He also has a ground station with a pan and tilt and a camera following his quadcopter (drone). Lots of useful stuff there.


Arduino UNO SPI Serial Clock (Pin 13 SCK) gives no output, but Blink Example (Pin 13 LED) works I was attempting to use an SPI library and DAC device (Library AD57X4) for the first time, when I realized that the Arduino UNO Pin 13 was not outputting a clock signal (something I expected it to do).

Using a serial analyzer I can sample at 16MHz, yet nothing comes out of UNO Pin 13 except maybe a very occasional noise blip.  After no luck with the AD57X4 library, I wrote this simple program to try to get SPI clock signal on UNO Pin 13.  Setting UNO Pin 13 to OUTPUT makes no difference.

#include <SPI.h>

void setup() {
  //pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

I do get a signal on UNO Pin 11 (MOSI), frequency 381 kHz.  This signal is due to SPI.transfer(0x00); , as it disappears when the line is removed.  Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 11 (MOSI) signal.

The Blink Example Works:

    // the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

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

I tried monitoring UNO ICSP header pin 3 (SCK), however there is no signal for either the SPI or Blink programs.

UPDATE:
I switched over to an Arduino NANO that I had around and was able to get this output.  I expected the clock to be high frequency and continuous for SPI.  The MOSI output is the same 381 kHz that I observed earlier.

#include <SPI.h>

void setup() {
  pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

EDIT:
Here is a schematic of my circuit.  I am using an EVAL-AD5754R Evaluation Board from Analog Devices.  Here is a link to the AD5754 chip data sheet.  I'm providing 5V power through the J7 terminal (via the UNO), and supplying the SPI connections through the J8 header. The EVAL-AD5754R board works perfectly via USB and their software, but now I am transitioning to controlling it through Arduino/SPI.  As you can see I'm temporarily using a 12V battery for the analog voltage supply - this is until I build a regulated circuit.  J8 DGND pins are shown unconnected on the schematic below, but I've tried connecting one of them to the UNO's GND to no effect.

This is the configuration of the linkers which act to configure the eval board:

This is an annotated table describing J8 header connections (UNO <-> EVAL-AD5754R):

I can't reproduce that. Using your first test code:

#include <SPI.h>

void setup() {
  //pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

I get this on the logic analyzer:

Also on my scope on pin 13:

As expected, a 4 MHz signal with gaps between the bytes.

  I expected the clock to be high frequency and continuous for SPI.

No, you get the clock when data is being transmitted and not at other times.

  Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 10 (MOSI) signal.

That would be the Timer 0 interrupt kicking in (roughly every 1 ms) and thus interrupting your looping code for a few microseconds.

Possible solution

Try enabling slave select (write LOW to pin 10). I think some versions of the logic analyzer ignore incoming data if the slave isn't selected.

In fact, pin 10 should be an output, otherwise the SPI hardware goes into slave mode. Some versions of the library might not set it to output.


Is there any problem in running Arduino logic to 12V LEDs? I want to run a strip of 300 12V LEDs (Adafruit Neopixels with WS2811), with my Arduino. Is it safe to connect a follows, or is there some "separation" between voltage levels needed?

5V voltage/out and ground (from converter 1) to Arduino Voltage-in and ground.
12V voltage-out (from converter 2) to LED strip voltage-in.
12V ground (from converter 2) to Arduino ground and LED strip ground.
Arduino data pin to LED strip data pin.

The signalling of those LEDs is 5V and the power supply 12V. Basically you have a 5V-powered chip with constant current sinks driving LED chains that are powered from 12V. The 5V power for the chip is created from the 12V power for the LEDs. So, you need to:

Provide +12V and GND to the chain of LEDs from a 12V power supply
Connect the data line to an Arduino
Connect the GND connection to the Arduino as well.

Nothing more is needed.


Parse JSON with arduino to turn on LED Hi i'm trying to parse JSON resposne from webserver in my arduino in order to turn on and off a LED light. I'm using the wifi client repeating example to make a get request to my server:

http://arduino.cc/en/Tutorial/WiFiWebClientRepeating

Here is what I get printed back from the serial port

connecting...
HTTP/1.1 200 OK
Date: Sun, 06 Apr 2014 01:14:37 GMT
Server: Apache
X-Powered-By: PHP/5.5.10
Cache-Control: no-cache
X-Frame-Options: SAMEORIGIN
Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json

19
{"lightstatus":"on"}
0

How do i parse the JSON portion of this response only so that I can use it to control my LED?

Thanks

I'm aware of a few JSON parsing libraries for Arduino.

aJSON
Arduino JSON Parser
JSON Arduino

I've never used any of these but I did do some simple JSON parsing in a project I'm working on so I'll show you how I did that.

NOTE: I'm reading serial data using the software serial library. You'll need to change this code to work for you. This will only work on very simple JSON strings. It's very limited but if that's all you're parsing then it'll work.

Example of JSON response from server:

{"id":"TEST1","lat":"38.56050207","lng":"-121.42158374","total":"3","available":"2"}

First, only read data between curly braces.

String response = "";
bool begin = false;
while (SIM900.available() || !begin) {

    char in = SIM900.read();

    if (in == '{') {
        begin = true;
    }

    if (begin) response += (in);

    if (in == '}') {
        break;
    }

    delay(1);
}

This code reads data one byte at a time and once it gets an open brace, it starts saving it into response. When it gets a closing brace, it ends it. So here's a clear limitation, you can only have one set of opening/closing braces in your string.

Once I have the string, I use indexOf and substring to extract relevant information:

start = response.indexOf("id\":\"") + 5;
end = start + 5;
nodeId = response.substring(start, end);

This code sets start to the beginning of id":" + 5 characters in the string. It's +5 because that's how long id":" is. So start points to TEST1 in the JSON string. In my system, the ID is always going to be 5 characters long so end is start + 5. I then use substring to extract that.

Again, before anyone starts down voting me for this horrible solution: if you know exactly what you're working with, and understand the limitations of this code, then this is not a bad solution. It's a solution that gets the job done.


Using two digits to display a number using TM1637 and a 4-digit display I decided to build a digital clock using a 4-Digit Display (TM1637) from Grove.

For that, I have been using the DigitalTube library by Grove for the TM1637 controller.

My idea is to use the two first digits of the display (left to right) to display the hour and the two last digits to display the minutes. However, managing displays is difficult and all the libraries I have found for the previously mentioned controlled can only display one number per digit.

Here you have an example:
Using tm1637.display(1,2);, lets you display a "2" in the second digit (L to R), using tm1637.display(0,3); lets you display a 3 on the firt digit and etc.

As I said, I want to display the hour on the first two digits and the minutes in the two last digits.
I've have readed all the examples coming with the DigitalTube library but nothing was useful.

Note: I'm using the DS3231 for managing the time with a RTC.

I don't know if you undestand my question. If not, let me know please.
Arduino UNO R3.

Using tm1637.display(digit#, value); calls, you can display a two-digit number using division to isolate the tens digit and mod to isolate the units digit.  For example, if hour and mins have hour and minute values, respectively, consider code like:

tm1637.display(0, hour/10);
tm1637.display(1, hour%10);
tm1637.display(2, mins/10);
tm1637.display(3, mins%10);

Code like the above is suitable in cases where values don't exceed 99, and where displaying a leading zero is ok.

If you don't want to display the leading zero when hour is less than 10, add an if test and blank the first digit in that case.


Libraries/classes using other libraries/classes This is, hopefully, a simple issue!

I'm trying to access my fully working libraries (fully compiles, and works with the hardware perfectly) from another library (Computer.h) to abstract it away from the Sketch.ino file.

LLRelay, and all my other libraries, work flawlessly when instanced/constructed/built/etc within the main Sketch.ino; however, when called within "Computer.h", there's issues.

I've been at this for most of the day trying different things, from instantiating the libraries in the header files, the *.cpp files, to within functions, to changing the scope and publicity/privacy of them - still no luck.  See the (2 * "HERE -") comments for the errors.

Any help is greatly appreciated!

This is what I have managed to reduce it down to for debugging:

Sketch.ino

// Sketch.ino
#include "Computer.h"

Computer pc1;

void setup(){};

void loop(){
    pc1.update();
};

Computer.h

// "../customLibs/Computer.h"
#ifndef Computer_lib
#define Computer_lib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class Computer {
    public:
        Computer();
        void update();
    private:
        void fans();
};
#endif

Computer.cpp

// "../customLibs/Computer.cpp"
#include "Computer.h"
#include "src/relay/LLRelay.h" /* Potential culprit, I have tried many variations and locations for this to go, all with the same, or similar compilation errors */

/* HERE - "undefined reference to `LLRelay::LLRelay(unsigned char)'" */
LLRelay fan1(13); // fan1(uint8_t relayPin);

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

void Computer::update(){
    fans();
};

void Computer::fans(){

    /* HERE - "undefined reference to `LLRelay::On()'" */
    fan1.On();

};

LLRelay.h

// "../customLibs/src/relay/LLRelay.h"
#ifndef LLRelay_lib
#define LLRelay_lib
#if(ARDUINO > 100)
  #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class LLRelay {
  public:
    LLRelay(uint8_t relayPin);
    void On();
    void Off();
  private:
    uint8_t _relayPin;
};
#endif

LLRelay.cpp

// "../customLibs/src/relay/LLRelay.cpp"
#include "LLRelay.h"

LLRelay::LLRelay(uint8_t relayPin){
  _relayPin = relayPin;
  pinMode(_relayPin, OUTPUT);
  digitalWrite(_relayPin, LOW);
};

void LLRelay::On(){
  digitalWrite(_relayPin, HIGH);
};

void LLRelay::Off(){
  digitalWrite(_relayPin, LOW);
};

The Arduino IDE must detect the library to include it in the build process. It is done by matching a library to a header file by searching the libraries in configured library locations. Only the root folder and the src subfolder of a library are searched.

If your library is in the sketch folder's libraries subfolder and it is called customLibs, then only the customLibs folder and the customLibs/src subfolder are searched and the include file LLRelay.h in customLibs/src/relay folder is not found.

reference: Layout of library folders and files


Strange behaviour with using max I have this really simple code.
Let's say I have a variable X.
Then all I want to do is create a random value R, if R > X then I want X to become R.
But for some reason, my n_of_buttons_pressed climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.

#define N_OF_BUTTONS 60

int n_of_buttons_pressed;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
}

void loop() {

  n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

  Serial.print("n_of_buttons_pressed:");
  Serial.print(n_of_buttons_pressed);
  Serial.println();

  delay(100);

}

The max() “function” is actually a macro defined in Arduino.h as

#define max(a,b) ((a)>(b)?(a):(b))

This expands in your code into something like

buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                  random(0, N_OF_BUTTONS) : n_of_buttons_pressed

The problem with the macro is that it evaluates at least one of its
arguments twice. In this case, if the test is true, the variable
buttons_pressed gets assigned another pseudo-random number.

The way around this is to store the pseudo-random number in a variable,
to avoid random() being evaluated twice:

int pseudo_random = random(0, N_OF_BUTTONS);
buttons_pressed = max(pseudo_random, n_of_buttons_pressed);


Male header pins on Arduino Uno On my board, there are 12 (2 groups of 6, each group consistent of 3 rows of 2 pins) weird male header pins. What are these, and how would you use them?

These are the In System Programming (ISP) pins. They are used to program the microcontroller without using the bootloader.

The bootloader is a program already loaded into the flash of the microcontroller that allows the program to be loaded into the microcontroller through the Tx & Rx serial lines and hence not requiring a programming device.

Using the ISP can be useful when:

The bootloader program doesn't exist in the microcontroller such as on a new chip.
The bootloader is corrupted.
Your program is just that little bit too big and you wish to gain the couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

The standard connection for the ISP is a 100 mil 6-pin header (2x3).

There are two ISP headers on the Arduino Uno because there are actually 2 microcontrollers on the board. There is the main microcontroller (aka the ATmega328P) which is used to execute the program you load into the Arduino board. The second microcontroller (ATmega16U2 or ATmega8U2) is used as a USB interface - converting the USB signals into serial data that is connected to the ATmega328P's UART (ie. Tx & Rx).

The following document details the ISP and gives descriptions of the pins used on the ISP header and how to interface them with the microcontroller etc.:
[PDF] AVR: In-System Programming - Atmel

EDIT: As Majenko correctly points out, the 2x3 ISP header closest to the ATmega328P can also be used to connect sensors and controllers that communicate using the Serial Peripheral Interface (SPI).

More information on the Serial Peripheral Interface and the SPI Library can be found at: https://www.arduino.cc/en/Reference/SPI


PWM water pump flow control - should I use capacitor for MOSFET? I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).

Should I use some capacitor on MOSFET output to "smoothen" voltage? And what kind?

I think you're talking about decoupling caps they are used to smoothen out the spikes and ups and downs in the power. But you're trying to control the flow level using pwm and if you add the Caps that would smoothen the pwm signal!


How do I use an Arduino as a USB output device for a 2x16 display? Can I make a USB 2x16 display using an Arduino?
I want to control a 2x16 character lcd display using USB, not com port/serial.

I need it to appear as a HID device when connected to the computer.

Please advise me.

Thanks

HID's generally are input devices to your computer, if you do want your computer to send data to the device you will need an application to do it.

So your best bet is to have a windows app to communicate with your arduino using a virtual com port ( as it does already) and send data as you require


Why bootloader sizes differs from 0.5 to 8 kilo bytes for different boards? According to official web info bootloader sizes are 0.5, 2 and 8 kilo bytes for UNO, Pro mini and ATMega2560. I believe all three boot loaders do similar job of receiving serial link data and write to Flash memory.

UNO and Pro mini use same/similar ATMega168/328 chips but boot loader size are 0.5 and 2 KB.

ATMega2560 apparent has a more advanced MCU which presumably should use similar or even less memory to do the same task, but the size is significantly large at 8 KB.

Why sizes differ? Small difference may be explained by different development teams, but, should be that much different, from 0.5 to 8KB.

Bootloader of the Mini and Uno are pretty much the same. (I can't find the source-code but the hex files are only slightly different).

The 2k is because they haven't updated mini328.upload.maximum_size in boards.txt. Probably because that would break the board for users that haven't updated the bootloader yet.

The 2560 is using a stk500v2 compatible boot loader instead of Optiboot (uno and mini), because optiboot only supports upto 64kb addresses. Not sure why it is that much bigger though.


Does the compiler generate intermediate assembler? My source files are *.ino, but after compilation there aren't any other files placed in the folder. Does the compiler generate intermediate assembler, and if so, where does it leave them? Or is the machine code available somewhere?

My source files are *.ino, but after compilation there aren't any other files placed in the folder.

Correct. The Arduino IDE performs compilation in a separate temporary directory, whose location you can see if you enable verbose compilation in the IDE options.

  Does the compiler generate intermediate assembler, and if so, where does it leave them?

By default GCC (which the Arduino IDE uses) does not leave intermediate assembly language files on disk. You must pass the --save-temps argument to have it leave them in the current directory, or --save-temps=obj to save them in the output directory.

  Or is the machine code available somewhere?

The machine code is available in the .elf and .hex files generated in the temprary directory.


Why does my analogRead work on Teensy but not Arduino Uno? I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.

Basically:

int timer = 100;
int ColA = 0;
int Output;

// Setting digital pin functions

void setup()
{
  Serial.begin(38400);
  pinMode(0, OUTPUT);

}

// Program

void loop()
{
  digitalWrite(0, HIGH);
  delay(timer);
  Output = analogRead(A0);
  Serial.println(Output);
  delay(timer);
}

It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.

Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!

If you're still using D0 as your output on the Uno then yes you are doomed to failure.

D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.

Pick a different IO pin to be your voltage source.


Why is IF statement executing on itself x = 5;
Serial.println (x);

if (x == 0);
    {
      //stuff in this IF keeps happening why ?
      //Iam too stupid ?
    }

You have a rogue semi-colon.

Splitting your code up on the end of statements you get:

1. x = 5;
2. Serial.println (x);
3. if (x == 0);
4. { // stuff }

With the semi-colon after the if it terminates the if before the opening block {, and that block becomes a completely separate statement detached from the if.


Why are characters with value above 127 "padded" with 1s to be 16 bits long, while ones with values 0-127 aren't? I am using the Arduino IDE to run and monitor, with an Arduino Nano clone.
This code shows what I mean by the question:
char foo = 127;
char bar = 128;
Serial.println(String(foo, BIN));
Serial.println(String(bar, BIN));
foo = 383;
bar = 384;
Serial.println(String(foo, BIN));
Serial.println(String(bar, BIN));

prints
1111111
1111111110000000
1111111
1111111110000000

It still happens if I then cast the elements to char, but not if I cast them to uint8_t:
char foo = 127;
char bar = 128;
Serial.println(String((char)foo, BIN));
Serial.println(String((char)bar, BIN));
Serial.println(String((uint8_t)foo, BIN));
Serial.println(String((uint8_t)bar, BIN));

1111111
1111111110000000
1111111
10000000

It behaves the same if I do some arithmetic as well:
char foo = 127;
char bar = 128;
Serial.println(String(foo / 64, BIN));
Serial.println(String(bar / 64, BIN));

1
1111111111111110

Why is this? If I assign a number bigger than 255, but smaller than 384, it behaves like for numbers below 128, but above that, it does it again, so it's obvious that only the least significant 8 bits of the value are stored as expected, but in cases where (n mod 255) > 127 (so the 8th bit is 1) they are retrieved from memory together with another 8 bits, which are all 1s.
I can live without an answer to the above issue, what I really need to have confirmed is the following:
If I were to store and retrieve a uint16_t as two elements of a char[], it would always be safe (and not undefined behavior) if I did it as follows, right?:
uint16_t foo = 34952;
char bar[2];
bar[0] = foo >> 8;
bar[1] = foo;
uint16_t extracted = (uint16_t((uint8_t)bar[0])) << 8 | (uint8_t)bar[1];

Thank you in advance for any help you can provide.

On the AVR platform the char type happens to be signed, and it can
store numbers in the range [−128, +127]. Thus, when you write
char bar = 128;

You are asking to store in bar a number that does not fit. It then
gets reduced modulo 28 into the value that does fit, namely
−128. For the kind of manipulations you are trying to make, I would
recommend you use uint8_t instead of char.

it would be always safe (and not undefined behavior) if I did it as
follows

It is indeed safe, and the casts you use are needed to make it safe.


Is there some kind of timer function that returns the amount of time passed? I'm doing a project and I want to get the amount of time between two sensor inputs.  i.e. the sensor detects something, and it triggers a timer, and when the sensor picks up something else, it stops the timer and stores the amount of time the passed in a variable.  Is there a library or a specific function that exists?

Just adding a few notes to the perfectly valid answers you already got:

On your typical AVR-based Arduino, micros() has a resolution of
4 µs and millis() is updated every 1024 µs. This last point
implies that millis() increments most times by 1 ms, but
occasionally by 2 ms. Keep this in mind if time resolution is an
issue.

Both millis() and micros() return 32-bit unsigned numbers. This
implies that millis() overflows (it rolls-over to zero) roughly every
49.7 days and micros() every 71.6 min. This limits the
maximum interval length you can measure with each of those functions. It
does not limit the maximum run time of your program, since
subtracting two timestamps does work fine across a rollover
event.


Sending IR via a wire So i have taken apart this old remote i found, and removed the IR-LED and replaced it with wires.

I thought that i would just be able to put the wire that used to go to the positive side of the IR-LED, to a pin on my Arduino UNO (and negative to GND), and just use the same IR decoding library to decode the signal, as if it was from an IR sensor.

But as it turns out, i receive undecipherable nonsense (or so it seems), like 5+ different codes from pressing the same button on the remote.

If i connect the 2 pins from the remote to the IR-LED on my breadboard, and an IR receiver to my Arduino i receive the signal you would expect, which in my case is "24137D" in HEX (1 on the remote) every time.

So my question is: Why does this happen and is it even possible to do what i am trying to do. Why? Why not? And if possible how is this done?

Here is the code i am using:

#include <IRremote.h> //https://github.com/z3t0/Arduino-IRremote

#define IR_Pin 7

IRrecv irrecv(IR_Pin);
decode_results results;

void setup() {
  Serial.begin(9600);
  pinMode(IR_Pin, INPUT);
  irrecv.enableIRIn();

}

void loop() {
    if(irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume();
  }

}

Maybe the answer is obvious and i just don't understand how IR works. If so feel free to link some documentation that can help me.

Thank you.

Your IR receiver is decoding the high frequency pulsed On-Off-Keying waveform for you. The Arduino doesn't do that.

An IR signal consists of high frequency (say 36KHz) on-off light pulsed at a lower (data) frequency (different combinations to make 1 and 0)

The receiver you have takes that high frequency signal, amplifies it, filters it, and gives you just the resulting 1 and 0 signals. From that the Arduino can use simple time measurements to work out the code.

Without the filtering that the receiver provides the Arduino will have to do all that work by itself - and while that may be technically possible, it's seldom done. You may be able to find a library that can do it, but it's unlikely.


Get accelerometer values from BNO055 using adafruit's Unified Sensor Library If I understand correctly using the Adafruit_Sensor one can extract information from the sensor specific information. These sensors are currently mentioned in the README. I am using the BNO055 for two things:

Orientation values (Heading, pitch, roll)
Linear Acceleration values

My code is similar to the Example mentioned Adafruit_BNO055's bunny

Code

I tried the following in my loop()

void loop() {
  // put your main code here, to run repeatedly:
  sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.println(F(""));

  Serial.print(F("Acceleration: "));
  Serial.print((float)event.acceleration.x);
  Serial.print(F(" "));
  Serial.print((float)event.acceleration.y);
  Serial.print(F(" "));
  Serial.print((float)event.acceleration.z);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);
}

Created sensors_event_t event and used the orientation and acceleration parameters to obtain the orientation and acceleration values in x, y, z directions.

output

The orientation and accleration values are the same:

Orientation: 105.50 -20.56 -101.00
Acceleration: 105.50 -20.56 -101.00
Orientation: 97.81 -14.69 -119.56
Acceleration: 97.81 -14.69 -119.56
Orientation: 93.81 -10.94 -125.56
Acceleration: 93.81 -10.94 -125.56
Orientation: 94.44 -12.25 -122.56

I tried adding another event event1 in the loop() but I still get the same results

sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.println(F(""));

  sensors_event_t event1;
  bno.getEvent(&event1);
  Serial.print(F("Acceleration: "));
  Serial.print((float)event1.acceleration.x);
  Serial.print(F(" "));
  Serial.print((float)event1.acceleration.y);
  Serial.print(F(" "));
  Serial.print((float)event1.acceleration.z);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);

Can't the BNO055 along with the Adafruit_Sensor library not provide the acceleration and orientation values as events or is the library used only to obtain orientation values from the BNO055?

Findings

If I use the same sensors_event_t in the code and use event.acceleration and event.orientation within the loop() and they provide me exactly the same values. I in fact get the same values for heading, pitch, roll and acceleration in x, y, z direction.

sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.heading);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.pitch);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.roll);
  Serial.println(F(""));
 Serial.print((float)event.acceleration.x); // same as roll
 Serial.println(F(""));
 Serial.print((float)event.acceleration.y); // same as pitch
 Serial.println(F(""));
 Serial.print((float)event.acceleration.z); // same as heading
 Serial.println(F(""));

Sensor

I have a Blue Dot BNO055 sensor and it has marking on it for X, Y, Z directions as follows:

I crossed checked with the logic of Euler Angles from Wikipedia

If i rotate along the x Axis, I do in fact get roll (0 to 360) and so on.

Inference

The Adafruit_Sensor library provides only orientation values when used with BNO055 and Linear acceleration values need to be called separately using the Adafruit_BNO055.

code for Linear Acceleration and orientation

  sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.heading);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.pitch);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.roll);
  Serial.println(F(""));
//  Serial.print((float)event.acceleration.x); // same as roll
//  Serial.println(F(""));
//  Serial.print((float)event.acceleration.y); // same as pitch
//  Serial.println(F(""));
//  Serial.print((float)event.acceleration.z); // same as heading
//  Serial.println(F(""));

  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  Serial.print(F("Li. Acc.: "));
  Serial.print((float)li_ac.x());
  Serial.print(F(" "));

  Serial.print((float)li_ac.y());
  Serial.print(F(" "));

  Serial.print((float)li_ac.z());
  Serial.print(F(" "));
  Serial.println();

  delay(BNO055_SAMPLERATE_DELAY_MS);


Are there any advantages to Wifi shields as opposed to a Yun? I have an Arduino Uno and I have a remote sensing project for which I need Wifi connectivity. After doing research, I've found that I have 2 options:

Buy a WiFi shield for my existing Uno
Buy an Arduino Yun with built-in WiFi

Looking at costs, I found that a WiFi shield costs more than double what it costs to buy a Yun, so it would seem to me that the best option is the Yun as I'd save some cash and get a more capable board. However, I can't help but think I'm missing something.

What are the advantages of an Uno plus Wifi shield as opposed to a Yun?

There's a number of things to consider that could sway your choice one way or another:

Power consumption

The Uno is a small low-power chip to which you add WiFi. The Yun is an Arduino Leonardo with a WiFi router (like you have on your desk) strapped to the back of it.  The Yun will therefore consume considerably more power than the Uno.

Boot time

The Uno takes about 1 second to boot up - faster (instant) if you remove the bootloader and program it direct with a programmer.  The Yun takes minutes to boot.

Stability

The Uno is a solid state single item. The Yun has an entire operating system with filesystems and things.  It's far more likely that the Yun will corrupt itself through power loss than an Uno will get struck by a stray neutrino.

Cost

Yes, the Yun is cheaper. But is cheap always good?

Remote-ability

The Yun can be completely reprogrammed remotely. A new sketch can be uploaded to the Leonardo portion of it without you even having to be in the same country. The same can't be said for the Uno.

Power

The Linux portion of the Yun is considerably more powerful than any normal Arduino.


How Server request happens? Can somebody explain the below code, like how the server understands,
how the request goes to the server from the below code.

if (client.connect(server, port))
  {

 client.print("GET /abc.txt");
 client.println(" HTTP/1.1");
 client.println("Host: www.yourdomain.com");
 client.println("User-Agent: Arduino");
 client.println("Accept: text/html");
 client.println("Connection: close");
 client.println();
 client.stop();

 }

Also, is the below lines are necessary ? If yes, on what type of situation it would be helpful ?

`client.println("User-Agent: Arduino");
 client.println("Accept: text/html");`

How this communication happens? This question is just for understanding purpose?

Those print() and println() are just sending text from the client to the server using the TCP/IP connection (which was setup by connect()). What's important though is that those lines of text follow the HTTP specification for request headers.

The HTTP specification defines various pieces of header information which the client can send to a server. Some of the information is mandatory, but there are lots of other optional headers too which can be helpful.

When the server receives these headers, it's nothing more than a bunch of text. There's nothing special about it. It has to assume or detect that it corresponds to the HTTP specification, and parse them appropriately to understand the details of the request. For example, the very first line specifies the resource (file) being requested, i.e. "/abc.txt".

The lines you mentioned are examples of optional information. The User-Agent header simply tells the server what kind of system and/or browser is requesting the information. In many cases, servers basically ignore this information. They might log it for statistical purposes, but they don't actually act on it. However, other servers may use it to decide exactly what information to send, e.g. showing a tablet-friendly version of a website if someone is accessing it from an iPad.

The Accept header can be used by the client to indicate what format of information it expects. Assuming the server honours it, this can be useful to ensure you don't accidentally download a format you can't handle. For example, the Arduino could happily process a little bit of plain text or HTML, but probably couldn't do anything useful with a JPG image.

For more information about the HTTP specification: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol


Cascaded Control loop Arduino I am trying to implement cascaded control system, with velocity inner loop and position outer loop.

Separately and without cascaded control, I have implemented position control and velocity control easily, thanks to the "pid library."

I have no idea how to convert position output from position pid to reference velocity.

Any help would be appreciated, since I am blank on this topic.
Thanks and best regards

This is not an Arduino specific topic, but here is just a pragmatic answer:

Use the output of the PID controller directly as your reference velocity, subtract your actual velocity and use it as input for the PID velocity. Units do not care in this case.

You have to make sure that the paramters of your PID position are well adjusted, this will set the problem with the units.

Here is an example to understand (only P gain considered):

If you want to drive from A to B with your car and the distance from A to B is 10 km, then your desired position is 10km and i would choose to drive about 100km/h. So in this example you start with a control deviation of 10km - 0km = 10km. If you choose a P gain of 10 the output of the PID will be 100, which is an ideal refernce Velocity, if velocity is given in km/h.

But if you are measuring your distance not in km but in m, the control deviation will be (10.000m - 0m = 10.000m), with a P gain of 10 you will end up with a refernce velocity of 100.000km/h, which is not an appropriate reference velocity in this case.

Now someone may object that in my example if you want do drive from A to C and C is 1.000km away, you will end up with an reference velocity of 10.000km/h, which is also not appropriate, but that is where the limitations in a PID controller are usefull, just set them for this example to 130km/h and you will end up stil with an appropriate reference velocity, and also your integrator part will not wind up endlessly.

You can look at I and D gain in a similar manner.


ESP32 partition table and writing location In my ESP32 project I have the following platformio.io file:
[env:esp32-poe]
platform = espressif32
board = esp32-poe
framework = arduino
lib_deps =
    openslab-osu/SSLClient@^1.6.7
    knolleary/PubSubClient@^2.8
    bblanchon/ArduinoJson@^6.16.1
monitor_speed = 115200

[env:custom_builtin_table]
board_build.partitions = default.csv

the default.csv table is this one:
# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x5000,
otadata,  data, ota,     0xe000,  0x2000,
app0,     app,  ota_0,   0x10000, 0x140000,
app1,     app,  ota_1,   0x150000,0x140000,
spiffs,   data, spiffs,  0x290000,0x170000,

I noticed that when I upload the code to my ESP32 the output is like this:
[...]
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 17104 bytes to 11193...
Writing at 0x00001000... (100 %)
Wrote 17104 bytes (11193 compressed) at 0x00001000 in 0.3 seconds (effective 521.5 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 128...
Writing at 0x00008000... (100 %)
Wrote 3072 bytes (128 compressed) at 0x00008000 in 0.0 seconds (effective 5621.7 kbit/s)...
Hash of data verified.
Compressed 8192 bytes to 47...
Writing at 0x0000e000... (100 %)
Wrote 8192 bytes (47 compressed) at 0x0000e000 in 0.0 seconds (effective 27422.0 kbit/s)...
Hash of data verified.
Compressed 1003456 bytes to 585011...
Writing at 0x00010000... (2 %)
[...]

Hence, it writes at:

0x1000
0x8000
0xe000 (otadata)
0x10000 (app0)

But I cannot understand what are the first two writings.

0x1000 is the "second stage" bootloader. This is the code that is responsible for loading the code according to the layout specified in the partition table.

In ESP-IDF, the binary image which resides at offset 0x1000 in flash is the second stage bootloader. Second stage bootloader source code is available in components/bootloader directory of ESP-IDF. Note that this arrangement is not the only one possible with the ESP32 chip. It is possible to write a fully featured application which would work when flashed to offset 0x1000, but this is out of scope of this document. Second stage bootloader is used in ESP-IDF to add flexibility to flash layout (using partition tables), and allow for various flows associated with flash encryption, secure boot, and over-the-air updates (OTA) to take place.

0x8000 is the partition table itself.

Second stage bootloader reads the partition table found at offset 0x8000. See partition tables documentation for more information. The bootloader finds factory and OTA partitions, and decides which one to boot based on data found in OTA info partition.

All this is detailed in the ESP-IDF manual.


LSM9DS1 breakout - How to increase speed With regards to the Adafruit LSM9DS1 breakout:
enter link description here

And using the Library:
enter link description here

I am trying to increase the sample rate, or speed of this chip.
I am using a Sparkfun Pro Micro 5V

With the adafruit library, you need to request accelerometer, gyro, magnetometer and temperature at once, and all I need is the accelerometer values. I am hoping by figuring out how to request only the accel values it will speed up the loop. But also, there must be another setting that could speed up the sample rate?

Any help would be appreciated!

my code currently:

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LSM9DS1.h>
#include <Adafruit_Sensor.h>  // not used in this demo but required!
Adafruit_LSM9DS1 lsm = Adafruit_LSM9DS1();
#define LSM9DS1_SCK A5
#define LSM9DS1_MISO 12
#define LSM9DS1_MOSI A4
#define LSM9DS1_XGCS 6
#define LSM9DS1_MCS 5

void setupSensor()
{
  // 1.) Set the accelerometer range
  lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_2G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_4G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_8G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_16G);

  // 2.) Set the magnetometer sensitivity
  lsm.setupMag(lsm.LSM9DS1_MAGGAIN_4GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_8GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_12GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_16GAUSS);

  // 3.) Setup the gyroscope
  lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_245DPS);
  //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_500DPS);
  //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_2000DPS);
}

double accelX = 0;
double accelY = 0;
double accelZ = 0;
double rms = 0;

void setup()
{
  Serial.begin(115200);
  // Try to initialize and warn if we couldn't detect the chip
  if (!lsm.begin())
  {
    Serial.println("Oops ... unable to initialize the LSM9DS1. Check your
wiring!");
    while (1);
  }
  Serial.println("Found LSM9DS1 9DOF");
  setupSensor();
  delay(5000);//program stabilization
}

void loop()
{
  lsm.read();
  sensors_event_t a, m, g, temp;
  lsm.getEvent(&a, &m, &g, &temp);
  accelX = a.acceleration.x;
  accelY = a.acceleration.y;
  accelZ = a.acceleration.z;
  rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
  Serial.println(rms);
}

Check the header of the library,

you will find readAccel readMag readGyro and readTemp in separate public functions and looking at the implementation of read it just calls those 4 in sequence. readAccel will update the accelData member field.

So you can just call lsm.readAccel() in the loop and then grab lsm.accelData directly and ignore the rest.

void loop()
{
  lsm.readAccel();
  accelX = lsm.accelData.x;
  accelY = lsm.accelData.y;
  accelZ = lsm.accelData.z;
  rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
  Serial.println(rms);
}


unexpected behaviour of encoder with increasing rpm I am using a DC motor with encoder, and I am trying to calculate how many pulses are  recorded in every one second interval. (note that the power source is of 12V for the motor)
Circuit and code:

int encpin=3;
volatile long npc=0; //new pulse count
volatile long opc=0;  //original pulse count
volatile long pulsecount;
unsigned long int newtime;
unsigned long int prevtime=0;
unsigned long int time;
void setup()
{
  pinMode(encpin, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
}
void function(){
  npc++;
}
void loop()
{
 newtime=millis();
 time=newtime-prevtime;
 pulsecount=npc-opc;
  if(time==1000){
    Serial.println(pulsecount);
    prevtime+=1000;
    opc=npc;
  }
}

It seems to be rather intuitive that increasing the rpm should increase the number of pulses recorded in one second. However, the results are rather erratic:
 RPM  PULSECOUNT
  26    2365
  32    2367
  38    2400
  44    2375
  52    2400
 116    2412
 142    2384
 195    2416
 280    2406
 350    3008
 416    1580
 520    1975
 624    2370
 730    2334
2737    2188

Increasing RPM sometimes increases the pulsecount, but sometimes decreases it....what could be the reason for this behaviour?

I think the problem is in the tinkercad simulation:
The encoder is attached to the motor and the motor is always rotating at the same speed. Selecting a different RPM on the component changes the gear ratio and the RPM of the shaft, but not of the motor. That means that the number output after 1s should be always the same.
Why it is not exactly the same, only the programmers of the simulation can tell.
It might have to do with simulation speed, because I get totally different numbers there.
To tell exactly what is going on, a documentation of the components in the simulation and of the simulation would be necessary.


Write your own program to control Arduino Uno Is it possible to write a program to control the Arduino Uno, without using
the Arduino IDE?

Most of the time I wrote code for arduino on codeblocks.

The other times on sublime text.

So the answer is yes.


Efficient way to store array with repeating values? So I have about 2000+ X and Y values where I will look up the Y value for a given X value. If I store the values naively they won’t fit in memory, however there are a lot of repeating values and the X values are arranged in numerical order so I don’t really need to store them explicitly.

So my plan is to use the 3 most common Y values and have an array for all the Y values with only 4 possible values (So using only 2 bits with a bitfield), where 0,1 and 2 corresponds to the most common Y values and 3 tells the program to go fetch the value somewhere else, and here I am thinking a hash table/tree.

Before implementing all this stuff I thought I would ask here if anyone has a better way of doing this, such as if it’s possible/recommended to use the flash memory on the arduino for this or if there’s some better way to store the data. The Y data consists of analog read values which hover around a specific value (say 800) and vary +- 20 or so. I think a histogram of the Y data follows a normal distribution, but I currently do not have enough data to tell.

Without a better understanding of what the data is or how you intend to use it it's impossible to give you real recommendations.

However it is simple enough to store your data in flash memory.

Since X is just a sequential value it can, as you have noted, be ignored.

For the rest, a simple array in flash which you then read with pgm_read_<X>() where <X> is the data size that you are using.

All this can be read on the Arduino PROGMEM Reference Page although the documentation is not great.

So here's a little example:

const int values[] PROGMEM = {
   100, 399, 2847, 1, -497, 32, 4370
};

void setup() {
    Serial.begin(115200);
    for (int i = 0; i < 7; i++) {
        Serial.println((int)pgm_read_word(&values[i]));
    }
}

void loop() {
}

The casting of the return from pgm_read_word as an int is needed to interpret the sign bit properly (it returns unsigned by default).


Why do people complain when I call my functions voids? I have posted questions about "my void loop" or "my void setup" and people complain that they aren't really voids. But they are! See this example code:

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

void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

Clearly setup and loop are voids because they have the word void right before them!

Note: this is a reference question.

This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:

function add ($a, $b)
  {
  return $a + $b;
  }

Or Lua:

function add (a, b)
  return a + b
end

Or JavaScript:

function add (a, b)
  {
  return a + b;
  }

Or VBscript:

Function add (a, b)
  add = a + b
End Function

All those languages have the word "function" there to indicate that you are declaring a function.

So what does C++ look like:

int add (int a, int b)
  {
  return a + b;
  }

So this must be an "int" right? Or what if it doesn't return a value?

void loop ()
  {
  }

Now it's a "void"? Kind of a weird name for a function!

Actually int and void in these examples are not weird names for functions. They are the return types of those functions. int add (int a, int b) is a function that returns an int. And void loop () is a function that returns nothing.

The C++ compiler can deduce when it is seeing a function declaration from some clues:

A return type (eg. int, float, long)
A name (the function name)
Some parentheses (for the function arguments)

Think of the word function as being there in spirit:

int [function] add (int a, int b)
    ^^^^^^^^^^   <-- don't actually type this!
    {
    return a + b;
    }


How to convert Arduino example sketch to a complete c++ project? I'm experimenting something new with my Arduino Leonardo. I removed its original bootloader and flashed it with LUFA mass storage example with added functionalities(now its a firmware). I'm trying to now add RFID reader(read/write) example to my firmware. For that I have to convert the sketch to a c++ code. So I copied relevant header file and cpp file from the library folder(libraries->rfid-master->bla.h,bla.cpp). But I'm confused what to do with the .ino file under examples(libraries->rfid-master->examples->ReadAndWrite->blabla.ino). I guess this code should be copied to the main class of my firmware. Any ideas?

Basically *.ino is *.cpp without headers. So you can

rename it to *.cpp,
If you have any functions which are used before they have been defined, provide declarations for each function before its first use
#include <Arduino.h> on the top
#include <Wire.h> if you are using Wire and so on

and you have "normal" CPP file.

If you are making library this way, than you create also *.h file, where you declare all exported functions and objects and #include that file in your *.cpp as first line (than you do not need/have to forward declare any of that exported functions)

You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project

the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there


What do I do with the potentiometer on Adafruit RGB LCD So I just got my Adafruit RGB backlight positive LCD 16x2 + extras - black on RGB In this picture it shows a potentiometer beside the LCD. Anyone know where this is supposed to go?

If it helps, I'm mounting the shields on an Adafruit I2C Controlled + Keypad Shield Kit for 16x2 LCD

The potentiometer is for setting the contrast level of the LCD. The Shield Kit shown also comes with a pot (the one with the orange face). Assembled it should look like this:

Notice the pot in the lower right corner to the right of the microcontroller ic and above the reset button.


Android  HC-05  Arduino communication issue My project involves Android (Samsung Galaxy 2) to Arduino (Uno) communication via HC-05.

HC-05 is connected to Arduino on pins 10,11 using SoftwareSerial lib.

I got this setup running for a while and was satisfied by the outcome - my bi-directional communication worked fine.

Issue:

I made a change to the communication protocol and now messages sent from Android to Arduino get corrupted. It happens under particular circumstances - when Arduino writes (streams) packets of data to Android and, at the same time, monitors the input from Android for a particular message which signals the end of communication. This message, when read from SoftwareSerial buffer, gets corrupted. This corruption is not consistent - it corrupts the packet in (seemingly) random way.

I've already run many tests and am pretty sure that this message is not corrupted on the Android side.

Questions:

Is there anything about HC-05 or SoftwareSerial lib which prevents
simultaneous bi-directional communication?
Can it be that input/output buffers interfere in some way?
How can I achieve reliable communication using the aforementioned HW and comm scheme?

P.S. I got pretty much code and am not sure what parts of it might be relevant to this issue. Will provide relevant parts per your request.

Thx

As mentioned by @alex.forencich, SoftwareSerial is not designed to support simultaneous bi-directional communication.

I found a link to AltSoftSerial library on Arduino site, and this lib seems to work properly in my setup.

To convert from SoftwareSerial to AltSoftSerial you need to change the pins that HC-05 is connected to (on Arduino Uno these are pins 8,9), and to make this minor change in the code:

//#include <SoftwareSerial.h>
//SoftwareSerial swSerial(10, 11);

#include <AltSoftSerial.h>
AltSoftSerial swSerial;


How to read/write variables persistenly on Arduino Due (no EEPROM/shield)? I am relatively new to Arduino and I am currently writing some code to control a relay board. The on/off times are provided by the user at run-time and should be stored persistently (EEPROM or flash) in case of power-down.

On my Uno I worked with the EEPROMex library and that worked well. Now I have a Due which doesnt have any EEPROM and I am struggling how to store variables persistently. Specifically, I dont know how to access whatever I wrote to the flash memory previously. In the example below the content of test[] is obviously overwritten on every restart.

PROGMEM int test[] = {1, 2, 3, 123, 23};

void test()
{
  Serial.println((long)test);
  for (int i = 0; i < 5; i++)
  {
    Serial.println(test[i]++);
  }
}

I noticed that the address does not change during re-starts, so I I tried reading/writing beyond index 4. This out-of-bounds read/write worked, I guess since I am anyway not storing anything else. Interestingly even this memory which is out of the array is overwritten on power-up.

So: How do I store on unser input data (variables) persistenly on an Arduino due without using any shields?

I really hope that somebody knows differently, but I'm fairly sure that the answer is that you can't directly save runtime data back to the Arduino Due board.  I've looked into this myself and have only found answers saying "wire up an external EEPROM" or similar.  Whilst it seems that it should be technically possible to write into unused (or pre-reserved) areas of the program memory, I suspect that the CPU has to be put into a special mode to do this, which is very probably only possible from the bootloader when flashing a new program to it.

I've chosen to go with FRAM chips for data storage. Link to mine.  They are difficult to wire up - the only ones I found were in surface mount packages (although some hobby retailers sell them mounted to little boards with header pins), but they are very cheap, very durable (you can write to them a great number of times before they wear out), operate at high speeds and you can read/write single bytes from/to them.  Other storage chips often require you to write whole "pages" of data at a time which can mean reading in the existing data, modifying it, then writing it back.

Additional comments:
In your original question, you state that the contents of your PROGMEM located array must be restored on restarts.  I don't think this is the case.  That would suggest that the contents are stored elsewhere and code is in place to overwrite them, however it could be the case that they are copied into working RAM, which would mean that the PROGMEM macro is not actually doing anything on the Due - which may well be the case.

Modify your code to change one of the values of the array (within the bounds of the array!) and then print its value out again after changing it.  If the value printed has changed then this means that PROGMEM is not actually doing what it is supposed to do on the Due, which would be a real shame.


Is there a away to transmit sensor signal over RF without Arduino? I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m).

Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?

You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

Add to that a NRF24L01 transceiver like this:

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.

So the whole thing could be done for under $10.

  Something that could work for considerable duration with a small tablet like battery?

See Power saving techniques for microprocessors


Using external reset to trigger radio receipt I am designing a low-power RF application using an ATTiny (Adafruit Trinket).

When the system receives a radio signal, it needs to read some sensors, and transmit with that data. Because I am short on pins, I am trying to think of creative (low-pin count) ways to design this system.

My current idea is:

Put the AVR to sleep.
Connect the radio's Rx Interrupt pin to the AVR Reset pin
When the AVR is reset, check the radio buffer

(if there's nothing in the buffer, assume this is a real power-on reset and go back to sleep)

Otherwise, read sensors, transmit
Go back to sleep

My aim here is that the AVR will use very little power while sleeping (furthermore, it will only need to wake up a few times per day).

Is it reasonable to use the AVR reset pin in this manner? Any gotchas to be aware of?

No gotchas I can think of, except for the fact that the ATtiny's memory
will be re-initialized every time you reset it. But I assume you are
aware of that.

Note that, if you want some data to be preserved across a reset, it is
possible using either the on-chip EEPROM or the .noinit
section of the RAM.


How to catch the Enter key received by Bluetooth? I got some code to receive characters from Bluetooth and code and print it back to the LCD display.

However, want to detect the Enter character to be the input signal, in other words, not to print nothing to the display until Enter is pressed.

An strange character is shown at display for Enter but I can't catch it.

This is my code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x20,16,2);

void setup()
{
  lcd.init();
  lcd.backlight();
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop()
{

  while (Serial1.available())
  {
    char dato= Serial1.read(); //Comprobamos el dato

     lcd.print(dato);

    switch(dato) {
    case '#':
      Serial.println("GATO...");
    break;
    case 'e':  digitalWrite(13,LOW);

    Serial1.println("Led apagado");
    break;
      case 'r':
      digitalWrite(13,HIGH); delay(200);
      digitalWrite(13,LOW); delay(200);

      Serial1.println("Led intermitente");
      break;
  } //fin switch

}//serial disponible

}//fin programa

It depends on what the enter key sends. It may be just CR (carriage return), LF (line feed), or both. You can check the ASCII table for the hex values for those characters.

LF is 0x0A and CR is 0x0D. Those are the characters you're looking for, you can add a if for these cases in order to guard the call to lcd.print(dato):

char dato= Serial1.read(); //Comprobamos el dato
if (dato != 0x0A && dato != 0x0F)
    lcd.print(dato);


How to use assembly in arduino I have been assigned a university project to make sound/audio responsive LED using assembly language. I have already made a C++ code in arduino which uses Fastled library. How do I write a working code for this project in assembly (not restricted  to arduino IDE, but preferable). I've already tried converting my code to assembly using an online converter, but it is useless.

The Arduino IDE is quite idiosyncratic. It won't let you work on a
project that doesn't have a file with the extension “.ino”. On the other
hand, it doesn't care about how much code is in that file, and you can
keep it happy by creating an empty .ino file. I recommend however that
you put at least a comment block in that file, in order to make things
less confusing for other people who could see your project. Then you can
put your assembly code alongside this empty file, in files of their own
ending with the “.S” extension. These files will be preprocessed before
being assembled, so you can #include <avr/io.h> and use the macros
defined therein for the IO ports, bits, etc.

The project would look like this:

my_project/         # containing directory
├── my_project.ino  # comments only, to keep the IDE happy
├── my_project.S    # main assembly file
└── some_extras.S   # possibly more assembly files...

If the whole project is pure assembly, one of your assembly files should
define a symbol called main, which is the entry point of the program:

.global main
main:
    ; code starts here

If you are going to mix assembly and C++, then you can define main()
in the .ino file, and call from there your assembly routines, which
should be declared as extern "C":

extern "C" void my_assembly_routine();

int main()
{
    my_assembly_routine();
}

Mind the calling conventions when mixing asm and C++ though.

If you are going to use the Arduino core library, then you should define
setup() and loop() instead of main(). The Arduino core will then
provide it's own main(), which takes care of its initialization.

If you are going to write mostly C++, with only some assembly sprinkled
here and there, inline assembly could be a better option. C.f. Michel
Keijzers' answer.


Two commands in Void loop? So basically I'm making 2 buttons turn on and off 2 different LEDs using debounce.
I got that settled with one button to turn on and off 1 LED.
But how do I make it so I can use the same lines but obviously different names of pins in Void loop?

So this is the one command line, but how do I make 2 commands with the if statement, may I have an example? Thanks

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

int inPin = 22;         // the number of the input pin
int inPin2 = 26;
int outPin1 = 13;       // the number of the output pin
int outPin2 = 6;

int state = LOW;      // the current state of the output pin
int reading;           // the current reading from the input pin
int reading2;
int previous = HIGH;    // the previous reading from the input pin
int previous2 = HIGH;

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

//===============================================================================================
void doIt(int outPin)
{
  Serial.print("Button Switch State Change:");
  if (state == HIGH) state = LOW;
  else state = HIGH;
  Serial.println(state);
  lcd.clear();
  lcd.print("Zone1|State: ");
  lcd.print(state ? F("On") : F("Off"));
  Serial.print(state ? F("On") : F("Off"));
  digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("System Activated");
  //
  lcd.setCursor(0, 1);
  lcd.print("Ready...");

  pinMode(inPin, INPUT);
  pinMode(outPin1, OUTPUT);
  pinMode(inPin2, INPUT);
  pinMode(outPin2, OUTPUT);

  Serial.begin(9600);
  Serial.println("System Activated");
  Serial.println("Made by Mateo Holguin");
  Serial.println("0 = Light is Off | 1 = Light is On");
  Serial.println("=======================================");
}

//===============================================================================================

void loop()
{
  reading = digitalRead(inPin);
  reading2 = digitalRead(inPin2);

  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    doIt(outPin1);
  }
  else if (reading2 == HIGH && previous2 == LOW && millis() - time > debounce){
    doIt(outPin2);
  }

  previous = reading;
  previous2 = reading2;
  time = millis();
}

I think you are asking

if (value > 5)
{
  StatementOne;
  statementTwo;
}

But I think you might want to write a function, which would look like this

void doThing(int button, int led)
{
  if (digitalRead(button))
     digitalWrite(led);
}

[Edit after reading your comment]
So you need to store the state of the system as a variable in the code.

bool state = false;
if (button1 && !state)
{
  state = true;
  // Your on code.
}
if (button2 && state)
{
  state = false;
  // Your off code
}

You need to add your existing code for turning your LCD and LED on and off where the comments are.
The state variable holds the on or off state of your LCD and LED.
You can of course split it even further so your LCD and LED come on separately of each other.

Does that help?  If so don't forget to mark it as answered.


Reading Digital Pins and Outputing on entire Ports I'm very new to coding so please don't grill me.

I'm working on a scientific project where I am using a NI-DAQ to digitally trigger mosfets to trigger 300us - 3ms pulses on two high powered LED arrays. My intention is to use the Arduino UNO to basically relay one digital output into many. It remains important to use the NI-DAQ as the pulses are dependent on video cues and other outputs, otherwise the pulses would be purely produced by the Arduino.

I have decided to the port Port reg output to accomplish this as it would appear to have the greatest temporal precision but I’m having a very difficult time getting a single pin to trigger a port. I would greatly appreciate some help.

My code currently looks as such:

int inpin = 2; //input specified as pin 2
int x = 0; // variable to store the read value

void setup() {
pinMode(inpin, INPUT); //sets digital pin 13 as input
DDRD=B11111111; //pin 8-13 is in output mode
DDRC=B11111111; //pin A0-5 designated output
}

void loop() {
x = digitalRead(inpin); //read the input pin
if (inpin = HIGH) PORTB=B11111111; // if digital input is high, all Bport high
if (inpin = HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
if (inpin != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
if (inpin != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low

}

At the moment it seems the board it reading the input but is not relaying the outputs correctly with the PORTB continuously off and PORTC continuously on. Any help would be great!

You have some coding errors.  You likely meant to write something like:

void loop() {
  x = digitalRead(inpin); //read the input pin
  if (x == HIGH) PORTB=B11111111; // if digital input is high, all Bport high
  if (x == HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
  if (x != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
  if (x != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low
}

Which could be simplified to:

void loop() {
if (digitalRead(inpin) == HIGH)
{
  PORTB=B11111111; // if digital input is high, all Bport high
  PORTC=B11111111; // if digital input is high, all Cport is high
}
else
{
  PORTB=B00000000; // if digital input is low, all Bport is low
  PORTC=B00000000; // if digital input is low, all Cport is low
}
}


Write data on the computer with Arduino I wonder if in Arduino you can modify the computer eg create a text file inside the computer using Arduino. Is there any way you can do this or something like that?

Because you can use the library #include <stdio.h>, which is a C++ language library to handle file on the computer.

In Arduino maybe you can create files on the computer using pointers or a library? Because using the library "Keyboard.h" you can handle the computer. The Keyboard library can interact with the computer by typing on the computer

I'm in doubt, I need your knowledge.

The keyboard library just sends key presses to the computer like a keyboard.  From the PCs point of view it's no different from you banging on the keyboard in front of it.  The Arduino can't control anything on the computer and it can't run any code on the computer.  Now if you can do what you want completely from the keyboard then arduino could send those same keypresses.  But the Arduino has no access to the PCs operating system or file system.


Is it ok to share the same power rail for the arduino and a shield? I have a two amp 5VDC power rail.  I have configured a motor shield to use external DC (by moving a jumper.)  Is it ok to share the rail between the arduino's 5V and Gnd pins, and the motor shield?

the Vin pin on the Arduino is the source to the internal voltage regulator. It needs about 7 volts in order to work. If you try to feed 5V into the Vin then the Arduino won't get a full 5V.

Motors draw a lot of current, and cause transients on the power line as they switch on and off. (They will cause transients even in a regulated supply, because it takes the regulator time to respond to the rapidly changing load of the motor.) If you're going to feed both your motor shield and the Arduino's 5V from the same power supply, you will need a reservoir capacitor between 5V and ground as close to the Arduino 5V input as possible. The reservoir capacitor will even out drops and spikes in power to the Arduino.

You'd be much better off feeding 7-9V into the Arduino's Vin. That way it's power is regulated separately.


NodeMCU ESP8266 12E loses code after power is reconnected I have uploaded a simple code to control a 8 channel relay by turning individual relays on and off
When I upload the code it works properly, the code works properly and the relays turn on and off in the desired pattern. However when i disconnect the USB cable from my computer and reconnect it, the code isnt working anymore, there is no visible action happening. Is the code erased from memory after power is cut?

int pins[] = {D0, D1, D2, D4, D5, D6, D7, D8};
int i;

void setup()
{
  Serial.begin(115200);
  for(i=0;i<8;i++)
  {
    pinMode(pins[i],OUTPUT);
    digitalWrite(pins[i],HIGH);
  }
}
void loop()
{
  for(i=0;i<8;i++)
  {
    digitalWrite(pins[i],LOW);//Turns this relay on
    Serial.println(pins[i]);
//Turn the previous relay off
    if(i==0)
    {
      digitalWrite(pins[7],HIGH);
    }
    else
    {
      digitalWrite(pins[i-1],HIGH);
    }
    delay(700);
  }
}

My circuit:
NodeMCU | Relay
D0 IN1
D1 IN2
D2 IN3
D4 IN4
D5 IN5
D6 IN6
D7 IN7
D8 IN8
Vin VCC
GND GND

D3 (GPIO0) and D4 (GPIO2) both need to be high on startup for the user program to be executed. The relay board connected to those pins are preventing a sufficient high on those pins.

If you need to use those pins then try using a stronger pull-up resistor on those pins. Try 330-470 ohms.

Either that or you will need to add additional circuitry between the port pins and the relay driver. Also please be aware that this will place a high on the relay driver input and will try to turn on the relays. Your powerup conditions may not be what you expect.


Not sure which Arduino to pick Is the Arduino Uno the best one to purchase for a complete beginner?

I eventually want to get into building Nodebots since I already have experience writing Nodejs web-based applications.

Or should I go directly to purchasing an Arduino Starter Kit? SparkFun Inventors Kit? Adafruit ARDX Experimentation Kit for Arduino? Seeed Studio ARDX starter kit? or Freetronics Experimenter’s Kit for Arduino?

I don't know the difference between these and based off what I have shared about my situation so far, which one should I start with to A. Learn the Basics, B. Evolve into developing Nodebots.

NodeBots does external control of Arduino with Java Script. The controlling computer is a PC or a SOC like Raspberry PI. (Eventually Raspberry can run NodeBots without Arduino.)

For NodeBots, Arduino board runs a firmware called Firmata which executes the commands sent by the Johnny-Five Java Script firmata master library.

I would recommend you to learn C++ and Arduino functions and libraries and code the Arduino directly without Firmata and a controlling computer.


Input a signal from a sensor to an Arduino Due I'm working with Arduino Due and I have a sensor that outputs a square signal with voltages in the range of 0-5V.

In the Due specs there is a warning that says:

"Warning: Unlike other Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Providing higher voltages, like 5V to an I/O pin could damage the board."

Is it possible to connect it to the board?

Thanks.

This is a tough one. If it was digital IO sensor, a simple level shifter would suffice. However, since it's analog, you have limited options.
The cheapest route (and the easiest) would be to use a voltage divider. They only take two resistors, and they divide linearly. That means 1/2 of 5V would be divided into 1/2 of 3.3V. You can then  use the full range of the Due (be careful not to use 0-1023, as it has a 12 bit ADC: it'll give you weird numbers).
More on voltage dividers. Even more on voltage dividers.
To build one:

From Sparkfun (link at bottom)

That's four different ways to build one. R1 would be 1700 ohms and R2 would be 3300 ohms. Vin would be from the sensor and Vout would be to the Due.


Does a moisture sensor need warm-up time? I am trying to use a moisture sensor to identify the moisture value of my plants. (As every one does.)

The sensor was connected to VCC all the time and my battery goes empty after a short time. So I decided to connect power only at the time I read from the sensor (on the arduino with digitalWrite(moisture_vcc, HIGH).

To problem is that the values were too high.

So I'm wondering if these kind of sensors need a "warm-up time"? And If so, how long is it?

Any experience with it?

Photograph of the YL-69 Sensor  :

Most of this content was generated by :  Conner Wolf

Basically, that sensor works by measuring the resistance between the two "pins" of the PCB stake. It does this by applying a voltage across the pins, and measuring the current flow. So, the intention is that more water means less resistance, means less voltage, and a fall in the voltage sent to the ADC of the processor.

However, this is also going to lead to the metal from one of the pins being eaten away by galvanic action (electrolysis).

The other pin is likely to have accumulation of materials rather than being eaten away.

This electrolysis and coating of the pins results in a change in surface area of the pins and causes resistance measured to change (for the same given moisture content).

If you want to squeeze as much life out of the thing as possible, there are a few things you can do.

DO NOT leave the sensor powered. When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again. Don't take readings too often.
Periodically reverse the pins of the electrical connection between the readout board and the "stake" board. Since only one terminal will be eaten away at a time, this should spread the decay out a bit.
Be aware that ANY mechanical disturbance of the "stake" board will probably cause a large shift in readout value. Your "jiggling the wires" causing a shift in values probably came from the mechanical force transmitted to the PCB through the wiring.

An improved version for this sort of thing use a AC bias on the sensor, which minimizes galvanic corrosion. AC bias reverses the voltage applied to the sensor, attempting to eliminate electrolysis on the sensor.

Higher Quality soil moisture sensors use capacitive sensor, and therefore make the sensor immune to the corrosion issue, but are much more complex and expensive.


How do I use a SMD crystal with 4 pins? I am running my arduino project with the atmega328 chip like this:

I have purchased by mistake this crystal:

The reason why I purchased by mistake that crystal was because it has this description:

  16MHz ±10ppm 22pF 60Ω SMD-3225 SMD Crystal Resonators RoHS

I thought that it contained the 22pF ceramic capacitors inside. But latter I learned that I still the 22pf ceramic capacitors. (Please correct me if I am wrong)

Anyways how can I use that crystal? I only know how to connect the 2 pin crystal. Since this crystal has 4 pins now I am confused.

To me it makes sense to connect it like this:

Connect pins 9 and 10 from atmega --TO--> pins 1 and 3 from the crystal.
Connect pins 2 and 4 from crystal --TO--> Ground
Connect the 22pf ceramic capacitors to pins 1 and 3 from crystal and ground like in the first diagram.

this is a nice question. Once for a project I stumbled upon this problem too.

The way you described the connection should work perfectly fine.

  To me it makes sense to connect it like this:
  Connect pins 9 and 10 from atmega --TO--> pins 1 and 3 from the crystal.
  Connect pins 2 and 4 from crystal --TO--> Ground
  Connect the 22pf ceramic capacitors to pins 1 and 3 from crystal and ground like in the first diagram.

Keep it going and greetings from Switzerland.


Teensy lc linker script question I am under the impression that the origin of RAM on a Cortex M is 0x20000000.  However, in the linker file for it, the ORIGIN of RAM is set to 0x1FFFF800.  Is that an error, or is there a reason for the discrepancy?

The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.

In the case of the MKL26Z64VFT4 used on the Teensy LC:

  The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM_L, and 3/4 is allocated to SRAM_U. Regardless of the block size, the SRAM is implemented such that:

  SRAM_L is anchored to 0x1FFF_FFFF and occupies the space before this ending address.
  SRAM_U is anchored to 0x2000_0000 and occupies the space after this beginning address.

  Valid address ranges for SRAM_L and SRAM_U are then defined as:

  SRAM_L = [0x2000_0000–(SRAM_size/4)] to 0x1FFF_FFFF
  SRAM_U = 0x2000_0000 to [0x2000_0000+(SRAM_size*(3/4))-1]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.


Differential voltage measurement with Arduino UNO EDITED:
I bought a very sensitive (and expensive) pressure sensor which requires differential analog measurement. I am an amateur hobbyst and a total beginner in Arduino so I would like to ask some advice on how to connect the device so nothing would be damaged.

In the figure below is the scheme which I've got form the manufacturer along with schematic on how I am going to connect that:

the wire colours are as in the provided device,
the symbols are as they were attached to the wires,
the resistor was provided and connected by the manufacturer.

As far as I understood the sensor manual I should connect the device to analog pins as in the schematic below, and read the A0 and A1 and subtract the signal values. Is that fine? Should I connect the wire going to A1 to Arduino GND as well?

Or should I connect the GND instead of A0 line in the image below?

EDIT: Original connection scheme from the DS and link to the CL1A sensor www and  link to the sensor datasheet (only in Polish)
Yeah, possibly I misunderstood something.

You do not need to do any kind of differential measurement here. The
Arduino analog input measures voltages relative to ground. Then, as long
as the Arduino and the power supply share a common ground, you should be
fine.

On the other hand, you may need a voltage divider. I have seen a few
sensors interfaced the same way (GND, +24V and signal), which output a
voltage between 0 and +10 V. That could fry the Arduin, and maybe
also the sensor. Check the datasheet to see the maximum voltage the
sensor can output, and use a voltage divider to get that safely into the
0 – +5 V range.


Problems improving the inquiry speed of Bluetooth HC-05 I'm buiding a project with the Arduino and Bluetooth HC-05 module that receives the MACs of Bluetooth devices around (does not connect, just inquiry). It works, but I want a better performance in detecting devices, because it doesn't find devices that stay less than 2 seconds in the area. So, I want it to work faster, detecting even if the device stays for 1 second (or maybe less) in the range of the HC-05.

-First, I tried to select the baud-rate (from 9600 to 1382400) of USART, but I tested it, and it did not change anything.

-Then, I tried to config the period and the duration of the inquiry process by "AT+IPSCAN", but, for any value I adjust, also results in anything.

Thought maybe I did not configure parameters, but I tested "AT + IPSCAN?" and "AT + UART?" and the values are those that I set.

This is strange, but I could not find a solution. Does anyone know what it could be?

You can't change how fast Bluetooth devices report their presence.

Bluetooth works the opposite way that you expect. An inquiry doesn't actively request what devices are there. Instead it sits and listens passively for devices to announce that they are there.

If a device enters the target zone and then leaves again before it has broadcast it's "I am here" signal there is nothing you can do.

That is why inquiries take so long. They wait enough time for devices nearby to announce that they are here.

I am not familiar with that specific module, so I don't know if it is always listening in the background and maintaining a list, or just listening during and enquiry, but either way the onus is on the remote device to announce that it is there.


Why does Serial.print print only a value for 0-84 for a 100 integer array? int a[100],i;
void setup() {
  Serial.begin(9600);
}

void loop() {
  for(i=0; i<100; i++) {
    a[i] = i;
    Serial.println(a[i]);
  }
  exit(0);
}

It's because you're using exit(0).  That turns off interrupts and goes into an infinite loop. However, serial printing is first placed into a buffer, and each character is then removed from that buffer in turn and sent out through the serial port.

That's all fine, up until the end when you use exit(0);, and what is left in the serial buffer to send never gets sent because interrupts are disabled.

There is never really any cause to use exit() on a microcontroller - after all, where can it "exit" to? There's no OS to exit to. So it does the next best thing which is as close to doing nothing as reasonably possible.

Instead, if you want to "stop" your program you should use a simple while(1); which will allow interrupts to still trigger.

Alternatively, if you really want to use exit(), you should flush the serial first:

Serial.flush();

That function will block until the transmit buffer has been fully emptied by the interrupt and the last byte has left the UART's TX shift register.


Can I generate 5 sec delay within an interrupt program? void buttonPressed()
{
  if(ledOn)
  {
    ledOn = false;
    digitalWrite(13,LOW);
  }else
  {
    ledOn = true;
    digitalWrite(13,HIGH);
  }

  vout=analogRead(sensor);
  vout=(vout*500)/1023;
  tempc=vout; // Storing value in Degree Celsius
  tempf=(vout*1.8)+32; // Converting to Fahrenheit
  lcd.setCursor(0,0);
  lcd.print("ROOM TEMPERATURE");

  lcd.setCursor(0,1);
  lcd.print("C = ");
  lcd.print(tempc);

  lcd.print("  F = ");
  lcd.print(tempf);
  Serial.print("f ");
  Serial.print(tempf);
}

here is the code of interrupt and i want to monitor the sensor value for about 5second.

You don't need interrupts for any of that. Your main loop just needs to test the switch, eg.

void loop ()
  {
  if (digitalRead (button) == HIGH)  // assuming LOW means pressed
     return;

  // read thermocouple here

  // display results

  delay (5000);

  }

  I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs

You are misusing interrupts in what you are attempting. See my page about interrupts. You simply should not be attempting to print or delay inside an interrupt routine. The most you should do is detect that the switch is pressed:

volatile bool switchIsPressed = false;

// Interrupt Service Routine (ISR)
void buttonPressed()
  {
  switchIsPressed = true;
  }  // end of buttonPressed ISR

Now in your main loop you detect that the switch is pressed and take your reading. If you want to do something else "remember" the time you showed the value, like this:

unsigned long whenTemperatureDisplayed = 0;

void loop ()
  {
  if (switchIsPressed && whenTemperatureDisplayed == 0)
    {
    // take reading ...
    // display reading ...
    whenTemperatureDisplayed = millis ();  // when we displayed the reading
    switchIsPressed = false;               // ready for next time
    }  // end of if switch was pressed

  if (whenTemperatureDisplayed != 0 &&
      millis () - whenTemperatureDisplayed >= 5000) // 5 seconds are up
    {
    // stop displaying the reading ...
    whenTemperatureDisplayed = 0;
    }  // end of if time is up

  // do other stuff here

  }  // end of loop


Works on Uno but not on Yun I found some code that works to transmit the required signal to an RX-2B RC receiver, the code works great from my Uno but when I tried to run it from my Yún nothing happens.

The code has definitely uploaded as I tested with an LED and the pin is getting a HIGH voltage written to it.

Does anyone have any idea what the issue might be? Code below.

Thanks.

/**
* Control Realtek RX2 (RX2 -G) RC Receiver with Arduino
*
* @author Mircea Diaconescu, Octomber 28, 2013
* @source https://github.com/dimircea/
* GPL v3 License
*
 * Many cheap RC toys are based on TX2 / RX2 transmitter / receiver ICs.
 * This Arduino sketch allows to replace the TX2 based Remote Control with Arduino.
 * Just one single pin is used from the Arduino board.
 *
 * Connect Arduino pin 10 to the solder point where the toy antenna is connected or         to the toy antenna cable.
 * One can replace pin 10 with other free digital pin available on the Arduino board.
     *
 * TX-2B/RX-2B datasheet: http://www.datasheetarchive.com/dl/Datasheet-    035/DSA0017137.pdf
 */

/** Functions (aka W1) - as defined by the IC datasheet */
#define COMMAND_ENDCODE         4
#define COMMAND_FORWARD        10
#define COMMAND_FORWARD_TURBO  16
#define COMMAND_TURBO          22
#define COMMAND_FORWARD_LEFT   28
#define COMMAND_FORWARD_RIGHT  34
#define COMMAND_BACKWARD       40
#define COMMAND_BACKWARD_RIGHT 46
#define COMMAND_BACKWARD_LEFT  52
#define COMMAND_LEFT           58
#define COMMAND_RIGHT          64

//output pins
#define ANTENNA_PIN 9

/** Initialize the Arduino data and pin */
void setup() {
 pinMode( ANTENNA_PIN, OUTPUT);
}

/** Loop code */
void loop() {
 // add here your commands to control the RX2 module...
 // for test purposes, here a continuous forward command is sent

 sendCommand( COMMAND_FORWARD);

}

/** Send command to the RX2 IC */
void sendCommand( int command) {
 int w1 = 0, w2 = 0;

 /** start code sequence 4 x W2, ~625Hz, Duty Cycle 75% */
 for ( w2 = 0; w2 < 4; w2++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 1200);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
  }

 /** function code sequence, n x W1, ~1.25KHz, Duty Cycle 50% */
 for ( w1 = 0; w1 < command; w1++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 400);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
 }
}

A Yun is like a Leonardo with a CPU running GNU/Linux at its side. If your sketch works with a Leonardo, it's likely to work with a Yun.

Uno has a different MCU and thus not every sketch will just work, especially those using the hardware serial. You'll have to convert them.


How to split a binary data to form two split binary data? I want to split a received binary data into two binary data.

Take the following received binary data for instance:

uint32_t data = 0xFFFF0001;

In binary format it is: 11111111111111110000000000000001

If we need to split this above binary into two new binary data how could it be done?

As an example from the 0xFFFF0001, how can we obtain the first 17-bit as as data1 = 11111111111111110 and then the remaining 15-bit as data2 = 000000000000001 ?

You can use the bit shift and and operator, like:

uint32_t data = 0xFFFF0001;

The following line will shift all bits 15 places to the right, meaning the least significant 15 bits will be removed, and the other bits shifted to the right.

uint32_t dataLeft = data >> 15;

11111111111111110000000000000001
>>>>>>>>>>>>>>>11111111111111110000000000000001
| Bit shift   || orig. bits    ||Removed bits |

For the other 15 bits,  you can use the and operator, which just makes all 1's 0's for those bits not in the bit mask (0x7FFF).

uint16_t dataRight = data & 0x7FFF;

value:              11111111111111110000000000000001
bit mask (0x7FFF):  00000000000000000111111111111111
                    -------------------------------- & / AND
                    00000000000000000000000000000001


How to make 2 LEDs flash in a 5/4 Polyrhythm? Basically I want one LED to flash 5 times in the same amount of time it takes another LED to flash 4 times. This is what I have, but they are flashing independently and I need them to flash simultaneously.

//Making a 5/4 Polyrhythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {

  for(i=0; i<5; i++)
  {
     digitalWrite (LED13, HIGH);
     delay(500);
     digitalWrite (LED13, LOW);
     delay(800);
  }

  for(i=0; i<4; i++)
  {
     digitalWrite (LED7, HIGH);
     delay(500);
     digitalWrite (LED7, LOW);
     delay(1000);
  }

}

I generally calculate whether the led must be on or off, based on the current time.

//Making a 5/4 Polyrythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {
    // led 13 flashes 5 times per interval of 6 seconds. So the led is on/off for 600ms ( 6000/(2*5) )
    // led  7 flashes 4 times per interval of 6 seconds. So the led is on/off for 750ms ( 6000/(2*4) )
    bool led13on = (millis()/600)%2!=0; // count the number of 600ms intevals have passed, and see if this number if odd or even. odd means led must be on, even means the led must be on
    bool led7on  = (millis()/750)%2!=0;
    digitalWrite (LED13, led13on);
    digitalWrite (LED7, led7on);
    delay(10);
}


3.3V to 5V PWM level shift I need to shift a PWM signal from a ESP32 (3.3V) to receiver that supports 5V. The signal is at maximum of 400Hz. Can this shifter do the job ?

That should work, but it's overkill. Those devices are made for bidirectional signaling. You should be able to use a single transistor that is driven to saturation at 3.3V. A Suitable "logic level" MOSFET with a 3.3 gate voltage should do the trick.
And, as Chris L said in his answer, you may be able to drive an input on a 5V Arduino directly with 3.3V. That's a high enough voltage to be read as a logic level 1.