Receiving junk values in Arduino serial monitor console I want to send a character from a Zigbee transmitter to an Arduino Mega 2560. After the character is received, Arduino should send some data back to Zigbee. But Arduino is always receiving junk values at the console. If I send a character, suppose 'a', instead of 'a', Arduino console is always showing 'y'. It is the same for every character I send.

#include <EEPROM.h>
#include <SoftwareSerial.h>
SoftwareSerial XBee(19, 18); // RX, TX
int addr = 0;
unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000;  //the value is a number of milliseconds
void setup()
{

  XBee.begin(9600);
  Serial1.begin(9600);
  Serial.begin(9600);
  startMillis = millis();  //initial start time
 }
void loop()
{
  int id = 1;
  EEPROM.write(addr, id);
  if (Serial1.available()>0)
    {
      currentMillis = millis();  //get the current "time" (actually the number of milliseconds since the program started)
  if (currentMillis - startMillis >= period)  //test whether the period has elapsed
  {
    char recbyte=Serial.read();
    Serial.print(recbyte);
    // delay(1500);
    Serial1.write(id);
    Serial1.write(" 30 ");
    Serial1.write(" 99 ");
    Serial1.write(" 72 ");
    Serial1.write(" 1098 ");
    Serial1.write(" 728 ");
    Serial1.write(" 578 ");
    // Serial1.write("$");
    Serial1.write('PS=1\r\n');
    Serial1.end();
    startMillis = currentMillis;
  }
    }
}

You have created a SoftwareSerial instance called XBee which is taking pins 17 and 18. You then use Serial1 which is pins 17 and 18.

You do not want, nor need, the XBee SoftwareSerial instance, since you are using hardware serial pins.  Delete it and all references to it.

Also, you are turning off Serial1 after using it, which means it will never work again:

Serial1.end();

You would only use that instruction in very very specific circumstances.  Delete it.

After checking to see if there is data available to read on Serial1 you then proceed to try and read it from Serial:

char recbyte=Serial.read();

That should be:

char recbyte=Serial1.read();

You are writing to EEPROM on every single iteration of loop:

EEPROM.write(addr, id);

It is likely that you have already killed your EEPROM.  C'est la vie...


Is it safe to power the Uno with 18v? So I'm aware the Arduino Uno can take 6-20 volts, with a recommended voltage of 7-12. But I have an unregulated 12v power adapter, which puts out about 18v with no load.

Most of the time the Arduino won't be doing much of anything but powering a 16x2 LCD, which should take only a couple mA.* I have a 10k ohm resistor on the back light, so it should only take 0.5mA.
*I don't have a datasheet, but from what I've read 1-2mA is reasonable

The Arduino won't be doing anything else that would draw any meaningful amount of current (except looping to check for input, etc). Online sources generally indicate the power draw when not doing anything is a little under 50mA, so I'm guessing that's about what the current draw will be. Using the formula in this answer, I calculate the power dissipation by the voltage regulator to be (18v-5v)*0.05A=0.65 Watts.

Is this correct?
Is the voltage regulator likely to overheat?

I'm not really concerned about power usage, because it will be plugged into the wall all the time. Also, the Arduino will be out of sight, but will have plenty of air around it to disipate heat (though not access to a breeze).

It won't do any harm to try it at 18V for a while. Most voltage regulators have thermal protection and just cut out if they get a little too hot. If it works reliably, stay with it.

EDIT: Their Uno page warns against overheating the board, so I would test it for a short while and make sure there is no overheating or strong "plastic" smell coming from the board. If there's enough heat to worry, then it's best not to run like that for extended periods.

If 18V is too high, you could get a power resistor (I'd guess say a 10 watt resistor around 24 ohms) to waste approximately half an amp from the power supply. Connect this to the supply, in parallel with the Arduino.  It's wasteful (unless your room needs heating anyway) but will lower the voltage (that reaches the Arduino) a little.


Decimal numbers sent over Serial get split and sent over multiple ticks Here is my Arduino sketch:

#include <HX711.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
HX711 hx(9, 10, 128, 0.002229);
LiquidCrystal_I2C lcd(0x27,16,2);

void setup() {

  Serial.begin(9600);
  hx.set_offset(-9635);
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  lcd.begin(16,2);

}
void loop() {
  if(digitalRead(0) == LOW){
    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("tare recieved");
    hx.tare();
  }

  double sum = 0;
  for (int i = 0; i < 10; i++) {
    sum += hx.bias_read();
    if(sum < 0) {
      sum = 0.00;
    }

  }
  sum = sum/10;
  lcd.clear();
  lcd.setCursor(4,0);
  lcd.print("Weight");
  lcd.setCursor(5, 1);
  lcd.print(sum);
  lcd.print("g");
  Serial.println(sum);
  delay(10);
 }

Here is an example output as seen on the Arduino Serial Monitor:

150.34
150.39
150.40
150.37
150.38

The Problem is when the data reaches node-serialport the value is split up on multiple lines.

 comport.on("data", function (data) {
    console.log(data.toString());
 }

When i log the data... it comes back like this:

1
50.4
5
150.
49
15
0.47
150.
48
15
0.45

Is there anyway to have Arduino only send the data if it is the full value and not the split up values?

As explained in Majenko’s comment, the serial link is not packetized: it
transmits individual bytes and nothing else. If you need to convey a
notion of “data packet”, or “full message”, you will have to devise a
way to signal the message boundaries. This is called message “framing”.

Your Arduino is sending ASCII data. In this case, the most common way to
frame messages is linewise: each message is a single line, and each line
is terminated by an “end of line” sequence. The standard end of line
sequences are CR (carriage return, i.e. 0x0d or '\r'), LF (line
feed, i.e. 0x0a or '\n'), and the pair CRLF (CR followed by LF, or
"\r\n").

Actually you are already doing that: you are using Serial.println(),
and this method automatically appends CRLF at the end of whatever it
prints. So now you just have to parse that at the other end: you put
all the incoming characters into a buffer until you see that incoming
CRLF. Then you know you have a full line, which you can report as an
entire message.

This procedure is very common and there is a standard Node.js module for
it. It once was part of the serialport module, but it seems to have
split into a separate module. It is called parser-readline, and you
would use it like this:

const Readline = require("parser-readline"),
      parser = comport.pipe(new Readline({ delimiter: "\r\n" }));

parser.on("data", data => console.log(data.toString()));

C.f. the documentation of
ReadLineParser.


Linked List based question I am making a Smart Cart using RFID. The user will
have a RFID card. As soon as he swipes the card on
the RFID Reader it will identify the user and will create
a linked list for that particular user. The linked list will
contain the unique Rfid based Ids of the items purchased by the user. In my code
the problem is that after the detection of the user it is
not creating any linked list for the items/it is not detecting the items bought by the user. Both the user and items are identified by their unique ids (ie RFID tags).It is detecting the user but once the user is being detected it is not mapping the items bought with that user.

the code for the same is :

int count = 0; // count = 0
int i;
char input[12];                                   // character array of size 12
boolean flag = 0;
// flag =0

boolean comparetag(char x[12], char bb[12]) {
  boolean ff = false;
  int fg = 0;
  for (int cc = 0; cc < 12; cc++) {
    if (x[cc] == bb[cc]) {
      fg++;
    }
  }
  if (fg == 12) {
    ff = true;
  }
  return ff;
}

struct Node {
  char x[12];
  struct Node *next;
};

struct Node* X;
struct Node* point;

void printList(struct Node *n) {
  while (n != NULL) {
    Serial.print(n->x);
    n = n->next;
  }
}

struct Node* Shopping(char[]) {

  Serial.print(input);
  // Print RFID tag number
  Serial.print("Welcome User");
  Serial.println();

  Serial.print("Start Shopping ");

  struct Node* head = NULL;
  head = (struct Node*) malloc(sizeof(struct Node));

  return head;

}

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

void loop() {

  if (flag == 0) {
    if (Serial.available()) {
      count = 0;
      while (Serial.available() && count < 12) // Read 12 characters and store them in input array
      {
        input[count] = Serial.read();
        count++;
        delay(5);
      }

      if (comparetag(input, "1B006AFA9F14")) {
        flag = 1;

        point, X = Shopping(input);
      } else {
        Serial.println("not Registered User");
      }
    }
  } else {
    int c = 0;
    if (Serial.available()) {
      while (Serial.available() && c < 12) // Read 12 characters and store them in input array
      {
        Serial.print("Taking Input");
        X->x[c] = Serial.read();
        c++;
        delay(5);
      }
      struct Node* second = NULL;
      second = (struct Node*) malloc(sizeof(struct Node));
      second = NULL;

      X->next = second;
      X = second;

    }
  }
  printList(point);
}

I don't see any code for making new nodes or linking them into a list. A linked-list needs a root (a known variable that points to the first member of the list); a way to make or acquire new nodes and link them onto the list as the number of items grows; and a way to unlink a node and "discard" it - return its memory - once it is no longer useful.

I'll offer a couple of suggestions for linked-lists, especially in processors like the Uno with limited memory:

Don't be tempted to use malloc() and free() or new and delete for a system that must run continuously. Allocating and deallocating small pieces of memory, especially when interspersed with other allocation & deallocations, will lead to fragmentation of the heap (that portion of memory used for allocating memory at run-time). The result is that the heap will end up with lots of separate pieces of memory that are free but too small for other allocation requests, so the heap has to acquire more memory to satisfy the larger allocations. It does this by reducing the stack space! Eventually the stack will grow into the heap space, and the program will fail.My solution is to define a global array of node structs; enough of them for the program's greatest conceivable need, plus a few more for safety; link them into a list of free nodes; and give new nodes to the application by deallocating one from the free list. A You need link() and unlink() functions for a linked-list anyway, so it takes very little more code to do this.
Because we're talking about memory limited processors, If I don't need more than 255 nodes, I link with array indices instead of pointers, saving one byte per node. This costs a little bit more code to index into an array than to de-reference a pointer but compilers have gotten pretty smart about minimizing even that overhead.


Optimization Teensy 3.6 Arduino IDE fast I/O Multiplexing Led Matirx I'm currently working on a 10x10 LED Matrix which is controlled by 5 Shift registers using multiplexing. I've the problem that the Teensy 3.6 is too fast/slow.

One part of my code is the Shiftout function. If I use normal digitalWrite() its working perfectly fine, but its slow. If I use digitalWirteFast() or something like GPIOA_PSOR = (1 << 12); the matrix starts to display crap.

Teensy 3.6 180MHz

74HC595 shift register

SS8050 BJT's to protect the whole thing

scematic here: circuits.io

void ShiftOut(uint8_t myDataOut) {
// This shifts 8 bits out lngMsLoopstartB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
uint8_t i = 0;
//clear everything out just in case to
//prepare shift register for bit shifting

//digitalWriteFast(dataPin, LOW);//Data aus
GPIOA_PCOR = (1 << 12); // Datapin low

//digitalWriteFast(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//for each bit in the uint8_t myDataOut
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i = 0; i <= 7; i++)  {

//digitalWrite(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1 << i) ) {
  //digitalWriteFast(dataPin, HIGH);//Data an
  GPIOA_PSOR = (1 << 12); // Datapin high

} else {
  digitalWrite(dataPin, LOW);//Data aus
  //GPIOA_PCOR = (1 << 12); // Datapin low
}

//register shifts bits on upstroke of clock pin
digitalWrite(clockPin, HIGH);//Clock an
//GPIOA_PSOR = (1 << 13); // Clockpin high

digitalWrite(clockPin, LOW);//Clock aus
//GPIOA_PCOR = (1 << 13); // Clockpin low

//zero the data pin after shift to prevent bleed through
digitalWrite(dataPin, LOW);//Data aus
//GPIOA_PCOR = (1 << 12); // Datapin low
}
}

if somebody needs the complete code, please let me know!

How it looks like when I use GPIO 2.Picture how it should look like: Imgur

Problem

The thing I want is to make the whole multiplexing faster. Currently 1 Time all 10 rows takes about 480 microseconds. Then add a 4 Bit Bit angle modulation (480*16) its: 7680 microseconds (7.68ms). So if you now divide 1000 by 7.68 = 130,2 Hz refresh rate. Thats ok and Im fine with that.

The main problem is that I want 8 bit. so same thing again 480 * 256 = 112880 (112,88ms). So now divide 1000 by 112,88 = 8,86 Hz refresh rate. That looks really bad. I would like to get about 60-100.

The Problem is not the big LED array or setting each value every frame new. This only takes 80 microseconds.

I have also written a driver for LED matrices based on shift registers. To quickly shift out the bits to the shift registers for each scan update, I used SPI. On the Teensy 3.6, this works quite well.

But what I suspect your issue is (since you didn't post your whole code) is that you are calculating each of the bit updates in between each shifting out. If you are doing this, I suggest that you don't. Instead, buffer the bit calculations, and use a timer interrupt to shift out each row update. This approach takes advantage of the fact that you are likely to recalculate the bit layout for the matrix overall at a much slower frequency than the need to send our row updates to effect the multiplexing of the LED rows. I explain this design in much more detail in this Instructable.

Using the interrupt allows you to cleanly do the heavy lifting of recalculating the bit layout into a buffer while the row updates will consistently go out, creating a very stable image. It's the closest thing you'd to true threading on Arduino-like platforms. Also, this approach will allow a much smaller base interval for row updates. In my code, I use a 5 µs update interval, that gets modulated in order to be able to create a 12-bit color palette. I probably could get a richer color depth on the Teensy 3.6 given it's clock speed, but I wanted my code to be universal, so I am able to get the 12-bit color on 8-bit AVR micro controllers too (e.g., Arduino Mega).

You can study (or use) my code at this GitHub repository, and read more about my LED matrices (hardware and software) at my website.


Using EEPROM Anything in loop() I'm trying to make a programm for Arduino Bluno Beetle, that saves a string in the loop. Here is my code:

#include <EEPROM.h>
#include <EEPROMAnything.h>
struct config_t{
   String lastThing;
    } savedValues;
void setup(){
   EEPROM_readAnything(ADDR, savedValues);
   Serial.println(lastThing);
}
String readString="asd";
void loop() {
 //...
 lastThing=readString;
 EEPROM_writeAnything(ADDR, savedValues);
}

(The EEPROMAnything.h can be found here: https://playground.arduino.cc/Code/EEPROMWriteAnything?action=sourceblock&num=1)

The code works until the 11th line. It gives there the following error:

'lastThing' was not declared in this scope

Does anybody know how to fix this problem?

The proper syntax for referring to a struct member is [structName].[memberName]. Changing lastThing in lines 8 & 13 to savedValues.lastThing fixes the "undeclared" error.


Difference between Ciao REST server and Ciao REST connector and when to use each or the other I'm reading the Ciao library and can't make out the difference between Ciao REST server and Ciao REST connector.

When is the connector suitable and at what point do I need the server?

This is a graphic of what im thinking to do:

I don't know about "Ciao" but generally a rest server answers requests from a client that is connecting via a rest connector.
You client will use POST, GET, PUT, etc. to ask the server to provide a service.  This could be as simple as "GET .\index.htm" or more likely posting information to be stored in a database.

The server will sit waiting for these requests and will have handling routines for each specific request and might supply a response.


connecting lv maxsonar ez arduino I am not 100% sure this question relevant here , but question is I have lv maxsonar ez which need 5v. I am powering my uno with  9v battery. And I have few other sensors also connected to 3.3v. But I have neopixel 3 meter LED which is powering with external power source which is 5v 4 amp. So My question is shall I connect my sonar sensor to the external power or keep with my uno 5v power ?

Thanks

I think the question is still relevant.
You should keep the maxsonar powered from Uno power if you don't want to burn it. Even if you use 9v Battery, Arduino Uno have internal 5v regulator. So it would be safer to supply the sensor from Arduino 5V (not Vin) pin.


Use an Arduino Mega in a incubator (high humidity) I wonder whether it is possible to use an Arduino Mega in a cell incubator.

In the incubator there is a temperature of 37°C, 5% CO2 in the atmosphere and a high relative humidity of around 95% - 98%. I think the temperature (specs of ATmega2560, temperature range: -40 °C to 85 °C) and the CO2 is no problem.

But I am concerned the condensation due to the high humidity will cause damage.

One mitigation could be, that I first pre-warm the Arduino Mega so it doesn't condensate.

(There is a possibility that I don't put the Arduino in the incubator at all, but it would be easier if I could).

"-40 °C to 85 °C" for the processor, yes, for the other parts, who knows?

The board doesn't get that hot unless you are powering from like a 12V source, and then it's just the regulator that gets hot.

You could a spray-on conformal coat, Mouser.com carries them. Insert any wires into the headers you will use and cover any headers you may want to use before you spray, if you get coating down into the female headers you may have poor contact later on.

The ziplock bag idea sounds like a good start as a start, put some silicon along the seal to fill the holes where the zipper won't close right next to the wires.


Serial.write() prints a variable twice I have this code:

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

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

char clat[11];
char clng[11];

void loop()
{

        bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c))
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
}

Now when all is done, the clng value is printed twice in the serial monitor.
The value i get is in this format:

27.275869  15.151013
  15.151013

As you can see, clng is printed twice. Any ideas why is that?

The width parameter to dtostrf() is the width of the resulting string NOT including the null terminator. So you are overflowing the array.

Change:

char clat[11];
char clng[11];

to

char clat[12];
char clng[12];

and it should work.


Switch controlled power saving esp8266 I'm trying to build a door sensor with the esp8266. I want it to be battery powered and use deepSleep for power saving. I'm going to use a normally closed reed switch between D0 (GPIO16) and RST.

I set the deepsleep to be for about 30 seconds (time to close the door). After that GPIO16 goes LOW and when the door is opened it will close the circuit and connect GPIO16 to RST and reboot the board.

Since the Red onboard LED is connected to GPIO16 and is activated on LOW as well, at the end of deepsleep it turns on.

2 Questions

Is this setup a good approach to powersaving on the esp8266? My concern is how much power setting GPIO16 to LOW uses.
Is it save to just rip off the LED from the board? I figure it being on would be the biggest drain of battery power. I already did some googling and it SEEMS safe? But I trust stack over forums.

Following @dandavis's advice. I will connect the switch between the power source and the board, get rid of the LED, and use ESPNOW for communication! Thanks for the help.


Analog Reference and Power Voltage On the Arduino website it states that the analog pins read voltages from 0 to 5 volts (default) and return a value from 0 to 1023. One can also set the range with analogReference(). However, this is probably assuming the Arduino is running at 5 volts. If one powers the board with, say 4 volts, will the analog reference still be 5 volts default, or changed to the input voltage of 4 volts?

Your suspicions are correct. Calling analogReference() with a value of DEFAULT sets the ADC reference to the voltage at AVCC which at least on the Uno R3 is tied directly to VCC and hence has the same voltage as whatever you're supplying there.


Would someone provide an example of extracting data from a char array? I have tried so many things now that I am just confused.
I am not understanding the way char arrays work.
I can't get the date and names extracted.  And when I use just strings, I jam up the memory.

Below was my last attempt, before asking the question.
while (f.available()) {
  String line = f.readStringUntil('\n');

  if (line.startsWith("04-23")) {
    currentDay = 1;
    int str_len = line.length() + 1;
    char char_array[str_len];
    line.toCharArray(char_array, str_len);
    Serial.println(char_array);                 // Everything works to here
    for (int j = 0; j < 2; j++) {
      b += char_array[j];
    }
    bMth = b.toInt (); // This should be an int of the birth month in this case: 04
  }
}

Var:
format: MM-DD-YYYY,Name  // this is inside the file
line = "04-23-2020,James"  // This is the output from - Serial.println(char_array);

What I am trying to do is

Extract the month/day so that I can compare it to today.
The year so I can calculate the age.
The name to display on OLED.
Everything else seems to work, but I can't get my head
wrapped around the char array access.

To do this in PowerShell I would do:
$line = "04-23-2020,James"

$dob = ($line.Split(","))[0]
$bMth = ($dob.Split("-"))[0] # This is not used in this example
$bDy = ($dob.Split("-"))[1]  # This is not used in this example
$bYr = ($dob.Split("-"))[2]

$age = $(get-date -UFormat %Y) - $bYr

Clear-Host
Write-Host (@'
Name: {0}
Age:  {1}

'@ -f $($line.Split(","))[1], $age)

In Python:
import datetime as dt

line = "04-23-2020,James"

dob = (line.split(',')[0])
bMth = (dob.split("-"))[0] # This is not used in this example
bDy = (dob.split("-"))[1]  # This is not used in this example
bYr = (dob.split("-"))[2]

age = int(dt.datetime.now().year) - int(bYr)

print('Name: ',(line.split(',')[1]))
print('Age: ', age)

When working with Arduino, cplusplus.com is your friend. Scroll down and look on the left side under (string.h). Lot's of great char functions there. Other useful functions such as iota() - cplusplus.com.
Here's one way to accomplish the parsing of the input data.
// Sketch uses 2064 bytes (6%) of program storage space.
// Global variables use 323 bytes (15%) of dynamic memory.
// Arduino IDE 1.8.9.
char line[] = "04-23-2020,James";
char Name[100];
unsigned int Month, Day, Year;

// Make an attempt to validate the input data.
byte Counter = 0;

void setup(){

  Serial.begin(9600);

  char * pch = strtok(line, "-,");

  while(pch != NULL){
    if(Counter == 0){Month = atoi(pch);}
    else if(Counter == 1){Day = atoi(pch);}
    else if(Counter == 2){Year = atoi(pch);}
    else if(Counter == 3){strcpy(Name, pch);}
    pch = strtok(NULL, "-,");
    Counter += 1;
  }

  // Print out the data.
  if(Counter == 4){
    Serial.println(Month);
    Serial.println(Day);
    Serial.println(Year);
    Serial.println(Name);
  }
  else{
    Serial.println("Error");
  }

}

void loop(){}


Is it possible to change and save I2C address programatically? I want to drive 3 i2c devices on a single i2c line. Is it possible to achieve this without using A0,A1,A2 pins?
I thought the address of i2c devices should be programmatically changeable.
2 mcp23017 and si5351 chips I use.

As far as I can see in the datasheets of the 2 mentioned chips, they don't provide a way to change the address programmatically over the I2C bus. They only have address pins, which have to be tied to Vcc or ground for setting the address. Most ready to use boards with such chips already have pullup or pulldown resistors for this. If you use the blank chips, you absolutely need to tie the address pins to a fixed value. Normally this is done semi-permanently.
You can also connect the address pins to Arduino output pins to dynamically change the addresses.
There is no other way to change the addresses but to use the address pins.


Arduino random LED on I have a project which has two options
No. 1 Randomly turn on one LED from a group of 6 LED (Relay Board)
No.2 randomly turn on one LED from a group of 2 LED (Relay Board)
The selection of the desired option happens with a switch.

I found this code online which is just perfect for 6 LED but I don't know how to add the selection of the options in it, how to do it?

int timeShowRandom = 3000;
int timeShowDecision = 6000;
int timeBlink = 100;
int buttonPin = 2;
int buttonPress = false;
int randomNumber;
int previousNo = 0;
int timePassed = 0;

void setup() {
  // Set button pin
  pinMode(buttonPin, INPUT);
  // Set output pins
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
}

void getRandomNo() {
 int rand = random(7,13);
  if (rand == previousNo) {
   getRandomNo();
  } else {
    randomNumber = rand;
    previousNo = randomNumber;
  }
}

void loop() {
 if (digitalRead(buttonPin) == HIGH && buttonPress == false ) {
     buttonPress = true;
  } if (buttonPress == true && timePassed <= timeShowRandom) {
    getRandomNo(); // Get random pin number
    digitalWrite(randomNumber, LOW);
    delay(timeBlink);
    digitalWrite(randomNumber, HIGH);
    delay(timeBlink);
   timePassed = timePassed + (timeBlink * 2);
  } else if(buttonPress == true) {
    digitalWrite(random(7,13), LOW); // Set random pin on
    delay(timeShowDecision); // For x seconds
    buttonPress = false; // Set button to be enabled again
    timePassed = 0;
  }
  else {
    // Reset all output pins
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(7, HIGH);
  }
}

Various suggestions:

Create 2 different arrays of pin numbers: 1 for the first group of relay pins, and the 2nd for the second group of relay pins:

byte firstRelayPins[] = [7, 8, 9, 10, 11, 12];
byte secondRelayPins[] = [13, 14]; //Replace values with your relay pins

Write a function that returns a random index from one or the other of the arrays based on a bool:

byte randomPin(bool useSecondArray) {
    int max;
    int index;
    if useSecondArray {
       return secondRelayPins[random(sizeof(secondRelayPins))]; //Fetch random pin from array
    } else {
       return firstRelayPins[random(sizeof(firstRelayPins))]; //Fetch random pin from array
    }
}

Based on the state of your switch, set useSecondArray when you call that function to determine which relay's pin you turn on.

Use the returned value to set the desired relay pin.

In your "turn everything off" code, use the arrays of index pins rather than hard-coded indexes.

You should also refactor your code to use millis() rather than using delay(). (Search on "Arduino blink without delay" for guidance on how to do that.)

Note that this is a rough outline of what to do. The code above will likely need to be adjusted to fit your needs. Don't expect to be able to copy/paste it into your project.


Read frequency of input in digital pins This is a somewhat theoretical question:
Let's say I have some sensor that sends digital signals to one of Arduino's digital ports.
Now, I don't know the frequency it sends those signals in.
For example, the frequency of the sensor output could be 100Hz, so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one), but it could just as well be 200Hz.
Would Arduino be able to faithfully read the digital signal regardless of its frequency? Or is there a conventional frequency that digital devices usually use for output?
Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs?
For: (1 0 1 0 0 1...) wouldn't it see: (1 1 0) - that is skip every other input because it's sampling rate would be too slow by half?
Thanks kindly for your help..

100 Hz is pretty trivial. See my page about timers.

This sketch can detect frequencies up to about 5 MHz:

// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

  Or is there a conventional frequency that digital devices usually use for output?

No.

  Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs? For: (1 0 1 0 0 1...)

No.

Why would it "expect" a frequency? It isn't a person expecting a chocolate cake on its birthday.

  So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully?

I'm not quite sure what you mean by "read all the voltage signals" which seems to imply you want to measure the voltage.

  so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one)

But then you say:

  let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

The voltage levels for 0 and 1 are documented in the datasheet. For the Atmega328P for most pins they are as follows:

You can see that if Vcc is 2.4V or above then LOW is -0.5V to 0.3 * Vcc, which if Vcc is 5V then a LOW is -0.5 to 1.5V.

Similarly a HIGH is 0.6V * Vcc to Vcc + 0.5, so if Vcc is 5V then a HIGH is 3V to 5.5V.

In between 1.5V and 3V then the digital status would be undefined.

So, if your LOW and HIGH are in those voltage ranges, yes you can detect the frequency of the signal.

I'm not sure about the bit where you said "keeps the old voltage if the next signal is the same as the previous one". That seems to imply that if the signals stay the same (eg. for a second) then the voltage won't change at all, and thus the frequency will be zero.


Ethernet shield compatibility Does anyone know if there is an Ethernet shield is compatible with the Arduino Ethernet shield (R3)? The R3 does not seem to be in production anymore and I need a replacement shield. Found some from Velleman, or maybe Ethernet Shield 2?

Arduino Ethernet Shield R3
Arduino Ethernet Shield 2
Velleman Ethernet Shield

No, it is not compatible.  It uses the ENC28J60 chip from Microchip, whereas the others all use the W5100 Wiznet chip. A very different chip.

You can use it if you refactor all your code to use the Ethercard library instead of the Ethernet library.

There are cheap Chinese (or other far east) clones of the Ethernet Shields, that use the W5100 (or a counterfeit copy) that people have varying amounts of luck with if you really need W5100 compatibility. I have one, but have had problems with it starting up properly sometimes and needs a bit of a kick with the reset button.


Testing an oscilloscope with my Arduino I bought a very old oscilloscope and although it works, I have my doubts about refreshing the screen (the electron beam fades away very slowly or is not showing up consistently across the screen).

I tested a bit with digitalWrite and anlogWrite, but this only sends either 0 or 5V out. Is there a way to make a preferably sine or triangle wave of 0 to 5V or -5 to +5V... I guess the Arduino should be capable of it, but so far I only get 0V or 5V out, nothing in between.

According to lesson 8 I should get a variable voltage of 0-5V on a pin with analogWrite, but all I get is 0 or 5V.

For what I see:

PWM gives with analogWrite a pulse signal of 0V or 5V with a duty cycle.
non PWM pins give either 0V or 5V (analogWrite of 0-127 appr: 0V, >127: 5V).

You can convert the PWM output of analogWrite() into an (approximate) analog voltage by adding a low-pass filter. That is, a resistor in series followed by a capacitor to ground.

The values to choose depend on the frequency response you want.

RC Filter Calculator (second section).

For anything more complex or accurate you will need a DAC. I often use the MCP4822 SPI DAC chip.


Liquid Crystal LCD and serial monitor not playing well together On my Arduino Uno, when I'm not using the serial everything seems in order:
#include <LiquidCrystal.h>

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup()
{
    // put your setup code here, to run once:
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("Prints");
    lcd.setCursor(0, 1);
    lcd.print("Well");
}

void loop()
{
    delay(1000);
}

However the moment I open the serial port with:
Serial.begin(9600);

The problem starts.
Clearing the LCD does not clear it but prints a character with 4 horizontal lines. Trying to move the cursor will print a different  unrecognisable character. Sending things to the Arduino via the Serial port prints gibberish on the LCD.

Any idea why? Is there a way to work with the LCD and the serial port simultaneously? I require the serial port in order to control the Arduino from NodeJS.
#include <LiquidCrystal.h>

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup()
{
    // put your setup code here, to run once:
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("Prints");
    lcd.setCursor(0, 1);
    lcd.print("Well");

    Serial.begin(9600);

    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for Native USB only
    }
}

void loop()
{
    lcd.clear(); // This will print 4 horizontal lines character instead of clearing
    delay(500);
}

On an UNO pin 1 is one of the hardware serial pins.  You can’t use pin 0 or pin 1 for other things if you are using Serial in your code.
Even if you aren’t using Serial, you use pins 0 and 1 when uploading your code and having other things connected can mess up that process.  It’s generally advisable to stay away from pins 0 and 1 unless you absolutely must use them.


I need to build a char array from two integers My C is rusty, so please forgive this simple problem.

This line works:

Tft.drawString("Test",200,200,2,WHITE);

But, this has compile errors:

String yStr = "Test";
Tft.drawString(yStr,200,200,2,WHITE);

The function in the library:

void drawString(char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);

The error is "no known conversion for argument 1 from 'String' to 'char*'".

Conclusion - I need a character array. Here's what I am trying to accomplish.

I have two integers that I would like to display on my Tft screen. For example, 225 and 250 to be displayed as "225,250".

I haven't figured out a way to build the char array for the drawString() function.

Assistance would be appreciated.

Thanks for the quick reply Ignacio.
I tried that, but the compiler still doesn't like it.

Here's how I built the string:

string stringXY ;
stringXY += xStr;
stringXY += ",";
stringXY += yStr;
Tft.drawString(stringXY.c_str(),200,200,2,RED);

Error: invalid conversion from 'const char*' to 'char*' [-fpermissive]

I am apparently using c_str() wrong?

Put it in a String and then use the c_str() method to get the associated char*.


Different dht21 readings on different arduinos First of all, let me begin by saying that I'm still pretty much a rookie.

I have a project with a dht21, an LDR and an ultrasonic distance sensor. I have 3 different arduino uno boards, namely:

A (supposedly) original arduino uno r3.
A chinese nhduino, arduino uno r3 clone.
And this one, sitting on top of this.

I've been playing around with the three boards for the last couple of months, testing a variety of sensors and having the same results with the three boards, as expected. But then, with the aforementioned setup, I'm getting very different readings on the DHT21 sensor. If I use the "regular" (first two) arduinos plugged in my laptop, the readings are consistent. But if I use the banana pi(duino), I get the temperature reading correct, but getting weird humidity readings... pretty most of the time a 5% humidity value.

Everything tested on the same room, same sensors and same protoboard. No external power supply.

I'm totally clueless here, any ideas of what could be the problem?

Thanks.

Problem solved. Using a ywrobot breadboard PSU and now it works. I haven't tested current in the circuit but looks like it was just too low. I wish I'd had datasheet for the board to look at. In a language different from chinese would have been ok, I guess.


Adafruit Feather 32u4 FONA KEY Pin I received a Adafruit Feather 32u4 FONA as a gift and have read the great, comprehensive document Adafruit put have put together surrounding pinouts, examples etc for the board. I am having issue understanding the section on the KEY pin, I understand that it is used to put the cellular module to sleep, but in order to do this it is mentioned to “cut the trace and wire it to a micro controller pin”. Does this mean that in order to utilize the on/off functionality of the SIM module I have to slightly butcher my new shiny board instead of using the pin directly?

Yes, you will need to physically cut the trace to use the on/off feature. This is common on development boards. It could be done with a jumper but that would add cost and/or require a larger board.

You will see on the back of the board there are 2 large pads connected by a thin trace. You can use an exacto knife to cut the trace. To repair the cut you use a blob of solder to bridge the gap between the pads.


Do you need an ESC to run this brushless DC motor with Arduino Uno? This is the motor:

https://www.aliexpress.com/item/Wholesale-JGA25-2418-8-5-1977-rpm-Electric-Motors-Brushless-Motor-High-Torque-Speed-Controlled-DC/32360228129.html

I'm hooking it up to the arduino as described and giving the PWM outputpin analogWrite functions, but it's not working.

No. It has an ESC built in.

You just provide power and a PWM signal, and optionally a direction signal.

To test:

Connect red to +12V.
Connect black to 12V GND and to Arduino GND
Connect white to D5
analogWrite(5, 128);


Potentiometer reading out letters My potentiometer reads out t's or u's in my serial.
I believe that my potentiometer is wired correctly.
What am I missing?
Here is my code:

#include <VarSpeedServo.h>

VarSpeedServo servo;
const byte buttonLeft = 2;
const byte buttonRight = 3;
const int led = 7;
const int potentioPin = A0;
int potentioVal = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(11);

  // PIN MODES
  pinMode(buttonLeft, INPUT);
  pinMode(buttonRight, INPUT);
  pinMode(led, OUTPUT);

  // INTERRUPT
  attachInterrupt(digitalPinToInterrupt(buttonLeft), turnServo, FALLING);
}

void loop() {
  int stateBtnLeft = digitalRead(buttonLeft);
  int stateBtnRight = digitalRead(buttonRight);

  if(stateBtnLeft == 0 && stateBtnRight == 0){
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
}

void turnServo(){
  Serial.println("Button was pushed");
  potentioVal = analogRead(0);
  Serial.write("Servo moving with speed ");
  Serial.write(potentioVal);
  Serial.println("");
  //servo.write(180, potentioVal, true);
  //Serial.write("Reached position of motor");
  //lightLed();
}

void lightLed(){
  digitalWrite(led, HIGH);
  delay(2000);
  digitalWrite(led, LOW);
}

You need to use Serial.print instead of Serial.write.


Arduino is freezing after 10-15 minutes I am having a problem with my Arduino freezing after a small amount of time. I'm using an RTC DS1307 breakout to keep track of the time and display the time on an LCD. It displays hours, minutes and seconds (updated every second).

Then I have 25V which is supplied by a transformer and connected to a set of LEDs through a CAT4101 constant-current sink LED driver. The Arduino board is powered by a 2amp USB transformer.

At a set time, the timer should set off the process to dim the lights.

Everything is working well if I set the lights to dim within a few minutes. However, if I leave the board on for more than 10-15 minutes then everything seems to freeze (i.e. the time on the LCD stops being updated and stays stuck at the moment it froze).

I originally thought it could have been something to do with my code. But I then skimmed everything down to the bare essential and just uploaded the code necessary to update the time on the LCD. And even in this case it freezes.

The only way I managed to avoid things freezing was to disconnect the CAT4101 pin 1 from Arduino's PWM and disconnect pin 2 from Arduino's 5V.

What could be causing this issue?

CAT4101

pin 1 = connected to Arduino PWM
pin 2 = connected to +5v
pin 3 = connected to ground
pin 4 = connected to ground with 2kOhm resistor
pin 5 = connected to LED cathode

UPDATE

Code below (I have stripped down the code by removing any additional functions and leaving only the bare code which is leading the application to crash).

#include <Wire.h>
#include <RTClib.h>
#include <LiquidCrystal.h>

RTC_DS1307 rtc;
DateTime now;
LiquidCrystal lcd(7, 8, 9, 10, 11 , 12);

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

 if (!rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(__DATE__, __TIME__)); // time = hh:mm:ss format, e.g. 06:01:01
  }

  lcd.clear();
}

void loop() {
  now = rtc.now();
  updateDisplay();
}

void updateDisplay(){
 int h = now.hour(); // Get the hours right now and store them in an integer called h
 int m = now.minute(); // Get the minutes right now and store them in an integer called m
 int s = now.second(); // Get the seconds right now and store them in an integer called s

 lcd.setCursor(0, 0); // Set the cursor at the column zero, upper row...
 lcd.print(" The time is: "); // ...with spaces to clear characters from setting alarm.
 lcd.setCursor(4, 1); // Move the cursor to column four, lower row
 if (h<10){   // Add a zero, if necessary, as above
  lcd.print(0);
 }
 lcd.print(h);   // Display the current hour
 lcd.setCursor(6, 1); // Move to the next column
 lcd.print(":");  // And print the colon
 lcd.setCursor(7, 1); // Move to the next column
 if (m<10){   // Add a zero, if necessary, as above
  lcd.print(0);
 }
 lcd.print(m);   // Display the current minute
 lcd.setCursor(9, 1); // Move to the next column
 lcd.print(":");  // And print the colon
 lcd.setCursor(10, 1); // Move to the next column
 if (s<10){   // Add a zero, if necessary, as above
  lcd.print(0);
 }
 lcd.print(s);   // Display the current second
}

I would add a delay(100); to the bottom of your loop()

I'm betting even odds that solves it.


Manual Arduino Due Installation Not sure if this is the right place to post this.

I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but it just says there is an error downloading the files.

Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

UPDATE

When I open the Boards Manager, I get :

Error downloading http://downloads.arduino.cc/packages/package_index.json

and when I try to install Due support, I get :

Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2

I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.

I have manually downloaded sam-1.6.4.tar.bz2 and extracted the contents to C:\Arduino\arduino-1.6.5\hardware\arduino\sam (I had to manually create the sam folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :

Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified

Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.

UPDATE 2

Question has been answered:
https://github.com/arduino/Arduino/issues/3358

Many thanks to Federico Fissore!

I had the same problem described above.
Error downloading http://downloads.arduino.cc/packages/package_index.json

I solved the problem, just deleting the temporary file: "package_index.json.tmp"


How do I specify a particular pin to use as output for the Print class? all.

I'm attempting to write a class that inherits from the Print class.  I only need serial output.

However, I'm having difficulty locating any reference on how to specify which pin on the ATMega my class will use as output of the write(...) functions.

How does the Print class know where to send output to ??

Thanks in advance.

You need to do far more than just "specify a pin". You need to write the software that transmits data through that pin in your chosen format.

You cannot send data through a pin. You can only set a pin HIGH or set a pin LOW. It is the sequence (and most importantly the timing) of setting a pin HIGH and LOW that constitutes sending data.

So you have to write the software that sets the pin HIGH and LOW in the right way and at the right time.

Fortunately sending is far simpler than receiving, as you can see if you look at the source code to SoftwareSerial.

Specifying the pin itself though is simple:

class MyClass : public Print {
    private:
        uint8_t _pin;

    public:
        MyClass(uint8_t pin);
        size_t write(uint8_t data);
};

MyClass::MyClass(uint8_t pin) {
    _pin = pin;
}

size_t MyClass::write(uint8_t data) {
    // In here you do whatever you have to in order
    // to manipulate _pin in the right way to send your data.

    // Don't forget to return the number of bytes written (there
    // is only one, so either 1 for "it got sent" or 0 for "it
    // didn't get sent".
    return 1;
}

It can be quite useful to have a begin() function for setting things up, such as configuring the right pinMode() for _pin, and maybe setting a baud rate like Serial does (although for simplicity you may choose to just have a single fixed baud rate, which means you can pre-calculate delay loops etc).


Best way to obtain angular velocity from a 9 DoF sensor I have been using a BNO055 sensor (9° dof IMU) for a project which will use angular velocity to the mouse cursor on screen.
So far, I have gotten quaternion output from the sensor and been able to convert it to angular velocity in a couple of ways. The first, multiplying 1 quaternion sample by its conjugate in the next sample, and then converting the quaternion Delta in Euler angles. The second, converting from quaternions to Euler angles and then finding the change in those between samples.
Both methods result in angular velocity measurement, but each with their advantages and disadvantages. E.g. Quaternion Delta between samples does not suffer from gimbal lock, but it's difficult to isolate y-axis from z-axis movement.
I know that you can ask the sensor for angular velocity data directly, but apparently that's less precise due to the Gyro drift and it's relative orientation only, which is why I opted to work with quaternions.
Is there a better way to go about this?
My code included below for reference with the 2 approaches in case it's helpful/interesting. It uses the Adafruit repository, doing the standard stuff in setup function and then calling the function below in loop.
void quaternion_Delta () {
  // Quaternion data 1
  imu::Quaternion quat = bno.getQuat();
  // Euler 1
  imu::Vector<3> euler_one = quat.toEuler();
  //delay between samples
  delay(BNO055_SAMPLERATE_DELAY_MS);
  // Quaternion data 2
  imu::Quaternion quat_two = bno.getQuat();
  // Euler 2
  imu::Vector<3> euler_two = quat_two.toEuler();
  // quaternion comparison
  imu::Quaternion quatDelta = quat_two * quat.conjugate ();
  imu::Vector<3> euler = quatDelta.toEuler();
  Serial.print(" X: ");
  Serial.print(euler.x()*radius_to_degrees, 2);
  Serial.print(" Y: ");
  Serial.print(euler.y()*radius_to_degrees, 2);
  Serial.print(" Z: ");
  Serial.print(euler.z()*radius_to_degrees, 2);
  Serial.print("\t\t");
  // Euler comparison
  imu::Vector<3> euler_comparison = euler_two - euler_one;
  Serial.print(" x: ");
  Serial.print(euler_comparison.x()*radius_to_degrees, 2);
  Serial.print(" y: ");
  Serial.print(euler_comparison.y()*radius_to_degrees, 2);
  Serial.print(" z: ");
  Serial.print(euler_comparison.z()*radius_to_degrees, 2);
  Serial.print("\n");
  }

Consider building on Sebastian Madgwick's PhD IMU research.  A GitHub Arduino project based on Madgwick's work can be found here.


Is there a way to get about a 10ns Timer resolution from an AVR CPU? I have an 8Mhz ATM32u4 that is able to read external pulse inputs at 125ns ticks using InputCapture3 (PC7) on its 16-bit timer.  Is there a magical way (bitbanging?) to get around 10ns tick resolution to read pulses?  Edit:  like ADC conversions to allow 16-bit systems 24-bit accuracy via creative coding, etc.
If there is no magic, I should use a faster CPU?  I am limited in coding pretty much to AVR type CPUs in the Arduino IDE.  So wondering what AVR CPU would be fast enough for a 10ns tick that is incorporated already into like a Nano, UNO, etc?
Unless I am able to use Pin Interrupts that are able to read at 10ns intervals, then I could use ARM CPU types with Arduino IDE code which does not require me to dive deep into register level language.
Or, is there a stand-alone analog or digital IC that is able to read at 10ns intervals pulses that an Arduino can process?
Thank you.
Edit:  I would need to measure the length of a one-shot pulse only, not a continuous or changing signal. Down to 70us length with an accuracy of at least 18ns tick, but preferably 10ns to account for hardware, etc inaccuracies. This one-shot pulse could repeat not more frequently then 1 second apart, but likely several seconds apart. The signal is two positive square waves forming a pulse measuring not less than 70us from the positive rising edge to rising edge. The system measures the pulse length and sends it the user (serial, BLE, etc).
Edit 2: someone suggested a "one-shot pulse stretcher". Interesting concept...   The more I am looking into it, the more I think it's a very viable hardware solution to the AVR's processing speed limitation. One may say that this is hardware "bitbanging" by streching out the short pulse to a proportionally longer one that the MCU capture process can measure reliably/accurately. An example is this old IC from Linear Tech. See Fig 12 and Fig 13.    https://www.analog.com/media/en/technical-documentation/data-sheets/6752fc.pdf
http://www.anderswallin.net/2014/02/pulse-stretcher-v1/

The shortest expected pulse would be about 70us which needs to be measured at (around) a resolution of 18ns for the accuracy I need.  So I went with 10ns for design to allow for some accuracy "overhead".  That is between 4000-7000 counts/ticks  (18ns-10ns ticks) for the 70us signal.
If I stretch this same 70us signal to be measured with the pulse-stretcher to 700us and use the currently available 125ns tick interval of the ATM32u4, I should arrive in theory to about the same accuracy as using an 18ns tick for a 70us signal to be measured.
Here is a similar problem that was answered: https://electronics.stackexchange.com/questions/46922/lengthening-a-5-ns-pulse

There is nothing you can do on the AVR processors that I know of, which can run on from a quite slow clock, and I think up to 24 MHz. Since your Uno / Leonardo / Micro run at 16 MHz that would be only an incremental speed improvement (to clock them at 24 MHz).
Your idea of bit-banging is interesting, but in general bit-banging is a last resort when you need extra things the hardware doesn't provide (like an extra SPI port) and in general will be slower, not faster, because it involves code rather than inbuilt hardware.
Running at 16 MHz each clock pulse is 62.5 ns which means that is the absolute most resolution it could count. I don't see why you can't count at the rate of 62.5 ns (rather than 125 ns), however that isn't 10 ns resolution.

Or, is there a stand-alone analog or digital IC that is able to read at 10ns intervals pulses that an Arduino can process?

Very likely. There are probably dedicated counting chips that would do that for you. I haven't looked, but it is the sort of thing there would be a market for. Such a chip would probably use I2C or SPI to communicate, which is easy enough to interface to.


How can I reduce the memory usage on my code? I wrote this code to control my christmas tree. It takes up the majority of the memory on my Arduino Uno:

Sketch uses 31822 bytes (98%) of program storage space. Maximum is 32256 bytes.
Global variables use 1882 bytes (91%) of dynamic memory, leaving 166 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

Does anyone know how I can reduce the memory usage?

Code:

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

#define TREEONE 3
#define TREETWO 4
#define TREETHREE 5
#define TREEFOUR 10

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for basement 50 for testing

const uint16_t monoMode = 1;

int song = 3;
int num = 0;
int count = 0;

//put arrays here
byte arrayTree[] = {17,16,9,8,3,2,5,4,17,16,9,8,3, ...etc };

void setup() {
  initSD();
  initMP3Player();

  pinMode(TREEONE, OUTPUT);
  pinMode(TREETWO, OUTPUT);
  pinMode(TREETHREE, OUTPUT);
  pinMode(TREEFOUR, OUTPUT);

  digitalWrite(TREEONE, HIGH);
  digitalWrite(TREETWO, HIGH);
  digitalWrite(TREETHREE, HIGH);
  digitalWrite(TREEFOUR, HIGH);
}

void loop() {
  if(!MP3player.isPlaying()){
    MP3player.playTrack(song);
    MetallicaChristmas();
  }
}

void initSD() {
  if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if(!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

void treeFunc() {
    //delay(arrayTimes[i]);
    num = arrayTree[count];

    //TREEONE
    if(num>15){
      if((num%2)==0){
        digitalWrite(TREEONE,HIGH);
      }else{
        digitalWrite(TREEONE,LOW);
      }
    }
    //TREETWO
    if((num%16)>7){
      if((num%2)==0){
        digitalWrite(TREETWO,HIGH);
      }else{
        digitalWrite(TREETWO,LOW);
      }
    }
    //TREETHREE
    if((num%8)>3){
      if((num%2)==0){
        digitalWrite(TREETHREE,HIGH);
      }else{
        digitalWrite(TREETHREE,LOW);
      }
    }
    //TREEFOUR
    if((num%4)>1){
      if((num%2)==0){
        digitalWrite(TREEFOUR,HIGH);
      }else{
        digitalWrite(TREEFOUR,LOW);
      }
    }
  count = count + 1;
}

void MetallicaChristmas()
{
  //event 1
  delay(670);
  treeFunc();
  delay(248);
  treeFunc();
  //event 2
  delay(116);
  treeFunc();
  delay(248);
  treeFunc();
  //event 3
  delay(100);
  treeFunc();
  delay(248);
  treeFunc();
  //event 4
  delay(132);
  treeFunc();
  delay(248);
  treeFunc();
  //event 5
  delay(125);
  treeFunc();
  delay(248);
  treeFunc();
  //event 6

  ...etc.

As well as PROGMEM (as described in the comments), there are a couple of other efficiencies that you can make:

A function call is expensive (takes a lot of code space), and you are performing a LOT of them!

The repetitious calls to delay() followed by treeFunc() are wasteful. Your commented-out line

//delay(arrayTimes[i]);

looks like you were going to do the right thing, so I’d restore that (use count instead of i) and put the delay() numbers in a new int arrayTimes[] array.

PROGMEM this array too, of course!
Once you’ve done this, you can remove all the calls to delay(). You’ll be left with nothing but repeated calls to treefunc(), which you can replace with a single loop:

for (count=0;count<sizeof(arrayTree);++count) {
   treeFunc();
} // for

Don’t forget to get rid of the count = count + 1; line from treeFunc() - it’s now in the for loop.

Also expensive is calling the same function twice except with different parameters in both sides of the if in treeFunc(). Instead of:

if (<condition>) {
   Function(1);
} // if
else {
   Function(0);
} // else

you can instead do:

Function(<condition>);

For this to work, you need to know that HIGH has the value 1 and LOW has the value 0 - and that a true condition has the value 1 and a false condition has the value 0.

So, you need to change the if () slightly:

digitalWrite(THREEONE, (num%2)>0);

Finally, the mod % operator itself is very expensive, since it is effectively a division, and the Arduino chip doesn’t know how to divide - so the code to do so is large. But the code you’ve written is using binary arithmetic, which the Arduino can do instantly - you just have to write it as such.

Instead of (num%2)>0 use num & B0001.
Instead of (num%4)>1 use num & B0010.
Instead of (num%8)>3 use num & B0100.
Instead of (num%16)>7 use num & B1000.

You’ve probably copied the guts of this code from somewhere else, and while it works it isn’t very efficient. Writing the code as above will greatly reduce your code size, exchanging repeated calls for much smaller PROGMEM arrays.


Arduino voltmeter maximum amp input I made a programmable Arduino that measures an input voltage. The Arduino will close or open an inverter using a relay to prevent the set of batteries from dropping below 50% to keep the batteries healthy. I currently have a set of 8 6V batteries configured to supply a total of 12V to one inverter. I used a set of 10k ohm and 100k ohm to safely measure the 12 volt input from the batteries. In the current configuration the total Amperage provided by the set of batteries is 400 amps. Is it safe to measure the voltage from a 12V/400A input or do I need some kind of protection?

It is perfectly safe.

The Arduino will see the voltage reduced by the divider you have. It will see whatever current it needs to see in order to sense the voltage - which is a tiny amount.

Remember: Current is drawn on demand by the load. It is never pushed by a supply.


Which Datasheet applies to the ATmega328p? While researching minimum-voltage requirements of Uno, I came across what appear to be two datasheets for the ATmega328P:

http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf

Specifically, the power requirements (and processor speed for each power level) differ. How could I know which datasheet applies to the chip I'm using? I'm actually using an Arduino clone:

You have ATmega328P-AU. Classic Uno with DIP socket has ATmega328P-PU. Arduino Uno SMD has Atmega328P-MU.

The automotive versions ATmega328P-15AZ and ATmega328P-15MZ have separate datasheet starting in Revision History with

  Creation of the automotive version starting from industrial version
  based on the ATmega48P/88P/168P/328P datasheet 8025F-AVR-08/08.
  Temperature and voltage ranges reflecting automotive requirements.


Arduino digital input fluctuates with neighbouring pins I am using digital pins (2,3,4,5) to play midi notes on and off with 3pdt switches with pull down 10k resistor between input pin and ground.

However when I press button 2 randomly at different time interval it sometimes shows pin 3 high in the monitor. (after reading forums here I have realised that it might be due to big switches that I am using where the physical contact plates might be reason for this). I have even changed wires and isolated them from each other to rule out the noise from the wires.
I have checked all the connections and soldered the Arduino board pins with best possible skills that I have and tracks are all clear.

Same case occurs between other buttons as but its not always.
However after reading about Debounce I have made changes to the code as following, now I got the error only once after that I havent seen it. Can someone have look at the code and advice me if I have assigned Debounce function to multiple switches correctly and if not, what should it be as I am new with coding
Since I am using 3pdt switch I have added switch mode..

#include <MIDI.h>

int buttonPin[] = {2, 3, 4, 5};
byte mode[] = {0, 0 , 0 ,0};
boolean currentState = LOW;
boolean lastState = LOW;
int buttonPinM[] = {6, 7, 8, 9};
byte mode1[] = {0, 0, 0, 0};

boolean currentState1 = LOW;
boolean lastState1 = LOW;

long lastDebounceTime = 0;
long debounceDelay = 50;

void setup (){
    MIDI.begin(MIDI_CHANNEL_OMNI);

    int i;
    for (i = 0; i < 4; i++) {
        pinMode(buttonPin[i], INPUT);
    }
    int j;
    for (j = 0; j < 4; j++) {
        pinMode(buttonPinM[j], INPUT);
    }

    {
        int i;
        for (i = 0; i < 4; i++);
    }
    {
        int j;
        for (j = 0; j < 4; j++);
    }
}

// This will track which pin/mode we're using

int j = 0;
int i = 0;

void loop () {
    {
        currentState = digitalRead(buttonPin[i]);

        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode[i]) {
                case 0:
                    if (currentState == HIGH) {
                        MIDI.sendNoteOff (i+55, 0, 1);
                        mode[i] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState == HIGH)
                        mode[i] = 2;
                    break;
                case 2:
                    if (currentState == LOW) {
                        MIDI.sendNoteOn (i+55, 127, 1);
                        mode[i] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState == LOW)
                        mode[i] = 0;
                    break;
            }
        }
        lastState = currentState;
        if (++i > 3)
            i = 0;
    }
    {
        currentState1 = digitalRead(buttonPinM[j]);
        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode1[j]) {
                case 0:
                    if (currentState1 == HIGH ) {
                        MIDI.sendNoteOn (j+61, 127, 1);
                        mode1[j] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState1 == HIGH)
                        mode1[j] = 2;
                    break;
                case 2:
                    if (currentState1 == LOW) {
                        MIDI.sendNoteOff (j+61, 0, 1);
                        mode1[j] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState1 == LOW)
                        mode1[j] = 0;
                break;
            }
        }
        lastState1 = currentState1;
        if (++j > 3)
            j = 0;
    }
}

Posting here since it is quite long, but it's not a complete answer, just a few thoughts and a possible improvement.

Ok, so there are a couple of things in your code I don't understand:

1: in the setup()

{
    int i;
    for (i = 0; i < 4; i++);
}
{
    int j;
    for (j = 0; j < 4; j++);
}

What are these for?

2: debouncing

You are not implementing it correctly, at least not for me. You are reading the button every 50ms, without debouncing. Ok, you won't see "bounces", but there are better solutions (see later).

3: modes 1 and 3

They are quite useless. What are they for?

4: pins 6,7,8,9

What are they for?

5: variable laststate

What is it for? You never use it

6: updating one button per loop

Is it needed? I mean, you are just updating one button per loop instead of all of them for each loop.

In the end

Ok, now my suggestions, apart from learning to indent the code (otherwise it's impossible to read it): I always use the bounce2 class to debounce a button, since it contains everything inside and.. Well, it works well. It can also detect the rising and falling edges of the button, thing that you need if I interpreted correctly your code.

One more thing: debounce delay can be lowered (even to just 5ms):

#include <MIDI.h>
#include <Bounce2.h>

int buttonPin[] = {2, 3, 4, 5};
int buttonPinM[] = {6, 7, 8, 9};

Bounce debouncers[4];
Bounce debouncersM[4];

int debounceDelay = 50; // Usually is lower - even 5ms is fine
uint8_t i = 0;

void setup ()
{
    MIDI.begin(MIDI_CHANNEL_OMNI);

    for (i = 0; i < 4; i++)
    {
        pinMode(buttonPin[i], INPUT);
        debouncers[i].attach(buttonPin[i]);
        debouncers[i].interval(debounceDelay);

        pinMode(buttonPinM[i], INPUT);
        debouncersM[i].attach(buttonPinM[i]);
        debouncersM[i].interval(debounceDelay);
    }
}

void loop ()
{
    for (i = 0; i < 4; i++)
    {
        debouncers[i].update();
        debouncersM[i].update();
    }

    for (i = 0; i < 4; i++)
    {
        if (debouncers[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOff(i+55, 0, 1);
        if (debouncers[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOn (i+55, 127, 1);
        if (debouncersM[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOn (i+61, 127, 1);
        if (debouncersM[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOff(i+61, 0, 1);
    }
}


Using RST pin as external power switch I have Arduino Nano with powered over USB. I have the request for external (physical) slide switch acting as power on/off for Arduino even if USB is always connected.

Looking at documentation and various posts, it seems the RST button could do just that. So when the "power" switch is on, RST is disconnected (= pulled high) and everything runs like normal. When the "power" switch is switched, it will pull RST low. As long as RST is pulled low, the board is stopped (the PWR led is lit, which is true and okay). Once released, the board will boot again.

Even though I agree this is not terribly elegant, is it going to work? I tried manually with the reset switch. Any side-effects I am overlooking?

That is a perfectly legitimate use of the RESET pin. Holding the chip in reset perfectly valid. Everything in the chip will be stopped.

Releasing it will start your sketch from the start again perfectly fine.

The only negative point is that your switch will be pulling power through the reset pin's pullup resistor, so will waste a little power.


Two 300RPM 12V DC motors connected to arduino motor shield r3 power supply I have two 300RPM 12V DC motors connected to arduino motor shield r3 that is mounted on arduino uno board.

Problem is my motors  runs very slow some times not even running.

After googling I found I need to use external power supply. I did  supplied 9 volt dc power to arduino motor shield r3.
But still motor is running very slow what could be the issue.

My other questions.

When supplying power to arduino motor shield r3  via external power supply pins do I need still need to provide separate power to arduino uno board via power jack.

Can I use 9 volt dc for arduino uno board and another 9 volt batter to arduino motor shield r3.

Is single 9 volt batter enough for running two 300RPM 12 dc motor.

My circuit.

My program

          void setup() {

          //Setup Channel A
          pinMode(12, OUTPUT); //Initiates Motor Channel A pin
          pinMode(9, OUTPUT); //Initiates Brake Channel A pin

          //Setup Channel B
          pinMode(13, OUTPUT); //Initiates Motor Channel A pin
          pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

        }

        void loop(){

          //Motor A forward @ full speed
          digitalWrite(12, HIGH); //Establishes forward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 255);   //Spins the motor on Channel A at full speed

          //Motor B backward @ half speed
          digitalWrite(13, LOW);  //Establishes backward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 123);    //Spins the motor on Channel B at half speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

          //Motor A forward @ full speed
          digitalWrite(12, LOW);  //Establishes backward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 123);    //Spins the motor on Channel A at half speed

          //Motor B forward @ full speed
          digitalWrite(13, HIGH); //Establishes forward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 255);   //Spins the motor on Channel B at full speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

        }

The external power of the shield is connected to the VIN pin, so it will power the Arduino via that. (vin goes to the voltage regulator that will provide the 5v the arduino needs).

You can connect two batteries in parallel to provide mode current.

But since they are 12v motors, they would need 12v to run at maximum power. 9v is a lot less than that.


How to read a text file line by line I am making an LED controller that reads instructions from a text file on my computer. I need to get the arduino to read this text file line by line and put each line into the appropriate variables. I'm using a sparkfun pro micro which is a knock off arduino pro micro. The pro micro is connected via USB

I've seen people use the SD library, but I don't know if this will work for my situation because I am reading directly from the computer and not an SD card. Is this the correct approach, or is there an additional/alternate library that I need to use?

What you can do is:

Read character by character and copy it to a temporary buffer of the maximum length of one line.
When you parsed an end of line symbol, you start parsing the (complete) line in the buffer.
In this line parsing (preferably a separate function), you parse the line, using string to type conversion functions, like atoi (string to an inter) etc. Also you can use the C function strtok to split the string based on a symbol (e.g. comma).
After parsing the line, clear the buffer (you already processed it), and continue filling the buffer again until it is full.
Don't forget to check for end of file.


Pyserial serial.write() doesn't work I need to communicate with an Arduino. When I use serial.readline() to read what Arduino has to say it works fine. But when I useserial.write('something') doesn't seem to do anything.

Interesting thing is that if I write the same code in the console or command-line, it works as expected...

Using Python 2.7.

Python code:

import serial
import time

arduinoSerialData = serial.Serial('com6', 9600)
time.sleep(1)

while True:
    arduinoSerialData.write('AAA')
    arduinoSerialData.flush()
    sleep(0.5)

Arduino code:

void loop() {

if (Serial.readString().startsWith("AAA")) {
    digitalWrite(7, LOW);
} else {
    digitalWrite(7, HIGH);
}

delay(500);

Again, Python code runs fine from the console, so no idea why this happens.

Closely related to To know the state of USB (Serial) connection (connected or not connected)

I would not be using Serial.readString() personally. How do you know where the string starts and ends? Just check for three "A" in a row.

Like this:

const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds
const byte LED = 7;

void setup ()
{
  Serial.begin (115200);
  while (!Serial) ;  // wait for Serial to become active
  Serial.println ("Starting");
  pinMode (LED, OUTPUT);
}  // end of setup

unsigned long lastMessage;
unsigned int countOfA;

void processInput ()
{
  while (Serial.available ())
  {
    char c = Serial.read ();
    if (c == 'A')
      countOfA++;
    else
      countOfA = 0;
    // do something with the data
  }  // end of while loop
}  // end of processInput

void loop ()
{
  if (Serial.available ())
  {
    lastMessage = millis ();  // remember when we last got input
    processInput ();  // now handle the input
  }

  if (millis () - lastMessage >= MESSAGE_TIMEOUT)
  {
    countOfA = 0;
  }

  // warn if no keepalive received
  if (countOfA >= 3)
    digitalWrite(LED, LOW);
  else
    digitalWrite(LED, HIGH);

}  // end of loop

Note that this will fail (ie. it will light the LED) if it gets something other than "A" which would include newlines, etc.

What it does it count the number of times it gets the letter "A". If it gets something else it resets the count. If 10 seconds elapse without receiving something, the count resets.


Serial.begin(): Why not always use 28800? In a lot of the sample code online people add the line Serial.begin(9600) in the setup block.

When I look up what Serial.begin() is on the official documentation, it says that it controls the bit per second data transfer.

So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

Why do people settle?

People settle because it is more than fast enough.  The most common use is just to print some stuff on a terminal for debuggin.  9600 baud is 960 characters per second, or 12 x 80 character lines per second.  How fast can you read? :)

If your program is using the serial port for bulk data transfer, you would choose not to settle.

  What is the limitation...

The limits on serial are high.  Directly you can use 115200 baud in your programs and it will just work.  The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.

Hardware serial will run to 1 M baud.  If you read around you will see people have used up to 1 M by directly controlling the UART.  You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip.  If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible.  Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.

Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling.  To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485.  With RS-232 you could run a mega bit at distances of 10's of feet.

The microprocessor clock speed will be the real limit.  With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81).  So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data.  A new byte will be sent every 160 clock ticks, which is very few lines of code.  For a short burst of data, you might achieve that rate.  The message is, the processor will run out of speed before the UART is the limit.

Note, this all applies to HardwareSerial, software serial is very different.


Aptotec PN532 shield power consumption I am currently planning a battery-powered project, where one of the tasks involves reading Desfire EV1 tags. Since the cheap RC522 based NFC shields are reported not to work with the Desfire EV1 tags, I wanted to make an attempt with a PN532 based shield. Due to offering the fastest shipping option, I ordered an Aptotec PN532 shield, although there are many other, and likely cheaper options out there as well. The Aptotec shield seems identical to the Seeed NFC Shield V2.0.

Communicating with the Desfire EV1 tags works as expected, but I am not understanding the shield's power consumption. If I understand the PN532 datasheet correctly, the chip itself should only draw 45µA when in standby mode, some 30mA when active, but not transmitting and additionally up to 150mA more during actual transmission.

After sending an 'InRelease all targets' command to the PN532, the shield however still draws about 50mA, although the PN532 should be in stand by mode. Using the RFConfiguration command to turn the RF field off completely still does not decrease the shield's power consumption. Activating the RF field e.g. by issuing an InListPassiveTarget command, the current draw increases to about 80mA, which matches with my assumption that the PN532 now draws 30mA more than when idle. There seems however to be something else on the shield causing a 'base line' 50mA current draw, which is not caused by powering the PN532 chip.

Does someone know where this power is lost, if it is possible to software-based turn off whatever is causing the power draw or if other PN532 shields show the same behaviour? Since my project must run on a battery, the 50mA unexplained current draw is not acceptable.

After some trial and error, I think I can answer this one myself.

The circuit schematic from the Seeed module is actually broken and the Apotec model is built almost identically. The PN532 chip has an SVDD output pin to power an optional security access module for cryptography support. In the Seeed design, this pin is connected to the 3.3V input voltage from the voltage regulator, which is simply wrong and the pin sinks an essential amount of current.


Can Arduino accept HDMI input video stream, and output it without any modification to the video? I'd like to know please whether an Arduino can accept an HDMI signal from a satellite receiver, let it flow without any modification to the stream, and output it to TV?

No.

HDMI uses multiple serial data streams at gigabit rates. No Arduino is ever going to do that sort of thing.  If you want something programmable to do that kind of thing you need an FPGA.


How to send MFRC522 data to a C# app using a NodeMCU TCP server? I am trying to send MFRC522 data to a C# application through a NodeMCU acting as an access point for the C# app. I have modified the code I got from this site.

#include ESP8266WiFi.h>
#include SPI.h>
#include MFRC522.h>

const char* AP_SSID ="IoT4143" ;
const char* AP_PASSWORD ="iot4143";

#define RST_PIN D3
#define SS_PIN D4

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

WiFiServer server(80);
WiFiClient client;

void wifiConnect() {
  WiFi.disconnect();
  WiFi.softAP(AP_SSID, AP_PASSWORD);

  int watchDog = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    watchDog++;
    if(watchDog == 60) {
      WiFi.disconnect();
      WiFi.printDiag(Serial);
      watchDog = 0;
      return;
    }
  }
  server.begin();
}

void setup() {
  Serial.begin(115200);
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
  wifiConnect();
}

void loop() {
  //Are we connected to WiFi?
  if(WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }

  //Wait for a connection attempt
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  int watchDog = 0;
  while(!client.available()) {
    delay(1);
    if(watchDog == 10000) {
      watchDog = 0;
      return;
    }
    watchDog++;
  }
  sendData();
}

void sendData() {
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  client.flush();

  // Match the request
  while(request=="READSTOP") {
    Serial.println("RFID READING STARTED..."); //Forward to C# App
    if (!mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    // Select one of the cards
    if (!mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    // Dump debug info about the card; PICC_HaltA() is automatically called
    client.print(mfrc522.uid));
  }
  Serial.println("RFID READING STOPPED"); //Stop server
  delay(1);
  client.stop();
}

I am very new to hardware/network programming. I don't know what will be possible errors in this code and whether it will work or not.

When I verified the code in the Arduino IDE, there was an error on this line of code:

client.print(mfrc522.uid));

  error:= no matching function for call to 'WiFiClient::print(MFRC522::Uid&)'

When the connect button in the application is clicked the "READSTART" string is sent to NodeMCU and when disconnect is clicked the "READSTOP" string is sent.

Please help!

MFRC522::uid is a struct (see source code). There's no defined way to print it.

If you want to write the raw bytes over the TCP connection, you can just use

client.write((uint8_t*)mfrc522.uid.uidByte, mfrc522.uid.size);

If you want to write it as ASCII text, you can use the following:

void byte_to_str(char* buff, uint8_t val) {  // convert an 8-bit byte to a string of 2 hexadecimal characters
  buff[0] = nibble_to_hex(val >> 4);
  buff[1] = nibble_to_hex(val);
}

char nibble_to_hex(uint8_t nibble) {  // convert a 4-bit nibble to a hexadecimal character
  nibble &= 0xF;
  return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
}

void printHEX(Stream &s, uint8_t *data, size_t length) {
  char *buffer = new char[length*2];
  for (size_t i = 0; i < length; i++) {
    byte_to_str(&buffer[i*2], data[i]);
  }
  s.write(buffer, length*2);
  delete[] buffer;
}

Then use it like this:

  printHEX(client, mfrc522.uid.uidByte, mfrc522.uid.size);

It loops over all bytes in the UID, converts them to ASCII (hexadecimal representation, so 2 characters per byte), and then writes the text over the TCP connection.

(Note that there are many other problems with your code as well, e.g. the includes are missing the opening '<'.)


Can't upload to my Arduino UNO When I upload my sketch I get this error message:

  avrdude: ser_open(): can't open device "\.\com3": the system cannot
  find the file specified

I tried reinstalling the IDE and the drivers. I tried looking into the preferences txt file and the COM was alright.

Also, I uploaded it successfully from another computer.

What is wrong about my PC trying to upload Arduino? And the most curious thing of all is that yesterday it was fine and it was working.

First of all DON'T PANIC, it's more than probable your Arduino is not broken.
Start running the following checks:

is any other software using the same serial port? serial ports cannot be concurrently opened by multiple processes...
disconnect the board, reset your PC, wait until the boot process is completed and then connect again: does your OS recognize the COM port? (Windows emits a sound, GNU/Linux logs a few lines...)
check the COM port matches, may be your board is no more recognized as COM3 but as COM4, depending on multiple factors
if you have anything wired to your board, disconnect everything, unplug the board and then re-connect the board alone, with nothing connected to its pins: you might have a short somewhere or using pins 0 or 1 (marked as RX & TX, they are also used for communication)
is your USB cable connection flaking? it might seem stupid, but if you have multiple cables running around your PC it is indeed possible to pick the wrong one or loose it from the socket...
are you using a cheap cinese clone? There are clones using counterfeited USB chips which get banned by Windows automatic updates, but a workaround exists even for that

While it is possible to brick the Arduino boards via software, there are very little possibilities you did it because it involves using tools completely hidden to the Arduino occasional user / newcomer.


Simplest/best way to control a set of 8-10 PWM signals from a smartphone As part of a larger project, I would like to be able to control a set of 8-10 PWM signals remotely, from a smartphone at a distance of 10 meters or more.  I will probably convert the PWM signals to analog voltages, and reduce their voltage swings to more like 0-1v, using a resistor divider and RC filter; they will drive high impedance loads in the remainder of the project.  I’d write an app for the smartphone allowing user control over the duty-cycle of each PWM signal (and thus the analog signal levels).

It seems to me that the way to go is Arduino, interfaced to the phone with Bluetooth.  I'd need one of the higher end Arduinos to get enough PWM signals (the basic ones like Uno only have 6 PWM outputs).  Software-generated PWMs are probably not high-frequency enough, as I’d like the filtered analog signals to be as ripple-free as possible. There seem to be several ways to interface Bluetooth to Arduino, such as the HC-05.

If people here concur with this approach, I shall move this question to the Arduino forum.

`

HC-05 is rated to about 9m so it wouldn't necessarily meet your requirement. The ESP8266 (example of one implementation called the Node MCU) can output PWM on any of the 0-16 pins. It can easily implement a web server which would let you control your outputs via 8026.11 (wifi). It also means you don't need to build anything for the phone/ tablet/ PC just use a web browser. The duty cycle could be set through the web server on the ESP. The ESPs are around the same price as an Arduino.

I've used the HC-05 with an arduino. It works very well, though not very far. For the Android side I used app inventor which is extremely easily to use for bluetooth.


Starter Kit for Arduino Cookbook I have this book here about Arduino. What kind of Kit should I purchase to get started? Would this work?

I'm not yet sure about what I'd like to do with Arduino, so I may prefer a pretty Universal Kit in order to cover a pretty wide range of projects.

Except this, I won't need any advanced stuff, at the moment, as a beginner I may want to understand the fundamentals, so will surely need LEDs, maybe screens, and other basic stuff like that.

Later on I may try to go for Wireless modules, but not at the moment as a beginner.

Any ideas? Hope to have clarified more or less what projects I'm aiming to, yeah the range is wide, but restricted to basic beginner projects.

The Stack Exchange format is not well suited for opinions.  That said, people are apparently giving the kit good reviews.  And I see hardware that appears to allow for several projects (LED arrays?, motors?, ultrasonic-distance-measurement?, IR-remote-control?, Alpha-numeric-LCD?, 7-segmet-LED-display?, ect).  Which is more than you need for basic Arduino projects.

In general, it would make the most sense to find a kit with a book rather than obtain a book and a kit separately. This is because slight differences between the written material and independently obtained hardware will cause confusion.  This is generally not a problem for experienced embedded developers.

Keep in mind that embedded processor projects are half hardware and half software.  Since the hardware has already been collected, the majority of activity will be in software.  If this paradigm agrees with you, good luck & have fun.


Analog output doesn't work for just 2 LEDs [Arduino Mega] I am having a problem with an Arduino Mega 2560.

Everything works fine, the ultrasonic sensors work fine, and the other LEDs work fine. Although there is 2 LEDs who do not work right and when I do analogWrite(), they actually do digitalWrite(). I have tried to attach these two LEDs to a potentiometer (potentiometer works fine, values are tested) but it always does digitalWrite() not analogWrite().

I have tested the LEDs and potentiometer on an Arduino Uno in PWM pins and analog pin and yes it does work very well.

Please mind that these LEDs are attached to analog pins. Why is this? Because I do not have anymore PWM pins available to use and so I have to use analog pins. No way I can rearrange this.

Here is part of the code (only part otherwise it's too long, most of my pins are taken):

//Leds//

int led = A4;
int ledUV = A3;

//Potentiometer//

int potReading;
int potPin = A2;
int lightDim;

void setup(){

    Serial.begin(9600);

    pinMode(led, OUTPUT);
    pinMode(ledUV, OUTPUT);

    pinMode(potPin, INPUT);

}

void loop(){

    potReading = analogRead(potPin);
    lightDim = (255./1023.)*potReading;

    analogWrite(led, lightDim);
//  analogWrite(ledUV, lightDim);
//  Serial.println("pot: ");
//  Serial.println(potReading);
//  Serial.println(" ");
    Serial.println("dim: ");
    Serial.println(lightDim);
//  analogWrite(led, 255);
//  analogWrite(ledUV, 255);

}

Analog pins an only read analog values, not write them.

analogWrite() is a deceptive name. It should really be PWMWrite() since all it does is PWM. And that, of course, needs PWM pins.


If I connect a battery to the vin pin on the arduino, will the 5V pin be activated? My wording might be a bit confusing, if I plug an 8 volt battery into Vin, will the arduino be powered and will the 5V pins work?

Yes, that's what the Vin pin is for: unregulated voltage or a voltage higher than 5V. Then the 5V pin will be at 5V, regulated by the on board regulator. You would only connect a source to the 5V pin if the source is already a regulated 5V.


Trouble with Timer 0 I'm taking my first wobbly steps outside the Arduino IDE and I'm not having much success with timers / interrupts. I can set a pin to output and light an LED with registers fine but I cannot for the life of me get it to blink using a timer. I have tried numerous tutorials and followed the Atmel ATmega328 datasheet very closely.

Using an Arduino Uno R3 & Atmel ICE (ISP.) My dev system is Raspbian (Debian) with the GNU AVR toolchain (avr-gcc, avr-objcopy, avrdude.) Apart from not having a bootloader it's a bog standard board (including fuses.)

Here's my current code:

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

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= (1 << PB5); // Toggle Arduino Pin #13
}

int main (void)
{
    DDRB = (1 << DDB5); // Arduino Pin #13 is Output

    cli(); // Clear Interrupts

    OCR0A = (unsigned char)0xFF; // Compare Register A = 255
    TIMSK0 = (1 << OCIE0A); // Enable Interrupt for Comp. Reg. A
    TCCR0A = (1 << WGM01); // CTC Mode

    sei(); // Set Interrupts
    TCCR0B = (1 << CS02) | (1 << CS00); // Divide by 1024 Prescaler (GO!)

    return 0;
}

I don't know if I'm just not seeing something or if I've set registers in the wrong order but it's driving me crazy.

return 0 resets the device. Use while(1); instead, to make it wait indefinitely.


Stopping Serial on RX/TX pins while running Serial on USB The Arduino/Genuino Micro has RX/TX pins and can do serial via USB.

But, Arduinos Serial ties them both together, so when using Serial.begin(9600) to send messages between my PC and the Arduino, I cannot use the RX/TX pins as GPIOs.

From what I can tell reading the Atmega32u4s Datasheet, the USART module on the chip is completely separate from the USB controller, so it should be possible to somehow disable the USART Transceiver and Receiver after executing Serial.begin(9600).

Is there something fundamental preventing me from doing this or can it be done? If it can, how would I do it?

The Serial and Serial1 are two seperated ports. They are not connected. The Serial is the USB serial and does not use pin 0 and 1 at all. The Serial1 is the hardware serial port at pin 0 and 1, but if Serial1 is not used then pin 0 and 1 are normal digital pins that you can use.

Don't be confused by the text labels printed on the board. Pin TX (also called TX1) is D1 and pin RX (also called RX1) is D0.
This is the pinmapping for the Micro: PighiXXX - Micro.

The Arduino Zero uses 'SerialUSB' to indicate the serial port via USB. You can do the same for the Leonardo and the Micro and use the alias 'SerialUSB' in your sketch instead of 'Serial'.
I found it more convenient to use 'SerialUSB' in my sketch, but not many people use it.
The Serial port at pin 0 and 1 is still called 'Serial1'.