Is it harmful to write to unused bits in PORT registers? Background:
I'm looking at writing a library to drive an LED matrix panel (one of these:http://www.adafruit.com/product/607) from my newly acquired Arduino Due.  My background is C++ programming, not electronics.

I'm planning to experiment with various optimisations of the code for memory and speed, but one constant is that I would like to be able to send the data to the matrix with single memory writes to port registers without having to use masking operations to leave certain bits unaffected.  As I need to send 6 bits of data with a clock signal, I figured this could be easy with an 8 bit write to one byte of a port register.  The 8th bit/pin could be used as the latch or some other used line.

Looking at the nice pinout diagram that someone has kindly put together (http://forum.arduino.cc/index.php/topic,132130.0.html), I was pretty shocked to discover that my plans weren't going to be as easy as I would have liked.  There are only two circumstances where there are whole bytes of port registers that connect to digital pins (Port A byte 1 and Port D byte 0).  All other bytes have "holes" in them, for example Port C byte 0 has no connection for bit 0, but has bits 1-7;

While two complete bytes is enough (I actually only need to use 13 pins to control the display, plus ground connections), the pins of the available two are spread out in a way that would make it a little awkward for me to make a stripboard shield as I intended due to the pins on the Arduino boards not being evenly spaced (why is that?) and I'm guessing that since most of the digital pins in Port A byte 1 are used for communication pins (including RX0 and TX0) I would lose my ability to print to the debug log.  As a result, I've ruled out using those port registers.

That leaves me with bytes 0 and 1 of Port C.  There are just enough pins available with those bytes and they are grouped nicely on the double connector at the bottom of the board (Digital pins 33-40 and 48-51), however some bits in those bytes are not mapped to Arduino IO pins.

Would it be bad if I were to write to bits of a port register that do not have Arduino IO pins assigned to them?  Would the answer depend on whether I had set those bits to be inputs or outputs using the Output Write Enable Registers?  I'm assuming that these bits are used for IO pins on the SAM3X8E chip but just not made available to the Arduino boards.

If the pins have no connection to the outside world (i.e., they don't have any actual pin associated with them on the SAM3X chip) then writing to the PORT (or indeed any other register associated with them) will have no effect whatsoever.

If they have a pin but that pin is not connected to anything, then there will be little effect.  There may be slightly increase current draw as the pin switches on/off, or you enable/disable the internal pullup resistor, but that's all.

If the pin exists and is connected to something on the board - maybe a button or LED, then you will basically be providing an output to that item.  If it's an LED it will flash.  However, if it's a button, and you provide an output opposite of its active state (i.e., provide a HIGH when it normally connects to ground when you press it) and that button lacks any current limiting resistance, then you could risk burning out that IO pin if the button gets pressed.

If the pin just goes straight to a header, then as long as nothing gets connected to that header then there will be no effect other than as detailed in the "pin present on the chip but not connected".


WeMos D1 ESP-Wroom-02 Mother Board ESP8266 - where is reset pin for deep-sleep This item was bought for battery use with deep sleep purposes. For doing so in ESP8266 reset pin must be connected to Gnd pin in order to wake up. This board lacks a reset on- board pin.
Since spec states it has a such capabilities - I wonder if someone has succeeded with putting it to sleep ( and wake it back on ).
PS - I know that on-chip gpio16 can be soldered to on-chip gnd - I'm hoping there is a more elegant, not soldering invloved, solution.
Guy

This support page has the instructions for enabling deep sleep:
Support for WeMos D1 ESP-Wroom-02 Nodemcu
edit by Guy: in short, solder/connect pins as shown circled in red:


Ultrasonic sensor underwater calibration Does anyone knows how to calibrate AJ-SR04M using the Arduino? I am working on AUV. underwater reading from current code; it is giving continuous 20cm while moving inches. http://shop2.hanjindata1.cafe24.com/product/aj-sr04m-ultrasonic-ranging-module/206/

If I understand your question correctly, your problem is probably that the working range of the AJ-SR04M sensor is 20cm - 500cm.

The sensor uses the same transducer to create the sound pulse and to listen for the echo.  It needs time to switch from one mode to the other, which explains why your sensor can't measure distances of less than 20cm.

The speed-of-sound in water is about 5x the speed of sound in air.  More specifically, at 20 degrees Celsius the speed-of-sound in air is approximately 343 meters per second, while the speed-of-sound in water is approximately 1482 meters per second.

This will cause the sensor to 'under-report' the distance in water.  The minimum distance will also be approximately 5x the minimum distance in air.

As an aside, you will also need to make allowance for the differences in the characteristic impedance and absorption between sound and water.

It's worth reading the paper Underwater Sound by P. Vigoureux (Proceedings of the Royal Society of London. Series B, Biological Sciences, Vol. 152, No. 946) for a discussion of all the factors involved.


Typedef Function Pointer Invoking Issue I'm having an issue trying to use a normal non-member function of my main sketch file as a callback.  I can't get the function pointer to invoke from a function other than it was saved.  More info below;

MotorEncoder.h

typedef void (*cb)(int16_t,int16_t);
class MotorEncoder
  ...
  private:
    cb _motor_callback;

Program.ino

cb encoder_cb = NULL;
...
encoder_cb = function_that_accepts_2_int16
DC_Encoder_1.move(motor_pos, speed, motor_id, encoder_cb);

EDIT: I want to edit the description as to not confuse anyone.  The code with the callbacks above is all correct.  The issue was I was working with open-source software and another developer was setting the selected serial-port connection back to the bluetooth channel in-correctly.  The callback was executed, I was connected to the ATMega2560 via serial connection to a raspberry pi and was looking for the callback to show there, not monitoring bluetooth so I didn't see any data come across.  Document your code.

This answer contains a few debugging guidelines, as I don't know what the problem is and don't see how one could tell without a good deal more of information.

I suggest creating a Minimal, Complete, and Verifiable example (MCaVe) of your code, not just snippets, so that other people can compile and run the code, thus being able to observe what happens in more detail and perhaps with added debugging output.

I'm presuming your callback is triggered as a consequence of an interrupt occurring.  I suggest you write the MCaVe to depend on a pin-change interrupt, rather than a motor-controller interrupt, to allow testing on a system consisting of no more than an Arduino with a button, a serial interface, and perhaps a few LED indicators.  Pressing the button would change pin voltage and cause an interrupt; your ISR would turn on an LED to signal it handled the interrupt, then trigger the callback.  The callback routine would turn on another LED as its signal.  The main loop would read the pin register bits for the two LEDs, record and report the times they came on, and turn them off after a second or two.  If you get a simple setup like this to work, the technique probably would carry over to your motor-controller case; or if not, probably being a smaller program and setup should be easier to debug and figure out why not.


ATtiny88 ADC reference voltage setting I'm writing a simple application that reads voltage from analog input 0. Here is the code:

#define OUT 5
#define ADC 0

void setup() {
  ADMUX &= (0<<REFS0); //Setting reference voltage to internal 1.1V
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(0);
  float voltage = sensorValue * (1.1 / 1023.0);
  if (voltage>0.5) {
    digitalWrite(OUT,HIGH);
  } else {
    digitalWrite(OUT,LOW);
  }
}

When I apply 1 V on ADC0, the OUT pin is low. Seems like the reference voltage is not set properly. When I set VREF to VCC (5V), everything works fine.

I cannot find the mistake. Would appreciate any help:)

Edit:

Link to datasheet: http://www.atmel.com/images/doc8008.pdf

In your setup section, you want to set or clear all relevant bits in admux.


Receive whole string in serial sending data? I connect my NodeMCU to Arduino Uno. The goal is to receive the whole string for example "12", every 1 sec.

This is my code on Arduino Uno side ( the sender)

int mock = 0;

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

void loop() {
    //Write mock to NodeMCU
    s.print((int)mock,DEC);
    s.println();

    mock++;
    delay(1000);
}

On NodeMCU side ( the receiver)

 char data; //Initialized variable to store recieved data
 String line;
 void setup() {
   Serial.begin(115200);
   s.begin(115200);
   while (!Serial) {
    ;
  }
}

void loop() {

    if( s.available() >= 2) {
        for (int i = 0; i< 2; i++ ) {
            data = s.read();
            line += data;
        }
        delay(1000);
    }

    Serial.print(line);

}

But the result on the serial panel is not what I expected

How can I make it so that I can receive something like

12
(wait one sec)
13
(wait one sec)
....

Node MCU just prints the whole thing, I can't delay it.

If you send "12" you send 4 characters/bytes: '1', '2' and a new line which is two characters:  ('\r', '\n').

On the receiver side you check for two characters (not the new line), so you should take it into account.

Actually, since you will eventually reach "100" you will receive 5 characters ('1', '0', '0', '\r', \'n').

So it is better to change the receiver side to store the bytes in line UNTIL a new line is received (than you can support values of any length).

Also remove the delay on the receiver side, or at least decrease it a lot, because it doesn't matter to check (too) often. if there is no byte available, it will check again. Now it can happen at time 1001 ms a byte would be received, but at time 1000 ms it is checked and it will not be checked again until time 2000 ms.


Connecting multiple TFT panels to Arduino Uno via SPI? Is it possible to connect more than one TFT screen (like this one or similar: https://www.adafruit.com/products/1651) to an Arduino Uno?

I'm wanting to connect and control two color screens at once; note the touch functionality of the one linked above isn't really necessary, I just like the size and overall build. They have a version that works like a shield and sits on top of the Arduino, which would work I suppose if I bought another unit for the other screen. The breakout board version is more flexible but I don't know of a way to control two screens that require that many pins.

Any suggestions?
Thanks

Yes, you can. All the SPI pins (MISO, MOSI and SCK) are all shared between the panels. You can even share the D/C and RST signals. The only signal that needs to be separate is the CS pin since this is the pin that identifies which panel is actively receiving commands and data at any one time. Also you don't need to connect up the MISO pin at all, since that is only connected to the SD card slot, not the TFT screen.

So each screen that you add just requires one more pin to be used. One screen uses 5 pins. Two screens use 6 pins. Three screens use 7 pins, etc.

And yes, for this the breakout version would be easier to work with than the shield version.


Arduino Due and BNO055 address in i2c mode I have a project where I need to have several IMUs, the BNO055 shuttle board (I explained my project here), I manage to get the Euler angles from one BNO055 sensor, which have the address 0x29, because I linked the I2C_MODE_ADR_SEL to a HIGH level.

I would like to have another sensor with the address 0x28. As the datasheet says, I must link the I2C_MODE_ADR_SEL to a LOW level (to the GND) the i2c Scanner from the Arduino Playground does not recognize any i2c device.

I don't know how to change my sensor address, can anyone help me with this issue ?

I've built MotioSuit, a mocap suit based on the BNO055 which currently has 9 sensors but could go up to 18.

https://hackaday.io/project/9266-motiosuit

The sensor board and library are open-source and documented in the link, I hope it helps!


What's wrong with this code..? I want to make an 8*8 led matrix. I found this code on the web:

    int latchPin = 12;  //Pin connected to ST_CP of 1st 74595
    int clockPin = 13;  //Pin connected to SH_CP of 1st 74595
    int dataPin = 11;   //Pin connected to DS of 1st 74595

    int latchPin2 = 6;  //Pin connected to ST_CP of 2nd 74595
    int clockPin2 = 7;  //Pin connected to SH_CP of 2nd 74595
    int dataPin2 = 5;   //Pin connected to DS of 2nd 74595

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);

      pinMode(latchPin2, OUTPUT);
      pinMode(clockPin2, OUTPUT);
      pinMode(dataPin2, OUTPUT);
    }

    void loop() {
      /************** Send HIGH to first Anode pin (16th pin) and LOW to all
      other anode pins (15, 11, 3, 10, 5, 6, 13) of LED matrix *************/

      // take the latchPin low so the LEDs don't change while you're sending in bits:
      digitalWrite(latchPin, LOW);
      //Send 0 0 0 0 0 0 0 1 (1) to Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 of 1st 74595
      shiftOut(dataPin, clockPin, MSBFIRST, 1);
      // shift out the bits:
      digitalWrite(latchPin, HIGH);

      /**************** Send LOW to the first cathode pin (4th pin) and HIGH to all
        other cathode pins (7, 2, 8, 12, 1, 14 and 9) of LED matrix *****************/

      // take the latchPin low so the LEDs don't change while you're sending in bits:
      digitalWrite(latchPin2, LOW);
      // Send 1 1 1 1 1 1 1 0 (254) to Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 of 2nd 74595
      shiftOut(dataPin2, clockPin2, MSBFIRST, 254);
      // shift out the bits:
      digitalWrite(latchPin2, HIGH);
    }

I expected this code to turn on the first LED, but when I uploaded this code nothing lights up. I checked my rows and colum connections.
Also, I want to ask if a 74hc595 can output sink current?

I can't add comment to your question so I post as an answer even though this is not much an answer. This is just a hint to solve your problem.
8x8 led matrix and 595s are pretty low-level stuff, so I assume you have some knowledge about electronics and programming in general.
I think your wiring is OK but I also think you misunderstand how 595 works.
Here is the flow taken from a library (ESP32) for 64x64 RBG LED panel using bunch of 595s:
uint8_t data[8]; // data for one row

digitalWrite(OE_PIN, HIGH); // disable output, 595 outputs go into high impedance state

for (int i=0; i<8; i++)
  shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, data[i]);  // dump data out

digitalWrite(LATCH_PIN, LOW);  // pulse 1 clock
delayMicroseconds(1); // note 2*
digitalWrite(LATCH_PIN, HIGH); // latch is active high

digitalWrite(OE_PIN, LOW); // Enable output

I think now you know how to fix your code.
Note 1: I find those names SER, SRCLK, RCLK (on TI's datasheet) are confusing. I prefer the names SERIAL DATA INPUT, SHIFT CLOCK, LATCH CLOCK (on ONSEMI MC74HC595 datasheet) or better DATA, CLK, LATCH, OE, RESET.
Note 2: Check 74HC595 datasheet to see clock pulse width limit and speed limit. And if you are using UNO or MEGA (@16MHz), you are good without stretching the clock (data clock and latch clock). If you use higher speed MCU, e.g: ESP32@240MHz or STM32@72MHz, you have to consider clock stretching there and also inside shiftOut() function.
To improve your circuit, you should wire both OE of 595s to a Digital pin. You can also connect both latch pin into one digital pin. Every time you latch, botch 595 latch, and every time you enable output, both enable output.
So with your configuration, just shiftOut data normally for the 595 on the left and invert data for the 595 on the right, like this
#define DATA_COL_PIN 11
#define DATA_ROW_PIN 5
#define CLOCK_COL_PIN 13
#define CLOCK_ROW_PIN 7

#define OE_PIN 4 //use digital pin 4 to enable output on both 595s
#define LATCH_PIN 6 // or 12, but you must connect both latch inputs of both 595s together

uint8_t col = 0b00000001; // for the left 595
uint8_t row = 0b00000001; // for the right 595

digitalWrite(OE_PIN, HIGH);
shiftOut(DATA_COL_PIN, CLOCK_COL_PIN, MSBFIRST, col);
shiftOut(DATA_ROW_PIN, CLOCK_ROW_PIN, MSBFIRST, ~row); // ~row = 0b11111110 = invert_bits(row)
digitalWrite(LATCH_PIN, LOW);
digitalWrite(LATCH_PIN, HIGH);
digitalWrite(OE_PIN, LOW);

The code above is just for you to understand how it works. Normally, they would work on a buffer such as
uint8_t row[8]; // each byte is one row

And they do row scanning, turn one row ON at a time and just flip each column ON and OFF following the byte data of that row.
I stop here as this is going off-topic. You just ask what is wrong with your code right?
BTW, 595 can sink/source 35mA on each pin (70mA in total). So if you want to light up one row at a time with your setup, you should choose each current limiter carefully so that not to exceed 70mA in total.

70mA / 8xLED = 8.75mA for each LED (assume red LED)
(5v - 1v7) / 8.75mA = 377R

It's likely the resistors should be at least 377 ohm or 470 ohm for safety.


Directly read analog voltage using PWM duty cycle timer registers I'm outputting an analog voltage by setting an 8-bit duty cycle using analogWrite. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the OCR4D register, which matches the value set, e.g.:

pinMode(6, OUTPUT);
analogWrite(6, 123);
Serial.print(OCR4D);   // 123

However, when setting the duty cycle to 0 or 255, OCR4D is not actually set at all; instead analogWrite calls digitalWrite behind the scenes and the pin is digitally set to LOW or HIGH. This is seen in the source for analogWrite:

if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}
else
{
// set PWM duty cycle as normal...

The problem with this is that OCR4D is simply left at its previous value, so it's not always possible to tell the actual output by reading OCR4D alone. In other words there is no way to tell the difference between:
- PWM is active and OCR4D reflects the duty cycle
- PWM is disabled and OCR4D reflects a previous duty cycle (which is not useful)

Which register(s) can I read to crosscheck the PWM is active?

I'm also aware of the pulseIn function, but would rather read the PWM register directly.

In the end I managed to do this by reading the timer/counter control register relevant to pin 6:

// read the voltage on an analog output pin
int analogReadOutput(int pin) {
    switch(digitalPinToTimer(pin)) {
        case TIMER4D:
            if (TCCR4C & (1 << COM4D1)) {   // PWM active
                return OCR4D;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        case TIMER4A:
            if (TCCR4A & (1 << COM4A1)) {   // PWM active
                return OCR4A;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        default:
            return -1;
    }
}

Note that this assumes two things that possibly aren't always true (outside of my simple program):

COM4D1 bit is a reliable way of telling if PWM is enabled,
duty cycle value is 8 bit with a max of 255.


Hardware logic gates for a simple demo with LEDs I need some logic gates for a simple demo like this one. I will use a regular breadboard and an Arduino UNO as a 5 V and GND supply.

I found these ICs from Texas Instruments SN74LSxxN (NOT, AND, OR, NAND, NOR, XOR). For my demo I only need two inputs (well obviously only one on NOT) and one output on each chip. I want to connect the output to a LED via resistor to demonstrate that for example 1 XOR 1 equals 0 (LED off), or NOT 0 equals 1 (LED on):

My LSs seem to work as expected without an LED connected:

int value;

void setup() {
 pinMode(10, OUTPUT);
 pinMode(11, OUTPUT);
 Serial.begin(1200);
}

void loop() {
 digitalWrite(10, LOW);
 digitalWrite(11, LOW);
 value = digitalRead(5);
 Serial.println(value);
}

…but it would be great to make an LED demo too.

These ICs are probably a better choice in my case?

SN74ACT04N (NOT)
SN74ACT08N (AND)
SN74ACT32N (OR)
SN74ACT00N (NAND)
CD74ACT02 (NOR)
SN74ACT86N (XOR)

For everyone who isn't happy with Arduino as power supply here an alternative circuit with the same question - which IC family should I use?

Update: Well, probably I should better use something like LogicBlocks for my demo.
There is no NOR, XOR or NAND in this set, but it should be much easier to handle.

The SN74HC04 has a documented output driver capability of ±4 mA when running at 5V:

Assuming you are using red LEDs with a forward voltage of 1.6V (as I measured one of mine lying around on the bench to be), then to not exceed this you need to get a resistor of:

(5 - 1.6) / 0.004 = 850 Ω

A reasonable (and safer) value would be a standard 1k resistor, which you are likely to have lying around (and if not, get a few hundred of them). That would give you 3.4 mA current through the output pin, which is in range.

  I found something very similar to my demo on YouTube ...

Yes, well, people on YouTube aren't always doing things exactly like they should. :)

See Mike Cook's tutorial The care and feeding of LEDs. As he points out, a lot of people use the wrong, or no, resistors because "it seems to work".

It may well seem to work for a while, but if you want a design that will last for a long time, you work within the manufacturer's specifications.

The problem with people disseminating wrong information is that someone will then copy it, and repeat it, and before long you find people saying "everyone does it this way".


Code for two bulb fading alternatively I have written this code

const int A = 3;
const int B = 5;
void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);

}

void loop() {
  for(int i=1;i<=255;i++)
  {
    int j =255-i;
    analogWrite(A,i);
    analogWrite(B,j);
    delay(100);
  }
  for(int i=255;i>0;i--)
  {
    int j =255-i;
    analogWrite(B,j);
    analogWrite(A,i);
    delay(100);
  }
}

Is  this code correct? If yes then can it be modified in any way to make it better?

To keep the two loops more symmetrical, let the first loop go from 0 until 254: [0 .. 255) and the second loop from 255 to 1: [255 .. 0), so both iterations have 255 values each.

Also, it is quite common in programming to include the start element, and not include the end element (as in the values above: [start_element .. end_element).

Also, for the simple formula (255 - i), I would leave out the formula. And to make things more clear define constants for the min/max values (0,255) and the delay.

Than you get:

const int A = 3;
const int B = 5;

const int MIN_INTENSITY = 0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
}

void loop()
{
  for(int i = MIN_INTENSITY; i < MAX_INTENSITY ; i++)
  {
    analogWrite(A, i);
    analogWrite(B, MAX_INTENSITY - i);
    delay(DELAY_TIME);
  }

  for(int i = MAX_INTENSITY ; i > MIN_INTENSITY; i--)
  {
    analogWrite(B, MAX_INTENSITY - i);
    analogWrite(A, i);
    delay(DELAY_TIME);
  }
}

By making a function and use arguments for the variable values, and create some better names for constants and variables you get this:

const int LED_1_PIN     =   3;
const int LED_2_PIN     =   5;

const int MIN_INTENSITY =   0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup()
{
  pinMode(LED_1_PIN, OUTPUT);
  pinMode(LED_2_PIN, OUTPUT);
}

void loop()
{
  fade(MIN_INTENSITY, MAX_INTENSITY,  1);
  fade(MAX_INTENSITY, MIN_INTENSITY, -1);
}

void fade(int startIntensity, int endIntensity, int stepValue)
{
  for(int intensity = startIntensity; intensity < endIntensity; intensity += stepValue)
  {
    analogWrite(LED_1_PIN, intensity);
    analogWrite(LED_2_PIN, MAX_INTENSITY - intensity);
    delay(DELAY_TIME);
  }
}


External ADC reading zero while input is zero Using ADS1115 (or any other external ADC), how its possible to read zero instead of random floating values while no any signal at the ADC's input pin?
The ADS1115 is driven by an op-amp buffer as follows.

The op-amp's + input is sometimes connected to a pH sensor, sometimes left unconnected.

The behaviour you are seeing is what happens when you have high-impedance inputs.  Basically, if you don't drive them, you get random values.

Unfortunately in your case, where the sensor you are using has no output current to speak of, I don't think there's anything you can do about this electronically.

You'll have to solve the problem in some other way if you really need to be able to disconnect the sensor.  A mechanical solution would be a connector which shorts when disconnected.  Switched headphone connectors do this, for example - when you pull out the jack, they make a connection so that the speakers can be switched on.


Optimizing Arduino File Selection from SD card the following code will display the files on an SD card in an Arduino and allow the user to open a file of their choosing. Here's the code with a walkthrough of what it does.

In the Init state, I call the libraries needed to run the code

// Example use of lfnOpenNext and open by index.
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile dirFile;
SdFile file;

// Number of files found.
uint16_t numberOfFiles = 0;

This is the area of the real problem, calling  SdFile parIndex[50]; Takes a large amount of dynamic memory. For number of files on an SD card, this is a pretty small number, so I need to get at something better

// Position of file's directory entry.
uint16_t dirIndex[50];
SdFile parIndex[50];
//------------------------------------------------------------------------------

In the Setup phase, we make sure the SD card is plugged in and, if it is, we call the function to give the files on the SD card.

void setup()
{
  Serial.begin(38400);
  while (!Serial) {}

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  printDirectory(dirFile, 0);
  }
}

The printDirectory function (This is the part most open to edits, if there's any way to improve performance here, please let me know as well).

void printDirectory (SdFile CFile, int numTabs)
{
  SdFile file;
  while (file.openNext(&CFile, O_READ))
  {
  if (file.isHidden()||false)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        //create tabs for spacing
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        SdFile SubDirFile;
        printDirectory(SubDirFile, numTabs+1);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        parIndex[numberOfFiles] = CFile;
        // Print the file number and name.
        Serial.print(numberOfFiles);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
        numberOfFiles++;
      }
    }
  file.close();
  }
}

This is the user interface portion, it was largely slapped together as a proof of concept for the above code. As it's written, the code only accepts index values 0-9, but my actual program could call any index value.

void loop() {
  int c;

  // Read any existing Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);
  Serial.print(F("\r\nEnter File Number: "));

  while (!Serial.available()) {
    SysCall::yield();
  }
  c = Serial.read();
  uint8_t i = c - '0';
  if (!isdigit(c) || i >= numberOfFiles) {
    Serial.println(F("Invald number"));
    return;
  }

After making sure that the input value exists, it calls up the arrays that contain the parent's directory SdFile object and the index of the desired file.

  Serial.println(i);
  if (!file.open(&parIndex[i], dirIndex[i], O_READ)) {
    sd.errorHalt(F("open"));
  }
  Serial.println();

  char last = 0;

  // Copy up to 500 characters to Serial.
  for (int k = 0; k < 500 && (c = file.read()) > 0; k++)  {
    Serial.write(last = (char)c);
  }
  // Add new line if missing from last line.
  if (last != '\n') {
    Serial.println();
  }
  file.close();
  Serial.flush();
  delay(100);
}

The main issue I have is that SdFile parIndex[50]; uses 22% of my dynamic memory vs the rest of the program using 12%. How can I rewrite my code to not require keeping the SDFile objects in dynamic memory?

For anyone unfamiliar, documentation for the SdFat library can be downloaded from that link.

Edit:
In terms of use: The SD files are .csv files that store speed and time parameters for running a motor test. Each test lasts for a few minutes to hours.

You have several possibilities:

Do not store the names of all files, but use the index and iterate through all files again. Disadvantage: this takes a lot of time (every time you need the file name)
Add SRAM to the Arduino (e.g. 23LC1024, 23K256), depending on your memory needs. Disadvantage: you have to 'manage' this memory yourself.
If you know something about the file names, you might generate the name. Probably it's not the case, but just to add another option. E.g. if you know that file nr 10 will always be called 'File10.txt', you can 'generate' the name.
I don't know exactly how you want to use the file names, but you might store only the latest x files used, to prevent having to iterate again reading the SD card. Of course, this only helps if there is a high chance the last x files are used more than the non recent files.

Update:
If you need to read the files while leaving the Arduino unblocked, you have to incorporate it in your loop, but don't read all the files in a loop. Something in pseudo code like:

bool readingSd = false; // True between reading first and last file
uint16_t lastTimeRead = 0; // Last time read

void loop()
{
   // Check if file read needed (initial or one hour past, I don't take
   // overflow into account
   if (lastTimeRead == 0 || (lastTimeRead + 1000 * 60 < millis())
   {
      checkReadFile();
   }

   // Perform your normal code... this will run between processing/reading
   // one file/dir.
   ...
}

void ProcessSingleFile()
{
   readingSd = true; // Within reading first/last file
   "read/process ONE file or dir (without containing files)";
   if ("last file read")
   {
       readingSd = false;
       lastTimeRead = millis(); // Move to top to prevent reading time
         // between first/last to take into account
   }
}


About arduino serial communication I've used the arduino uno with the python serial library months ago and some packets got lost in the way. I've been searching about serial communication for arduino and I've been thinking that I could use some parity systems and other things to guarantee that my packets will arrive. First of all, if I use the parity system of the arduino's serial library, how good it will be? I need to send packets like "this button was touched", but ALL packets must arrive, so if some packet fails, I need to send it again.

How to make it possible? I'm thinking about using the parity system of the arduino's library, but I don't think if it's gonna work well.

Can somebody point me some good text about it?

There is no way to guarantee that all packets will arrive. The best you can do is to have the receiving system acknowledge receipt of all packets, with enough data within to verify the correctness of the packets.

UART parity is not a good method to verify correctness since it can only detect single-bit errors within a byte; two bit errors will verify correctly, and of course the entire byte may get dropped before it can even get to the receiver.

RFC 916, "RELIABLE ASYNCHRONOUS TRANSFER PROTOCOL (RATP)", describes a TCP/IP-like method of sending data reliably over an asynchronous medium. It's more wordy than just sending a byte containing status changes, but if you need reliability then you need more than that.


Print with round towards zero instead of round to nearest When printing with one decimal place, Arduino's Serial.println() rounds numbers like 123.89 to “123.9”. Is there any way to change the rounding mode? For some reasons I want the value to be rounded towards zero (i.e., truncated) to one decimal place, like 123.89 → “123.8”.

here is the code

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

}

void loop()
{
float A = analogRead(A0);
A = (A/1023)*5.0;
Serial.print("A = ");
Serial.println(A,3);
float B = A*10;
Serial.print("A * 10 = ");
Serial.println(B,1);
delay(1000);
}

the output is

A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.9
A = 2.517
A * 10 = 25.2
A = 2.527
A * 10 = 25.3
A = 2.507
A * 10 = 25.1

instead I want the output to be like this

A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.8
A = 2.517
A * 10 = 25.1
A = 2.527
A * 10 = 25.2
A = 2.507
A * 10 = 25.0

is it possible ?

A cheap trick to round a number to one decimal place (in "chop-off mode") is to multiply it by 10, convert it to an integer, and divide by 10.0f again:

float myVal = 123.89f;
myVal = (long)(myVal * 10) / 10.0f;
// = ((long)1238.9) / 10.0f
// = 1238 / 10.0f
// = 123.8

You can then print this modified number to the serial monitor.

This method can also be generalized to other precisions. For 2 decimal places, we just have to multiply by 10^2 (100) and divide by 10^2. A macro would be:

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

Note: You don't have to actually dynamically compute pow(10, numDecimalPlaces), you can also create macros for each decimal precision from 1 to x and simply precompute that value (100, 1000, 10000, ..).

The same can also be achieved by using the standard library function trunc from math.h:

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

See http://www.cplusplus.com/reference/cmath/trunc/.

Here's a small sketch in which it is demonstrated:

#include <Arduino.h>

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

void printValueFormatted(float value, int numDecimalPlaces) {
    //format correctly
    char buf[20];
    char* res = dtostrf(value, sizeof(buf)-1, numDecimalPlaces, buf);

    //skip over empty chars
    while(*res == ' ')
        res++;

    //print buffer
    Serial.println(res);
}

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

void loop(void)
{
    float myVal = 123.8978f;
    printValueFormatted(myVal, 4);
    printValueFormatted(TRUNCATE(myVal, 1), 1);
    printValueFormatted(TRUNCATE(myVal, 2), 2);
    printValueFormatted(TRUNCATE(myVal, 3), 3);
    printValueFormatted(TRUNCATE(myVal, 1), 4);
    printValueFormatted(TRUNCATE(myVal, 2), 4);
    printValueFormatted(TRUNCATE(myVal, 3), 4);
    delay(1000);
}

Prints

123.8978
123.8
123.89
123.897
123.8000
123.8900
123.8970


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

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

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

simulate this circuit – Schematic created using CircuitLab

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

simulate this circuit

Here 1K is required

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

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


7-Segment, 3-digit display not displaying correctly I have written the code that should work, but for some reason the numbers do not display correctly. When I choose to display 3 times the same number it works correctly (so pin connections are correct) but when trying to display different numbers on each digit things get messy. Can anyone see what is wrong with the code? I don't seem to find it. thanks!

Working when 3 digits are the same:

Not working with different numbers (should be 3, 2, 1:

And the code:

int a = 2;               //Defining segments corresponding to the pins
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup(void) {      //Setting Pins as output
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
}

void WriteNum(int PositionN, int Number) {
  int Position;
  int NumberSegments[10][7] = {{a,b,c,d,e,g},     //Defining segments for forming numbers
                          {b,c},
                          {a,b,d,e,g},
                          {a,b,c,d,g},
                          {b,c,f,d},
                          {a,c,d,f,g},
                          {a,c,d,e,f,g},
                          {a,b,c},
                          {a,b,c,d,e,f,g},
                          {a,b,c,d,f,g}};
  digitalWrite(A0, HIGH);                       //Setting begin conditions (All segments low and no digits turned on)
  digitalWrite(A1, HIGH);
  digitalWrite(A2, HIGH);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);

  switch (PositionN) {                        //Deciding which digit to turn on
    case 1:
      Position = A0;
      break;
    case 2:
      Position = A1;
      break;
    case 3:
      Position = A2;
      break;
  }
  digitalWrite(Position, LOW);
  for (int i = 0; i < sizeof(NumberSegments[Number]); i++){       //For each segment in number to display
        digitalWrite(NumberSegments[Number][i], HIGH);            //Light that segment
        }
  delay(5);
}

void loop(void) {
  WriteNum(1,2);
  WriteNum(2,2);
  WriteNum(3,2);
}

I have three recommendations for you. @Gerben was correct as to your problem, but doing the following three steps will improve the speed of your code:

Change your definition for NumberSegments to be [10][8], and put the number of active segments as the first number of each array:

 ...[10][8] = {{6,a,b,c,d,e,g},     // ...
               {2,b,c},
               {5,a,b,d,e,g}, // etcetera

Change your for loop as follows:

for (int i = 1; i <= NumberSegments[Number][0]; i++) { // ...
   digitalWrite(NumberSegments[Number][i], HIGH); // ...
}

This will only turn on the minimum number of segments required. Note the loop now starts at 1, and uses <= instead of <.
Put the keyword static in front of NumberSegments:

static int NumberSegments[10][8] = {{ // ...

This last one is a language nicety. Every time the function WriteNum is called, the poor thing has to re-create the (large) NumberSegments array - and it’s the same every time! The keyword static means “only create this variable once”. Next time into the function, it’ll already be available: no processing required!

You might also consider moving int position; below NumberSegments, since it’s convention to put static variables first in a function.

You can also use the keyword const on NumberSegments, since its values never change:

static const int NumberSegments[10][8] = {{ // ...


How to interpret accelerometer data to get decimals from -255 to 255 I'm using gy-521 module and I'm wondering how can i get useful readings from it so that i could work with the data that I'm receiving.

I want for AcX and AcY variable values to be from -255 to 255.
How to make this work.

sample data that I'm getting right now

X = 16380 Y = -64
X = 8116 Y = 3520
X = 12564 Y = 8728
X = -12652 Y = 1296
X = -17732 Y = -2420
X = -14576 Y = -2264

;

#include<Wire.h>
const int MPU_addr=0x68;
int16_t AcX,AcY;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  AcX=Wire.read()<<8|Wire.read();
  AcY=Wire.read()<<8|Wire.read();

  Serial.print("X = "); Serial.print(AcX);
  Serial.print(" Y = "); Serial.println(AcY);

  delay(333);
}

Use this code:

AcX = map(AcX, -32768, 32767, -255, 255);
AcY = map(AcY, -32768, 32767, -255, 255);

Of course, you won't be able to store the resulting value in int8_t since its range is from -128 to 127.

Here you can read more about Arduino map() function.


FIS1100 (IMU)/ I2C/ Arduino I am a student and currently doing a semester project. The first goal is to get accelerometer and gyroscope data from FIS1100 using the Arduino (Uno). I've got the FIS1100 Evaluation Kit user guide from my supervisor. I've simply separated the sensor PCB from the MCU and connected this sensor to an Arduino Uno as shown on this photo:

The connections are as following:

SCL (on the header of FIS) - A5 (Arduino)
SDA (on the header of FIS) - A4 (Arduino)
GND (on the header of FIS) - GND (Arduino)
3V3-to VIOREF (on the header of FIS) - 3V3 (Arduino)

I wrote this simple code, which I uploaded to the Arduino board. Unfortunately as a result, I got zeros as output.

#include <Wire.h>
const int I2C_address = 0b1101010;
long a_X, a_Y, a_Z;
float g_X, g_Y, g_Z;

long gyro_X, gyro_Y, gyro_Z;
float rot_X, rot_Y, rot_Z;

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

}

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(800);

}

void setupFIS(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x02);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x08);
  Wire.write(0b10000011);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x04);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x03);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x05);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x06);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x07);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
}

void recordAccelRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x19);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  a_X = Wire.read()<<8|Wire.read();
  a_Y = Wire.read()<<8|Wire.read();
  a_Z = Wire.read()<<8|Wire.read();
  processAccelData();
}

void processAccelData(){
  g_X = a_X/16384.0;
  g_Y = a_Y/16384.0;
  g_Z= a_Z/16384.0;
}

void recordGyroRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x1F);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  gyro_X = Wire.read()<<8|Wire.read();
  gyro_Y = Wire.read()<<8|Wire.read();
  gyro_Z = Wire.read()<<8|Wire.read();
  processGyroData();
}

void processGyroData(){
  rot_X = gyro_X/1024.0;
  rot_Y = gyro_Y/1024.0;
  rot_Z= gyro_Z/1024.0;
}

void printData(){
  Serial.print("Gyro(deg)");
  Serial.print(" X=");
  Serial.print(rot_X);
  Serial.print(" Y=");
  Serial.print(rot_Y);
  Serial.print(" Z=");
  Serial.print(rot_Z);

  Serial.print("   Accel(g)");
  Serial.print(" X=");
  Serial.print(g_X);
  Serial.print(" Y=");
  Serial.print(g_Y);
  Serial.print(" Z=");
  Serial.println(g_Z);
}

So, I really need help to get some relevant data.

And also I have doubts concerning the I2C-address of the FIS1100. In the datasheet of the FIS1100 on page 50 it is said:

  the address is 0b1101010 in case when pin SA0 is left unconnected, internally there is a weak pull-down of 200k; the address is 0b1101011 in case when pin SA0 is pulled-up externally.

Now lets go again to user guide and on page 25 (schematic of pull-up/down resistors) we see that SA0 is externally pulled-down.

Question: which I2C-address should I use?

I think you'll find you need to add some pull up resistors to both connections on the I2C (SDA and SCL).

Also I'm not sure what you should be pulling them up to 3.3v or 5v.  You should check if you need a level shifter or if the device you are connecting is 5v tolerant.

According to you question you should be using the address 0x6A.  0x6B is when you have an external pull up resistor, which I don't think you do have.  So your code is correct.


Accessing Values From Array Within a Library There are many great examples of how to access information from an array on the net. I ran into a specific case that has me confused. I am using a library for attiny 85 TinyPpmReader.h. This is a simple library that will take PPM signals in from a RC receiver running in pulse position mode and allows you to attach to a pin to process input. Easy enough.

In the code below, I ran into some confusion when trying to access the data in the array. I am trying to filter out a single channel in the ppm stream and print the contents of only 1 channel (Original example prints 8 channels) and eventually map that value to a servo. (I pasted the serial monitor ouput at the end of the code)

I tried accessing the variable stored in the array like this:

void loop()
{
for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */

if(TinyPpmReader.detectedChannelNb == [5]) //Is this channel 6 in index 0-7?
{
Serial.println(TinyPpmReader.width_us[5); // if so, print only index 5 containing channel 6 values
}
delay(500);
}

Example unedited sketch from library

#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400)
  TinyPpmReader.attach(PPM_INPUT_PIN);
}

void loop()
{

  Serial.print(F("* Period="));Serial.print((int)TinyPpmReader.ppmPeriod_us());Serial.println(F(" us *"));
  Serial.print(F("ChNb="));Serial.println((int)TinyPpmReader.detectedChannelNb());
  for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */
  {
    Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us"));
  }
  delay(500);
}

The serial monitor prints this:

* Period=17928 us *
ChNb=8
Ch=1496 us
Ch=1744 us
Ch=896 us
Ch=1560 us
Ch=1640 us
Ch=1496 us
Ch=1536 us
Ch=1688 us

Any suggestions? It is probably something simple but I dont think I am googling the correct question to get the correct answer.

EDIT: That worked Mark!

New Code Mapping attempt (Compiles,does not work)

#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          // reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

This code (from the example) is what prints a single index - index Idx:

Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us")); }

To print, say, index 3 you'd use

Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us")); }

To simply get the value from index 3, without printing it:

int a = TinyPpmReader.width_us(3);

(assuming it's an int)


Web page using bluetooth? I have a project where I read 2 sensors using an esp32 and also have an web server. I can connect using mobile phone and display the page where I see info about the sensors (using web sockets to update the info on the page very quickly ) and also send some commands back to esp32. Is working fine, just the issue that when I am connected to esp I don t have internet on my phone anymore (which is a normal thing:) ).
My question is if I can achieve same but using bluetooth instead wifi ? Is there any way to have a "web page" using bluetooth ?
Thank you

No. There is no such facility in Bluetooth to provide such a feature.  That's not to say that technically it can't be done, there just isn't any software (a web browser) that would support it.

Instead you would need to use a Bluetooth-enabled app on the smartphone to communicate with the ESP32 over Bluetooth and display the data / provide control natively.  Such an app would probably have to be written by you since it would be specific to the way you are working, unless you can find a generic app that lets you design an interface for your project and then communicate using a documented protocol that you would then have to implement on the ESP32.

An alternative is to just reverse everything. Instead of having your phone connect to the ESP32 then connect to a webserver on it just have the ESp32 connect to your phone when your phone is set to WiFi Hotspot mode. You can still then get your phone to connect to the webserver on the ESP32, and your phone also has mobile internet. If course, if you are wanting internet through a WiFi connection for your phone then you can't do that. However, your ESP32 can then just also connect to your WiFi router so there is nothing to change on your phone. You just browse to the webserver on the ESP32 through your local WiFi network.


Arduino i2c communication between another arduino and a sensor Can the following scenario exist?

Microcontroller 1 sends a code to microcontroller 2 to start reading sensor data. Then Microcontroller 2 reads sensor data from sensor and sends it back to microcontroller 1.

If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

Need help with this badly!!

Can the following scenario exist?
  Yes. Such a scenario is called Multi-Master.

  If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

MCU 2 would just be set up as any other slave. It waits, as normal, for an instruction in whatever for you like. Once it receives that instruction in then switches into master mode and makes a normal request exactly as you would from MCU 1 if you wanted it to read the sensor.

On receive:

Set "run as master flag"
Disable slave mode

In loop:

If "run as master flag" is set:

Perform request to get data from sensor
Clear "run as master flag"
Enable slave mode

Running a multi-master system does have its own set of caveats and things you have to watch out for. You can read more about it here:

https://www.hackster.io/chipmc/arduino-i2c-multi-master-approach-why-and-how-93f638


Is my Arduino Uno broken? I think I broke my Arduino Uno as I was playing with it. I connected an ultrasonic range finder to it and uploaded a sketch to it. It was working fine until I accidentally touched the ICSP headers for the USB interface (the pins near the USB port). Now,everything is still working but my computer cannot detect it and it does not show up in the device manager or the IDE. Please tell me if it is broken and how to fix it.

BTW, I just bought it and just started using it after another Arduino had the same problem.

Please tell me if it is broken and how to fix it.

See Have I bricked my Arduino Uno? Problems with uploading to board

Those tips may also help with fixing problems with your Mega (if you ever have them). ;)


Powering multiple Arduino shields To start, I am a software guy, so I am not too clued up on the electronics side of things. My question is: I have a number of Arduino shields and would like to power them with a portable power source, and therefore would like some advice on what to use without frying any electronics.

This is a list of the current equipment that will require power:

Arduino Mega 2560
SIM900 GPRS/GSM Shield
Sparkfun GPS Logger Shield
Sparkfun Wifi Shield - ESP8266

The shields will be stacked on top of each other.

All the shields are 5v compatible. So no need to worry about 3.3v.

But there may be a chance of insufficient current if you use a battery to the power-jack of arduino mega (due to the internal voltage regulator). I'd suggest you cut a USB cable and solder the +5(red color) wire to VIN on the mega and ground(black wire) to GND pin. And use a 'power bank', which is used for mobile phones.


Compiling Assembly Script in External EEPROM to Arduino Code I'm working on a simple game console, and I'm planning to use a cartridge system using an EEPROM. I know that you can read and write data from an EEPROM, but can you compile the data into executable Arduino code, and vice versa? If the Arduino can do it, we can probably too, right?
Thanks in advance!

I would suggest you investigate a different micro with external addressing or one that loads its code from an external memory such as flash like the ESP32s do.


Crosses Initialization in switch case with different size of array per case void setup()  {
 Serial.begin(9600);
}

void loop()
{
 time_Text(2);
}

void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    int tPTT_y[] = {11, 11, 11, 11};
    int tPTT_x[] = {6, 7, 8, 9};
  }
  break;
case 2:
  {
    int tPTT_y[] = {11, 11};
    int tPTT_x[] = {10, 11};
  }
  break;
 }

 int n_tPTT = sizeof(tPTT_x) / sizeof(tPTT_x[0]);

 Serial.print(tPPT_y);
 Serial.print(" : ");
 Serial.print(tPPT_x);
 Serial.print(" : ");
 Serial.println(n_tPPT);

}

I have a case that I need to assign different kind of array value (with different size per case), and then find the size of the array, and print it. The problem is that the tPTT_y and tPTT_x is a local variable which cannot be accessed outside of the case function. I have tried to declare it before the switch function but I cannot give a size number because the size is different per case, how could I solve this?

Create two global arrays that contain the maximum amount of number you ever need, e.g.

int tPTT_x[4];
int tPTT_y[4];

Than create one global int that contains how much x and y are filled, e.g.

int filled;

Than you can change your cases to

void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    tPTT_y[0] = 11;
    tPTT_y[1] = 11;
    tPTT_y[2] = 11;
    tPTT_y[3] = 11;
    tPTT_x[0] = 6;
    tPTT_x[1] = 7;
    tPTT_x[2] = 8;
    tPTT_x[3] = 9;
    filled = 4;
  }
  break;
case 2:
  {
    tPTT_y[0] = 11;
    tPTT_y[1] = 11;
    tPTT_x[0] = 10;
    tPTT_x[1] = 11;
    filled = 2;
  }
  break;
 }

Than you can use the 'filled' variable to see how many items in the array are 'valid' (0 <= item < filled).


Getting different values inside vs. outside a function while using global array function splitter is designed to get a string of parameters and create a an array of parameters. If only part of parameters were given, the rest of them will get default values.

for example : input string 1,2,3,4 would fill parameters array with values {"1","2","3","4"}, but  if input string is 1,2, parameters={"1","2","20","0"} while parameters[3] and parameters[2] were given its default values.

BUT

when assigning default values, inside splitter the correct values are stored in parameters but when using print_output function to show parameters values - different values are shown.

in output supplied, when input is 1,2,  default values should be pasted, to parameters[2], and parameters[3] , while input is 1,2,3,4 no need to use defaults.

OUTPUT:

Running string 1,2
param_2 was set to default value:20
param_3 was set to default value:0
output:
1
2
0
0
Running string 1,2,3,4
output:
1
2
3
4

CODE:

#define PARAM_AMOUNT 4
#define COLOR 1
#define LED_DELAY 20
#define BRIGHTNESS  50
#define LED_DIRECTION 0

char *parameters[PARAM_AMOUNT] = {"0", "0", "0", "0"};
int param_def[] = {COLOR, BRIGHTNESS, LED_DELAY, LED_DIRECTION};

void setup() {
  Serial.begin(9600);
  Serial.println("Running string 1,2");
  splitter("1,2");
  print_output();

  Serial.println("Running string 1,2,3,4");
  splitter("1,2,3,4");
  print_output();
}

void splitter(char *inputstr) {
  char * pch;
  int i = 0;

  pch = strtok (inputstr, " ,.-");
  while (pch != NULL)
  {
    parameters[i] = pch;
    pch = strtok (NULL, " ,.-");
    i++;
  }

  //  update default values
  for (int n = i ; n <= PARAM_AMOUNT - 1; n++) {
    sprintf(parameters[n], "%d", param_def[n]);
    Serial.print("param_");
    Serial.print(n);
    Serial.print(" was set to default value:");
    Serial.println(parameters[n]);
    delay(50);
  }
}

void print_output() {
  Serial.println("output:");
  for (int n = 0 ; n <= PARAM_AMOUNT - 1; n++) {
    Serial.println(parameters[n]);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
}

It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:

char parameters[PARAM_AMOUNT][PARAM_LEN];

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.

Then in splitter function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.

strcpy(parameters[i], pch); will copy the token returned by strtok into your array. pch points into inputstr and the delimiters in inputstr are replaced by 'strtok' with zeros


Did I break my new Arduino Leonardo Eth by restarting it? I just bought a new Arduino Leonardo Eth, and, it was working perfectly.

I probably uploaded about 30 different sketches, and it did everything as expected.

The basic sketch was using the fade demo on pin 9 to ground with a LED attached.

I was then curious on how long the unit takes to restart, so, I unplugged the USB and put it back in.

When it started back up, the LED was on solid. I then restarted it again, and I honestly can't remember the state of it.

When I plug it in, it gets detected in the Arduino application and I see the port, but, after about 20 seconds, I get a popup on Windows saying about a malfunctioning USB device.

Pressing reset on the Arduino or unplugging/plugging it back does the same - I get about 20 seconds, and then it "goes bad".

Even if I am real quick in the IDE, or press restart after compiling/before upload, it just hangs.

I'm really annoyed with myself if I did break it, but, I'm not really sure what else I could have done differently... after all, there isn't an off switch.

Does anyone know what I have done, and, is there anyway to fix it?

You should be able to use my board detector sketch on one of your other Arduinos to check out the problem board.

See also Have I bricked my Arduino Uno? Problems with uploading to board

Also my bootloader uploader sketch will reflash bootloaders on quite a few devices. I'm assuming that the "Arduino Leonardo Eth" has the same bootloader as the Leonardo.

Hmmm - I see that the "Arduino Leonardo Eth" is from Arduino.org, not Arduino.cc. The bootloader is probably slightly different. I'm really not an expert on what those boards use.

Before worrying too much, try the approach of holding down Reset and then uploading a sketch, letting go of Reset as the sketch starts to actually upload.

Comment by William Hilsum

  I didn't realise there was a difference between .org and .cc, and, I guess by using the leonardo template from .cc, I broke "something". The moment I downloaded the IDE from .org, & uploaded with the eth template , it worked flawlessly. I guess there are some changes between leonardo and leonardo eth. I wanted an arduino with ethernet, so I didn't need a separate shield. No idea if I picked the right "side" after reading all the crap with cc vs org!

That is very annoying that the split of the Arduino camps now produces a support nightmare for people who just want to use their virtually identical products, but have to go through this.

Thanks for the update.


How to receive data from my server database to a variable in my Arduino? I am learning to work with the client - server communication. I am able to communicate with my server and able to store values in the table. But I want to receive one of the specific data from the database.

Here I want to get the 'abc' value from the 'Current' column to store in a variable in my Arduino.

Below is the code that I have done until now. I would be really happy if you could solve the problem.

Here is my database structure

---------------------------------------------------
| Device |  Previous |  Next |  Distance |  Current|
---------------------------------------------------
|katup123| xyz       | abc   | 2.600     | abc     |
---------------------------------------------------

Here is my PHP code:

locator.php

<?php
$con=mysqli_connect("your_domain.com","peter","abc123","locate");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Current FROM locate WHERE Device='katup123'");

while($row = mysqli_fetch_array($result)) {
  echo $row['Current'];
  echo "<br>";
}
?>

Here is my Arduino code:

// Include the GSM library
#include <GSM.h>
#define PINNUMBER ""
// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APNgpsll
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password
// initialize the library instance
GSM gsmAccess;
GSMClient client;
GPRS gprs;
// URL, path & port (for example: arduino.cc)
char server[] = "your_domain.com";
char path[] = "/locater.php";
int port = 80; // port 80 is the default for HTTP

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;
  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected) {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) & (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  Serial.println("connecting...");
}

void loop() {
  char result [20];
  Serial.print(" Connecting to server Database ");
  if (client.connect(server, port)) {
    client.print("GET /locator.php?");
    Serial.print("GET /locator.php?");
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: www.your_domain.com");
    Serial.println("Host: www.your_domain.com");
    client.println("User-Agent: Arduino");
    Serial.println("User-Agent: Arduino");
    client.println("Accept: text/html");
    Serial.println("Accept: text/html");
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
    Serial.println();
    Serial.println("\nCOMPLETE!\n");
    client.stop();
  } else {
    Serial.println("connection failed");
    Serial.println("\n FAILED!\n");
  }
  delay(5000);
}

Here I want to store the 'abc' value to my 'result' variable. I don't know how to do it.

After you send the GET request, you read the response to fill the char result [20] variable you declared:

int i=0;
...
if (client.connect(server, port))
{
  client.print("GET /locator.php?");
  ...
  Serial.println("\nCOMPLETE!\n");

  // Read response from server
  i=0;
  while (client.available())
  {
    result[i] = client.read();
    Serial.print(result[i]);
    i++;
  }

  client.stop(); // disconnect
}

This is an example, result will contain the text output by locator.php. You will need to tweak this code to apply to your case. The above code has no error checking of any kind. Also, you should perform a check and only make the web call one time.

In locator.php you should replace echo "<br/>"; with echo "\n";. And for good measure, make sure there is no white space before <?, and remove the trailing ?>.


Counting minutes in arduino I have a dipswitch of 4 steps to get a binary number that will turn out to decimal from 0 to 15, So I need to get that number and make it the ammount of minutes to make something and also be aware of some input while the time runs out.

So I was thinking of having a variable being equal to millis() and then dividing it by 60,000 which is a minute in millis and If I get an integer that must mean a minute has passed, the problem is that I don't know how to check if the result is an integer or a float.

any advice?

Your method is completely wrong.

You need a variable that contains the value of millis() at the start of your period, whenever that may be (when the switches change? when a button is pressed? since the Arduino was powered up?) and compare that value to the current value of millis().  When the difference between them is greater than or equal to 60000 * 15 then 15 minutes have passed.

Look at BlinkWithoutDelay in the Examples menu in the IDE - it showcases the technique for you.


Sending uint16_t over I2C How do you transmit and read a uint16_t over I2C?

I'm trying to read two uint16_t values from a slave device, and I'm seeing nonsensical readings.

This is the code on my slave Arduino Uno:

#include <Wire.h>

void send_wire_int(uint16_t num){

    // Send low byte
    Wire.write((uint8_t)num);

    // Send high byte
    num >>= 8;
    Wire.write((uint8_t)num);
}

// This is called from the I2C host.
void I2C_Send()
{

    //  send_wire_int(acount_abs);// Send encoder A count.
    //  send_wire_int(bcount_abs);// Send encoder B count.

    send_wire_int(0);
    send_wire_int(0);

}

void setup(){

    Wire.begin(30);                                                        // initialize I²C library and set slave address
    Wire.onRequest(I2C_Send);                                                   // define I²C slave transmit ISR

    Wire.flush();
    Wire.setTimeout(1000L);

}

void loop(){
    //stuff
}

All it does is wait for the master to request data. Originally, it was sending the values of two registers back, but these values were also garbled or non-changing, so I changed it to just send back 0s but I still get the identical garbled values.

This is the code on my master Arduino Uno:

#include <Wire.h>

uint16_t receive_wire_int(){

    while(Wire.available() < 1){}

    // Read low byte into rxnum
    uint16_t rxnum = Wire.read();

    while(Wire.available() < 1){}

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    return rxnum;
}

void setup() {
    Wire.begin();        // join i2c bus (address optional for master)
    Wire.setTimeout(1000L);
    Serial.begin(9600);  // start serial for output
}

void loop() {
    Serial.println("Requesting data..."); Serial.flush();

    Wire.requestFrom(30, 4);

    uint16_t acount = receive_wire_int();
    uint16_t bcount = receive_wire_int();

    Serial.println(String("acount:")+String(acount)+String(" bcount:")+String(bcount));

    delay(500);
}

As you can see, it simply requests the two uint16_t values in 4 bytes, and then prints them to the Serial (my laptop's terminal).

The output I'm seeing is:

acount:65280 bcount:65535

when I would expect:

acount:0 bcount:0

What I am I doing wrong?

So I've just tested your code and apparently you have to send all data at once. After some research: it sends characters into the function twi_transmit and this function just fills the buffer and actual data are sent asynchronously. So, if you are fast enough, you will overwrite the buffer with another bytes and it's still like you have only 1 character to send.

For example this works (AVRs are little endian):

#include <Wire.h>

// This is called from the I2C host.
void I2C_Send()
{
    uint16_t   uints[2] = {0xDEAD,0xBEEF};

    Wire.write((uint8_t*) uints, 4);
}

void setup(){
    Wire.begin(30);  // initialize I²C library and set slave address
    Wire.onRequest(I2C_Send); // define I²C slave transmit ISR

    Wire.flush();
    Wire.setTimeout(1000L);
}

void loop(){
    //stuff
}

And receiver with HEX prints:

#include <Wire.h>

uint16_t receive_wire_int(){

    while(Wire.available() < 1){}

    // Read low byte into rxnum
    uint16_t rxnum = Wire.read();

    while(Wire.available() < 1){}

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    return rxnum;
}

void setup() {
    Wire.begin();        // join i2c bus (address optional for master)
    Wire.setTimeout(1000L);
    Serial.begin(9600);  // start serial for output
}

void loop() {
    Serial.println("Requesting data..."); Serial.flush();

    Wire.requestFrom(30, 4);

    uint16_t acount = receive_wire_int();
    uint16_t bcount = receive_wire_int();

    Serial.print("acount: 0x");
    Serial.print(acount,HEX);
    Serial.print("  bcount: 0x");
    Serial.println(bcount,HEX);

    delay(500);
}


How to wake up Arduino Mega when in Power Saving Sleep Mode? I'm using sleep mode to turn off my device after the routine has finished executing and want to use interrupts to wake it up every 33 milliseconds. Basically, the idea is that if the routine completes in less than 33 milliseconds the processor can shutdown and save power for whatever remaining time, which will hopefully translate to reduced power consumption. I've currenlty managed to turn off my device with the sleepNow() function you see below, but the interrupt I have programmed in doesn't seem to work. The program simply goes to sleep and never wakes up. What am I doing wrong?

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

const uint16_t PERIOD = 2150;

void setup()
{
  noInterrupts();
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B |= (1 << CS12); // ...and set the prescaler
  interrupts();

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  Serial.println(millis());
}

void loop()
{
  Serial.println("Program is on");
  Serial.flush();
  sleepNow();
}

void sleepNow()
{

    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_PWR_SAVE);

    // Set sleep enable (SE) bit:
    sleep_enable();

    // Put the device to sleep:
    sleep_mode();

    // Upon waking up, sketch continues from this point.
    sleep_disable();

}

It is certainly tempting to go into a very deep sleep in order to save
power, but you still need to keep awake whatever peripheral you want to
use as a wakeup source. If you want to use a 16 bit timer, there is no
other choice than SLEEP_MODE_IDLE.

But it may not be that bad. In IDLE mode you can selectively disable the
clock (and hence put to sleep) the peripherals you do not use. Or maybe
put them all to sleep, and then wake up the few ones you do need. This
is achieved with the power_*_disable() and power_*_enable() family
of functions.

In the edited code below: all peripherals but the Timer 1 are disabled
while the CPU sleeps. The USART is enabled only for the time it needs to
send its message:

#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <util/delay.h>

const uint16_t PERIOD = 2150;  // 34.4 ms

void setup()
{
  // Disable all but the needed peripherals.
  power_all_disable();
  power_timer1_enable();

  // This is for debug pulses.
  pinMode(22, OUTPUT);

  // Configure Timer 1 to wake us up every 34.4 ms.
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
         | _BV(CS12);    // ...and set the prescaler /256

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  // Send a debug pulse.
  digitalWrite(22, HIGH);
  _delay_ms(2);
  digitalWrite(22, LOW);
}

void loop()
{
  // Enable the USART only while needed.
  power_usart0_enable();
  Serial.println("Program is on");
  Serial.flush();
  power_usart0_disable();

  // And go to sleep in IDLE mode.
  sleep_mode();
}

Notice also that the ISR does not print to the serial port: it just
sends a debug pulse to watch with the scope. This should be removed from
production code. The delay is achieved with the avr-libc function
_delay_ms() because the standard Arduino delay() would not work: it
relies on Timer 0, which has been disabled.


Error with Arduino/Processing Serial Communication I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.

Arduino Code:

int ledPin = 13;
int knockSensor = A0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 5;
int sensorReading = 0;

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

void loop() {
 sensorReading = analogRead(knockSensor);

  if(sensorReading > 0){
   Serial.println(sensorReading, DEC);
   delay(100);
  }
}

Processing Code:

import processing.serial.*;

Serial port;

int centerX = 550;
int centerY = 400;

float val;
float ellipseX;
float ellipseY;
float ellipseW;
float ellipseH;
float ellipseXX;
float ellipseYY;
float ellipseWW;
float ellipseHH;
float lineX;
float lineY;
float lineXX;
float lineYY;

void setup(){
  background(255);
  size(1100,800);
  frameRate(10);
  smooth();

  String portname = "/dev/tty.usbmodem1411";

  //String portname = Serial.list()[0];
  port = new Serial(this, portname, 9600);
  println(Serial.list());
  //port.bufferUntil('\n');
}

void drawEllipse(float val)
{
  if(val > 0 && val < 50)
  {
    ellipseX = random(540,560);
    ellipseY = random(390,410);
    ellipseW = val + 10;
    ellipseH = val + 10;

    stroke(0);
    fill(random(255), random(200,255));
  }
}

void drawLines(float val)
{
  if(val > 50 && val < 70)
  {
    lineX = random(500, 600);
    lineY = random(360, 440);
    lineXX = random(500, 600);
    lineYY = random(360, 440);

    stroke(0);
  }
}

void drawEllipse2(float val)
{
  if(val > 70 && val < 120)
  {
    ellipseXX = random(460, 640);
    ellipseYY = random(330, 470);
    ellipseWW = val + random(20);
    ellipseHH = val + 10;

    stroke(0);
    fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
  }
}

void serialEvent(Serial port)
{
  String inString = port.readStringUntil('\n');

  if (inString != null)
  {
      val = Float.parseFloat(inString);
  }

  drawEllipse(val);
  drawLines(val);
  drawEllipse2(val);
  println(val);
}

It seems like you need to do some basic debugging:

Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.


Connecting PC speaker to Arduino I've looted this speaker from my old PC and trying to understand how to connect it to Arduino to produce simple sound notification (and not fry anything in the process).

As far as I understand this is a piezo speaker, there is no markings on it. Here is how it looks:

How do I connect\control it?

Should I connect it to PWM pin? If so, what are the safe values to output on PWM pin?

Should I use resistor when connecting speaker? What resistor should I use?

No need for a resistor. Just connect black to ground, and red to a IO pin. Use the tone function to specify a frequency.


Trying to start a timer to change lights when a button is pressed I am trying to setup a series of lights (traffic lights) that change based on a timer that begins when a button is pressed.  The goal is to use the lights to track how long its been since you pressed the button.

The issue I am running into is trying to use the "TimeAlarms" library.  I am getting an error
'Timer' was not declared in this scope

I think it may be an issue with the version of Arduino I am using (1.6.8) but I am not sure.

Board: Arduino Leonardo

Here the code:

#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      void YellowTimer(){
         setLights(LOW, HIGH, LOW)
         }
      void RedTimer(){
         setLights(HIGH, LOW, LOW)
         }
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}

Any help would be greatly appreciated.

You must first declare your timer functions. I have placed them above so they are visible when you call the timer. Also in the loop() you want probably to call timer.
I have changed the code to reflect what I told above. I do not have ability to test this, so please try. There may be some syntax errors, but I think you can handle it.

#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void YellowTimer()
{
    setLights(LOW, HIGH, LOW)
}

void RedTimer()
{
    setLights(HIGH, LOW, LOW)
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      Alarm.timerOnce(86400, YellowTimer);
      Alarm.timerOnce(172800, RedTimer);
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}


Reload only one variable in loop() I need some information for the TFT screen 2.8 and arduino mega.
The screen works very well and displays the data.
The small problem I encounter is for the text display, the page is reloading every second and this makes a small black screen every second.
I would like to know if it was possible to reload only one part of the screen display?

See in video
https://youtu.be/vxSa6xkH0vU

My loop()

void loop(void) {
   tft.fillScreen(BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setRotation(3);
  dt = clock.getDateTime();
  clock.forceConversion();

  // Go
  tft.println();
  tft.setTextColor(GREEN);
  tft.setTextSize(5);
  tft.println("Info");
  tft.println();
  tft.setTextSize(2);
  tft.println(clock.dateFormat("d-m-Y H:i:s", dt));
  tft.println();
  tft.setTextSize(2);
  tft.println("Temperature: ");
  tft.println(clock.readTemperature());

  delay(1000);
}

You can use tft.rect(x,y,width,height) to clear only a portion of the screen. Make sure to set tft.fill before calling it.


Will the 3.3V regulator on an Arduino Leonardo work when powered from USB? Will the 3.3V regulator produce 3.3v when the Arduino is powered from the USB port?

Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?

Yes, provided that

it is an "official" Leonardo or a competent clone and
as long as you do not load the power supply excessively with external loads.

Official circuit diagram here

The USB supply feeds the 3V3 regulator via MOSFET T1 at the bottom of the sheet and U3, an LP2985 LDO regulator. If your board has the same circuitry as this it should provide 3V3 from USB.


Arduino continually resets when connected to external power supply, but not USB I'm working on a seemingly simple Arduino project which plays a sound and flashes an LED when provoked by some trigger.

The problem:

When powered by an external power supply, the Arduino continually resets after playing ~1/4 seconds of audio. When powered from USB, it works fine (however the LED, being powered from the external power supply, of course does not work here).

Wiring diagram:

Parts list:

Arduino Pro Mini 5V
Adafruit MAX98306 3.7W amplifier
Sparkfun FemtoBuck LED Driver
4 Ohm 3W speakers
3W LED

I am using a 9V 1A power supply. Again, when no speakers are connected, the Arduino and LED work as intended. It's only when a speaker is connected that the board resets over and over again. Playing roughly 1/4 of a second of audio and then resetting implies to me that there's insufficient current, however, the problem persists even after using a 2.5A power supply.

Things I have tried:

Increasing the power supply to 12V 2.5A
Desoldering the LED driver (even with the LED driver removed, the board still resets)
Checking continuity and staring at the wiring for long periods of time while scratching my head

Overall, I'm at a loss as to why it would work when powered via USB instead of through my external power supply.

What am I doing wrong? Any insights are greatly appreciated!

Most likely lack of current - lack of current able to be provided by the Mini. The audio is powered from the onboard regulator on the Mini, which has limited current capacity.

If too much current is drawn it will either get too hot and go into thermal shutdown until it cools down enough, or it will drop the output voltage, making things reset and crash.

Power the audio system from an external 5V regulator.


Could someone explain this weird looking code, used to setup timers? While looking at sketches other people have written, I occasionally come across code that looks somewhat like this:

TCCR1A = 0;
TCCR1B = 0;

TCNT1 = 34286;
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << TOIE1);

All I know is that is has something to with timing/timers (I think). How can I decipher—and create—code like this? What are TCCR1A, TCCR1B, TCNT1, CS12, TIMSK1, and TOIE1?

This isn't weird looking. It's what normal MCU code actually looks like.

What you have here is an example of the concept of memory-mapped peripherals. Basically, the MCU hardware has special locations in the SRAM address space of the MCU assigned to it. If you write to these addresses, the bits of the byte written to address n control the behaviour of peripheral m.

Basically, certain banks of memory literally have little wires running from the SRAM cell to the hardware. If you write a "1" to this bit in that byte, it sets this SRAM cell to a logical high, which then turns on some portion of the hardware.

If you look into the headers for the MCU, there are great big tables of keyword<->address mappings. This is how things like TCCR1B etc... are resolved at compile time.

This memory-mapping mechanism is extremely broadly used in MCUs. The ATmega MCU in the arduino use it, as do PIC, ARM, MSP430, STM32 and STM8 MCU series, as well as lots of MCUs I'm not immediately familiar with.

Arduino code is the weird stuff, with functions that access the MCU control registers indirectly. While this is somewhat "nicer" looking, it's also much slower, and uses a lot more program space.

The mysterious constants are all described in great detail in the ATmega328P datasheet, which you really should read if you're interested in doing anything more then occationally toggling pins on an arduino.

Select excerpts from the datasheet linked above:

So, for example, TIMSK1 |= (1 << TOIE1); sets the bit TOIE1 in TIMSK1. This is achieved by shifting binary 1 (0b00000001) to the left by TOIE1 bits, with TOIE1 being defined in a header file as 0. This is then bitwise ORed into the current value of TIMSK1, which effectively set this one bit high.

Looking at the documentation for bit 0 of TIMSK1, we can see it is described as

  When this bit is written to one, and the I-flag in the Status Register
  is set (interrupts globally enabled), the Timer/Counter1 Overflow
  interrupt is enabled. The corresponding Interrupt Vector (See
  ”Interrupts” on page 57) is executed when the TOV1 Flag, located in
  TIFR1, is set.

All the other lines should be interpreted in the same manner.

Some notes:

You may also see things like TIMSK1 |= _BV(TOIE1);. _BV() is a commonly used macro originally from the AVR libc implementation. _BV(TOIE1) is functionally identical to (1 << TOIE1), with the benefit of better readability.

Also, you may also see lines such as: TIMSK1 &= ~(1 << TOIE1); or TIMSK1 &= ~_BV(TOIE1);. This has the opposite function of TIMSK1 |= _BV(TOIE1);, in that it unsets the bit TOIE1 in TIMSK1. This is achieved by taking the bit-mask produced by _BV(TOIE1), performing a bitwise NOT operation on it (~), and then ANDing TIMSK1 by this NOTed value (which is 0b11111110).

Note that in all these cases, the value of things like (1 << TOIE1) or _BV(TOIE1) are fully resolved at compile time, so they functionally reduce to a simple constant, and therefore take no execution time to compute at runtime.

Properly written code will generally have comments inline with the code that detail what the registers being assigned to do. Here is a fairly simple soft-SPI routine I wrote recently:

uint8_t transactByteADC(uint8_t outByte)
{
    // Transfers one byte to the ADC, and receives one byte at the same time
    // does nothing with the chip-select
    // MSB first, data clocked on the rising edge

    uint8_t loopCnt;
    uint8_t retDat = 0;

    for (loopCnt = 0; loopCnt < 8; loopCnt++)
    {
        if (outByte & 0x80)         // if current bit is high
            PORTC |= _BV(ADC_MOSI);     // set data line
        else
            PORTC &= ~(_BV(ADC_MOSI));  // else unset it

        outByte <<= 1;              // and shift the output data over for the next iteration
        retDat <<= 1;               // shift over the data read back

        PORTC |= _BV(ADC_SCK);          // Set the clock high

        if (PINC & _BV(ADC_MISO))       // sample the input line
            retDat |= 0x01;         // and set the bit in the retval if the input is high

        PORTC &= ~(_BV(ADC_SCK));       // set clock low
    }
    return retDat;
}

PORTC is the register that controls the value of output pins within PORTC of the ATmega328P. PINC is the register where the input values of PORTC are available. Fundamentally, things like this are what happen internally when you use the digitalWrite or digitalRead functions. However, there is a look-up operation that converts the arduino "pin numbers" into actual hardware pin numbers, which takes somewhere in the realm of 50 clock cycles. As you can probably guess, if you're trying to go fast, wasting 50 clock cycles on an operation that should only require 1 is a bit ridiculous.

The above function probably takes somewhere in the realm of 100-200 clock cycles to transfer 8 bits. This entails 24 pin-writes, and 8 reads. This is many, many times faster then using the digital{stuff} functions.


D1 Robot... lights up but nothing I have the Arduino shield described here, I have run the example code compiled to the device, both v1 and 1.1 example, and it shows nothing whatsoever on the screen.

https://www.dfrobot.com/wiki/index.php/Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)

Is there a special trick to initializing this or did I yet again get a lemon that will not display anything?

I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display.


3rd Libraries: fatal error: Something.h: File does not exist I created this question because I find many questions with similar problems,
  so I wanted to provide a reference/ more generic question for these type of problems.

For my projects I have installed 3rd party libraries by cloning from the library's git repository into the folder that preferences.txt's sketchbook.path value exists into a folder named libraries. In other words if the sketchbook.path has the value /home/myuser/sketchbook I clone the repositories into the folder /home/myuser/sketchbook/libraries.

Then on the folder /home/myuser/sketchbook/myexample I store my code myexample.ino that needs a library with header files Something.h.

While I click on Arduino IDE the verify button I get the error:

/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions
    -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD
    -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__
    -I/usr/share/arduino/hardware/arduino/cores/arduino
    -I/usr/share/arduino/hardware/arduino/variants/standard
    -I/usr/share/arduino/libraries/SPI
    /tmp/build6596169359663087897.tmp/LoRaSerialGateway.cpp -o
    /tmp/build6596169359663087897.tmp/LoRaSerialGateway.cpp.o
LoRaSerialGateway.ino:15:18: fatal error: Something.h:
compilation terminated.

So my guess is that I cannot make avr-gcc to compile using the 3rd party library. Do you know how to pass into avr-gcc the correct paths for the appropriate libraries?

Assuming you have a working library system already, i.e., there are some libraries in .../libraries now and they compile properly or at least the compiler are successfully finds them; and you want to add another library, say "CrashAndBurn.h" and "CrashAndBurn.cpp", you need to put those two files into a folder named .../libraries/CrashAndBurn/. Then in your sketch, you add an include directive #include <CrashAndBurn.h>.

An alternative is to put the .h and .cpp files somewhere else, such as a folder under your project folder, and modify the include directive to point to them, as #include "libs/CrashAndBurn.h", where the libs folder is within the sketch folder. Or you could put them in any folder, anywhere, and write an absolute path to them: /home/some/place/else/CrashAndBurn.h


ATMega328P-PU and 328P-AU im planing to make my very own arduino design based on the Arduino PRO mini. I picked this board instead of the UNO mostly because it's way more simpler compared with the UNO since the USB-to-Serial part is missing. As many of you know the MINI uses the 328P-AU which is the SMD version of the 328P however since the AU version is too small for me i would like to use the PU (UNO's chip) instead. From the datasheets the only difference is a small change in the pins position. And the one million dollar question is: Is there any difference on those 2 chips? If i try to use the same design just with the PU model is it gonna work?

The -AU and -PU suffixes on the part name indicate different packages. The former is used for the "32A" package (32-lead TQFP), and the latter is used for the "28P3" package (28-lead DIP). In plain English, the -AU is a surface-mount part, and the -PU is a breadboard-friendly chip.

As far as functionality, there is virtually no difference. The 32A package exposes pins for ADC6 and ADC7, which are not available on the 28P3 package, but they are otherwise identical. (Note that these pins are only used for the ADCs; they are not a member of any port, and thus cannot be used for digital I/O.)


Computer not detecting my Arduino MEGA 2560 R3 I've tried different USB cables, computers, ports and none of them can detect my possibly bricked Mega 2560 R3. Nothing shows up at all in the Device Manager, not even "Unknown Device".

When the board is plugged in via USB, the "L" LED is constantly lit as well as the "ON" LED next the reset button.

I came up on this article here and I gave it a try, which I believe is putting it in DFU mode. However I'm not having any luck with this. http://www.wayneandlayne.com/blog/2011/02/16/fixing-linux-firmware-issues-on-arduino-mega-2560/

Any one have any ideas on where to go from here? I'm very new with Arduino.

If your Mega has an ICSP header for the USB chip (circled below) then you can test that chip.

You can use another Arduino (eg. a Uno) to detect the signature on that chip, as per my sketch on Sketch to detect Atmega chip types.

All you need is 6 hookup wires to connect your testing board (the known good one with the sketch on it) to the ICSP header on the Mega. Note the pin orientation. I have circled the correct header pins, and pointed to pin 1. On the board pin 1, has a small white dot.

Below are the ICSP pin names, seen from above (component side).

Wire the Uno to the chip being tested as follows:

Arduino Uno      Target chip

D10 (SS)            /RESET
D11 (MOSI)          MOSI
D12 (MISO)          MISO
D13 (SCK)           SCK

Gnd                 GND
+5V                 VCC

Check your wiring! If you wire things around the wrong way you can turn a good chip into a bad one.

Important! Only attempt this process if you can see that you have an ATmega8U2 or ATmega16U2 chip on your board (see below). If you have something totally different this will not work. In that case you probably have a cheap clone board.

Using the Serial Monitor on your Uno, you should then see something like this:

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  7 2015 at 10:47:47 with Arduino IDE 106.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x93 0x89
Processor = ATmega8U2
Flash memory size = 8192 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xFF
Clock calibration = 0xAB
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 1000

Bootloader:

1000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
1010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
1020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xCB 0xC4 0x00 0x00
1030: 0x4E 0xC0 0x00 0x00 0x4C 0xC0 0x00 0x00 0x4A 0xC0 0x00 0x00 0x48 0xC0 0x00 0x00
...

My board had a ATmega8U2 on it, yours might have a ATmega16U2. However the concept is the same. If you see something like that, the chip is (probably) good. At least it responds to programming commands.

If you see something like

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  7 2015 at 10:47:47 with Arduino IDE 106.
Attempting to enter ICSP programming mode ......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

Then either you made a wiring error, or the chip is bad.