Arduino Nano/Uno and js sketch compiling/uploading from browser I need to compile generated source code in js runtime then upload it to my device.

Compiling:

I have found arduino-cli

Uploading:

There is only avrgirl but it doesn't work in browser. What should I do?

You can't, and that's a good thing. If the browser could let a Web site access your hardware, that would be a huge security breach. You may be able to bypass this security restriction if you can write an extension (plugin) for your browser.


Multiple independent LED patterns I have an problem, which at first thoughts (and being new to Arduino) I though was a perfect application for an Arduino. However, after trying and failing to implement it I am doubting myself!

Simply - I need to control many LEDs independently, many of which will have their own individual patterns - for example "5 seconds on - 5 seconds off". "continuous flashes" - or sequences such as "2 flashes, pause, 1 flash". Obviously without the luxury of threads I am becoming a little unstuck. Be great to hear if a) Arduino is the best choice and b) if it is - how can I go about this!

Thanks in advance :)

Handling multiple patterns at the same time is certainly possible with a platform like Arduino, and there are a number of ways you could go about it.

One method I would consider is writing functions which effectively represent each pattern mathematically. You'd just pass it the total time that's elapsed in your program so far, and it will do the appropriate action for that specific moment in time. It will return immediately afterwards (no delays or anything).

To do that, you'll first need to know how long a single cycle of the pattern lasts. You can then use the modulo operator to figure out how far through the current cycle you are. From there, all you need to do is have some if conditions to determine what to do at any given time.

Here's what it might look like for your "5 seconds on, 5 seconds off" pattern:

function pattern5on5off(unsigned long totalTime)
{
  // Calculate how far through the current cycle we are
  const unsigned long cycleTime = totalTime % 10000;

  // If we're in the first 5 seconds of the cycle then turn the light on.
  // Otherwise, turn it off.
  if (cycleTime < 5000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

Admittedly, constantly calling digitalWrite() when you don't technically need to isn't very efficient. It shouldn't cause any harm though, and is fairly easy to optimise if necessary.

To use the above example in a sketch, you'd just need to call it in loop(), and pass the number you get from millis(); e.g.:

void loop()
{
  const unsigned long totalTime = millis();

  pattern5on5off(totalTime);

  // call other patterns here...
}

Other patterns will be more complex, but follow the same principle. You'd just to use appropriate if statements to express your logic.

The vital thing to remember is that the function represents a specific moment in time. It should never pause or delay the program, otherwise it will prevent the other patterns from running.

Edit: Timing on the first cycle
As jfpoilpret noted in the comments, the very first cycle will start at a random point. This is because the first time you call millis() in loop(), it won't start at 0 (the device will already have been running for a short time before loop() gets called). It's easy to resolve though, if necessary.

You would do it by offsetting the totalTime value by the whatever value you got on the very first time around loop(). For example:

unsigned long g_startTime = 0;

void loop()
{
  unsigned long totalTime = 0;

  if (g_startTime == 0) {
    // This is the first cycle.
    // Store the start time so we can compensate later.
    g_startTime = millis();

  } else {
    // This is not the first cycle.
    // Compensate for the start time.
    totalTime = millis() - g_startTime;
  }

  pattern5on5off(totalTime);
  // etc..
}


Problems adding ESP8266 wifi board I just received an ESP8266 wifi module and I am trying to add the board. However I am having an issue. All websites/tutorials say to use http://arduino.esp8266.com/stable/package_esp8266com_index.json, however nothing is there. Can it be found somewhere else?

It looks like the server is down.  Isitdownrightnow reports that it's been down for almost 4 days: http://www.isitdownrightnow.com/arduino.esp8266.com.html

There is a discussion about it over on the ESP8266 forums: http://www.esp8266.com/viewtopic.php?f=26&t=3134&start=8

Let's hope it will be back again soon.


Motor cutting out when using HC-05 Bluetooth module I'm using an L293D motor driver chip along with an HC-05 Bluetooth module. The two work as expected separately - I can send a string via a Bluetooth terminal app on my phone to the HC-05 and I see it in the serial monitor just fine, and I can use the serial monitor to change the speed/direction of the DC motor without an issue. However, if I try to use the Bluetooth console on my phone to change the speed, the motor only spins for about a second before I lose connection with the HC-05 and it stops.

I think this is happening because the Arduino is tripping some breaker by drawing too much current to power both the HC-05 chip and the DC motor. Is this the case? Should I use an external battery pack to power the DC motor and L293D chip, and then keep the HC-05 connected to the 5V out line on the Arduino?

Thanks.

Previously I was powering everything off of the 5V line on the Arduino, but I just switched to using an external battery pack of 4 AAs and that seems to work fine.

That suggests, that your power source was not strong enough. You didn't say, how you are powering the Arduino, but I guess you are doing so via USB. The USB port of a PC can only give you 500mA of current (at least without any extra configuration to get more). Also the parts on the Arduino (for example the diode between USB power and the 5V pin) can only give you a limited amount of current. Especially when the motor is starting, the needed current is rather big. That might have caused a short voltage dip, deep enough to irritate the HC-05 module.

Using an extra battery as power source for the motor eliminates that problem. Though I think you should be able to connect all parts to the same power source, as long as it is powerfull enough to power all parts (plus some overhead). In that case be sure to connect the power for the L293D and Arduino in parallel, so that the motor current does not have to flow through the Arduino (which could kill the voltage regulator or the diode).

Depending on your motor, it also might generate a huge amount of EMI (Electromagnetic Interference) either though air transmission or through the power lines, which might irritate the HC-05 enough. In that case the easiest option would be to add a second power source. Though I think the problem is with the power source as described above.


How do I set the motor state to "HIGH" at the beginning of this sketch? My intent with this sketch is to have motors run for one minute, then stand by for 18 minutes. In practice, the sketch starts the motor state at "low" for the OffTime interval, then goes to the OnTime interval and loops. The desired result is exactly the opposite: the "high" interval first, followed by the "low". I have tried setting the motorState to "HIGH" in the constructor and played with the order of the IF statements to no avail.

I would appreciate any insight into this problem, as well as an intuition for the practical use of millis(). I need a solution which doesn't use delay but am having trouble wrapping my head around the logic of millis() as used. (I adapted this code from a tutorial.)

class LifeTest
{
  // Class member variables initialized at startup
  int motorPin;
  long OnTime;
  long OffTime;
  // These maintain the current state
  int motorState;                               // Used to set the motor.
  unsigned long previousMillis;                 // Stores last time motor was updated.

  public:
  LifeTest(int pin, long on, long off)
  {
    motorPin = pin;
    pinMode(motorPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    motorState = LOW;
    previousMillis = 0;
  }

  void Update()
  {
    unsigned long currentMillis = millis();     // Check to see if it's time to change the motor state.
    if((motorState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
    motorState = LOW;                         // Turn off motor.
    previousMillis = currentMillis;           // Remember the time.
    digitalWrite(motorPin, motorState);       // Update the motors.
    }
    else if((motorState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
    motorState = HIGH;                        // Turn on motor.
    previousMillis = currentMillis;           // Remember the time.
    digitalWrite(motorPin, motorState);       // Update the motors.
    }
  }
};

LifeTest motor1(50, 60000, 1080000);
LifeTest motor2(51, 60000, 1080000);
LifeTest motor3(52, 60000, 1080000);
LifeTest motor4(53, 60000, 1080000);

void setup()
{
}

void loop()
{
  motor1.Update();
  motor2.Update();
  motor3.Update();
  motor4.Update();
}

I would appreciate any insight into this problem, as well as an intuition for the practical use of millis().

I have a lengthy tutorial about this at How to do multiple things at once ... like cook bacon and eggs.

However as this site frowns upon link-only answers (the link might go down) I'll try to explain as well, here.

millis() is like having a wristwatch. You glance at it from time to time to see if it is time to do something, like catch a bus to work, put the dinner on, take the cake out of the oven, that sort of thing.

If you delay() all the time, you can only do one thing at a time. For example, if your cake takes 30 minutes to cook, and you do this:

PutCakeInOven ();
delay (30UL * 60 * 1000);  // delay 30 minutes
TakeCakeOutOfOven ();

This is fine, but you aren't also cooking some eggs at the same time, or doing the dishes, right?

With millis() you can do lots of things! Win-win! The basic technique is to note the time when you started, and then when time is up, you do whatever-it-is you need to do. Like this:

unsigned long BakeStartTime;
const unsigned long CookingTime = 30UL * 60 * 1000;  // 30 minutes
bool CakeInOven = false;

void setup ()
  {
  PutCakeInOven ();
  BakeStartTime = millis ();  // when the cake went into the oven
  CakeInOven = true;
  }

void loop ()
  {
  if (CakeInOven && (millis () - BakeStartTime >= CookingTime))
    {
    TakeCakeOutOfOven ();
    CakeInOven = false;
    }

  // do a whole lot of other stuff, like cooking some eggs

  }

You can expand this technique to do dozens of things "at once".


3.3v pin on a 5v Pro Micro? I have a arduino pro micro that runs on 5v.
I also have a Max4466 that needs 3.3v, however the pro micro doesn't seem to have a 3.3v VCC.
Is there any way to attach the max4466 to the Board?

You need to add an external 3.3V voltage regulator. You can get these quite cheap on eBay (etc) as a module - some even come in a breadboard friendly format.

Power it from the 5V from the Arduino, then power your MAX4466.

However, the MAX4466 can run at up to 5.5V, so I fail to see why you think you need 3.3V.


Arduino Micro: 69 is supposed to show up when I press 1 on the keypad, however some weird number (15 in this case) is showing up // **I AM ALSO GETTING WEIRD CLUELESS DELAYS WHEN I PRESS BUTTONS ON THE MODE MENU**

/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 0.70
   An Open-Source Project by John Seong
*/

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

const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

int timeV, thrustV, massV, gravityV;

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

bool keyDetect = false;
bool menuKeyDetect = false;
bool goHomeDetect = false;

bool countDownDetect = false;
bool countDownOutput = false;
bool twrCalDetect = false;

String timeValue, thrustValue, massValue, gravityValue;

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

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

  Startup();

  timeV = constrain(timeV, 15, 120);
}

void loop() {
  PressKey();

  if (menuKeyDetect == true) {
    PressMenuKey();
  }

  if (goHomeDetect == true) {
    GoHome();
  }

  if (countDownDetect == true) {
    CountDownSequence();
  }

  if (countDownOutput == true) {
    CountDownOutputSequence();
  }
}

// Pages & Sections
void Startup() {
  lcd.print("Jeb's Launch");

  lcd.setCursor(0, 1);
  lcd.print("Control System");

  delay(3000);

  lcd.clear();
  lcd.print("Alpha Build 0.70");

  lcd.setCursor(0, 1);
  lcd.print(" STUDIO HORIZON");

  delay(3000);

  lcd.clear();
  lcd.print("Welcome, Kerman");

  lcd.setCursor(0, 1);
  lcd.print("Press any key...");

  keyDetect = true;
}

void ModeMenu() {
  menuKeyDetect = true;

  lcd.clear();
  lcd.print("1. Countdown");

  lcd.setCursor(0, 1);
  lcd.print("2. TWR");
}

void CountDown() {
  lcd.print("Time (sec): ");

  lcd.setCursor(0, 1);
  lcd.print("# to continue...");

  goHomeDetect = true;
  countDownDetect = true;
}

void TwrCal() {
  lcd.print("Thrust: ");

  lcd.setCursor(0, 1);
  lcd.print("# to continue...");

  goHomeDetect = true;
}

// Actions & Behaviours
void PressKey() {
  char key = keypad.getKey();
  if (key) {
    Serial.println(key);
    if (keyDetect == true) {
      lcd.clear();
      ModeMenu();
      keyDetect = false;
    }
  }
}

void PressMenuKey() {
  char key = keypad.getKey();
  if (key == '1') {
    Serial.println(key);
    if (menuKeyDetect == true) {
      lcd.clear();
      CountDown();
      menuKeyDetect = false;
    }
  } else if (key == '2') {
    Serial.println(key);
    if (menuKeyDetect == true) {
      lcd.clear();
      TwrCal();
      menuKeyDetect = false;
    }
  }
}

void GoHome() {
  char key = keypad.getKey();
  if (key == '*') {
    lcd.clear();
    ModeMenu();
  }
}

void CountDownSequence() {
  char key = keypad.getKey();

  if (key == '0') {
    timeV = timeV + 0;
  }

  if (key == '1') {
    timeV = 69;
  }

  countDownDetect = false;
  countDownOutput = true;
}

void CountDownOutputSequence() {
    lcd.setCursor(13, 0);
    Serial.println(timeV);
    lcd.print(timeV);
}

According to the documentation, the getKey() function is
non blocking. This means it does not wait for a key to be pressed:
it instead returns immediately whether a key has been pressed or not. If
no key has been pressed (i.e. most of the time), it returns a NUL
character, which has the numeric value zero and evaluates to false in
a boolean context. Hence the idiom:
char key = keypad.getKey();
if (key) {  // if a key has actually been pressed
    // handle it
}

The CountDownSequence() function fails to account for this:
void CountDownSequence() {
  char key = keypad.getKey();  // no check for NUL

  if (key == '0') {
    timeV = timeV + 0;  // this has no effect at all
  }

  if (key == '1') {
    timeV = 69;  // this is what you would expect to be executed
  }

  countDownDetect = false;  // these two lines tell the rest of the
  countDownOutput = true;   // program that we are done.
}

Since key will almost certainly be '\0', the program will move to
the next step without ever initializing timeV.
As a side note, I recommend you try to rewrite your program as a finite
state machine. A single state variable would make it less
confusing and easier to understand than the current collections of
booleans.

Edit: Expanding on the idea of the finite state machine. I tried an
implementation of your concept based on it.
For handling a menu system, where the user can navigate through several
on-screen “pages”, the most obvious first approach is to have one state
per page displayed. For this program, these states could be:

MENU, which offers the choice to move to either of the following two
pages
SET_COUNT allows the user to set the countdown duration
TWR allows him to compute the thrust/weight ratio
COUNT_DOWN actually runs the countdown timer

In the following, I added an extra transitional state called START
that comes right before MENU. This is not required, and its only
purpose is to avoid code repetition by having a single transition
(START → MENU) responsible for actually drawing the menu.
When implementing a finite state machine, my first recommendation would
be to start by drawing a state diagram like this:

In this diagram, each transition is labeled with the event that triggers
it. The events are key presses, save for “finished” which means that the
countdown is done. The state diagram can become significantly more
complex than this as you add new functionality. It is, however, a very
good way of designing your system from the point of view of user
interaction.
Once you are happy with the state diagram, the coding is just a matter
of translating it to a switch/case construct, with one case per
state. Here is my take at it:
/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 0.70
   An Open-Source Project by John Seong
*/

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

const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad=Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// Show a two-line message on the LCD.
void lcdShow(const char *line0, const char *line1) {
  lcd.clear();
  lcd.print(line0);
  lcd.setCursor(0, 1);
  lcd.print(line1);
}

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcdShow("Jeb's Launch", "Control System");
  delay(3000);
  lcdShow("Alpha Build 0.70", " STUDIO HORIZON");
  delay(3000);
  lcdShow("Welcome, Kerman", "Press any key...");
  while (!keypad.getKey()) ;  // wait for key press
}

void loop() {
  static enum {START, MENU, SET_COUNT, COUNT_DOWN, TWR} state = START;
  static uint32_t last_second;  // millis() value on last full second
  static int count;             // countdown value

  char key = keypad.getKey();

  switch (state) {
    case START:  // transitional state
      lcdShow("1. Countdown", "2. TWR");
      state = MENU;
      /* fallthrough */
    case MENU:
      if (key == '1') {  // Countdown
        lcdShow("Enter time", "seconds: ");
        count = 0;
        state = SET_COUNT;
      } else if (key == '2') {  // TWR
        lcdShow("Thrust:", "# to continue...");
        state = TWR;
      }
      break;
    case SET_COUNT:
      if (key >= '0' && key <= '9' && count <= 99) {
        lcd.print(key);
        count = 10 * count + (key - '0');
      } else if (key == '#') {
        lcdShow("Take off in", "     seconds");
        // Force a refresh on entering COUNT_DOWN:
        last_second = millis() - 1000;
        count++;
        state = COUNT_DOWN;
      } else if (key == '*') {
        state = START;
      }
      break;
    case COUNT_DOWN:
      if (millis() - last_second >= 1000) {
        last_second += 1000;
        count--;
        if (count == 0) {
          Serial.println("Take off!");
        } else if (count < 0) {
          state = START;
          break;
        }
        lcd.setCursor(1, 1);
        lcd.print(count<10 ? "  " : count<100 ? " " : "");  // pad
        lcd.print(count);
      } else if (key == '*') {
        state = START;
      }
      break;
    case TWR:
      if (key == '*' || key == '#') {
        state = START;
      }
      break;
  }
}

Note the comment “fallthrough” between START and MENU. This
indicates that the lack of break at this place is intended: the
processing of the MENU case will follow right after the processing of
the START case, in the same loop iteration. The purpose of the fall
through is to not loose the current key press, if any. If this is not
important, you could put a regular break here and defer the handling
of MENU to the next loop iteration.
Note also that the key presses are checked with tests of the form
if (key == SOME_VALUE), which means there is no need for an extra
if (key) to test whether there was an actual key press.


How can I stop someone from hacking in to my Arduino via Bluetooth? I am using an HC-05 bluetooth Module. How can I stop someone from pairing with my device by brute forcing the key? Failing that, and if someone does pair with my device, is there a way to authenticate the user? I was thinking of salted hash with a shared secret key. Is there anything better?

Configure your Bluetooth module to AT Command Mode

Then use AT+PIN Command to change the default PAIRING PIN of the Bluetooth Module.

Visit this link for more information about how to configure bluetooth to AT Mode


Arduino and ESP8266 communication over wifi I need to same advice, how to realize communication between ESP and arduino over wifi. I have connected temperature and pressure sensor to ESP, and I need to get this data from sensor to arduino. ESP will be connected to battery, so it should be also low power solution. I thought about something like every 2 minutes read the data and send to arduino, and then deepsleep. However I don’t know, how to realize that communication. I need webserver on arduino and client at ESP? Could someone help me?

On the Uno with Ethernet shield you start an EthernetServer on port 23 or 2323. See ChatServer example.

On esp8266 you create a WiFiClient, connect it to IP address of the EthernetShield and port 23 (or 2323). Everything you print to WiFiClient will be send to EthernetServer's EthernetClient.

You can test the server with Telnet client.


Change conditioning in real time I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:

int solenoidPin = 4; //connected to Digital 4
int moisturePin = A0; //connected to Analog A0

void setup() {
  Serial.begin(9600);
  pinMode(solenoidPin, OUTPUT);
}
void loop() {
  int val;
  moisture = analogRead(moisturePin); //connect sensor to Analog A0
  Serial.println(val); //print the value to serial port
  delay(1000); //wait 1 second for next reading

  if (moisture <= 350) //if moisture is less than reading 350 {
  digitalWrite(solenoidPin, HIGH); //switch solenoid ON
  delay(600000) //water for ten minutes
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
}

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the if (moisture <= 350) while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?

if (moisture <= 350) //if moisture is less than reading 350 {

That is wrong, because you have the brace { after the comment. You need it before the comment, eg.

 if (moisture <= 350) { //if moisture is less than reading 350

Or preferably in my opinion:

if (moisture <= 350) //if moisture is less than reading 350
  {

  I'm just asking if it's possible to change the if (moisture <= 350)

Yes, of course. That's what variables are for. You could read a potentiometer, and the value from that could replace 350 in the code. You could use a simple LCD or LED display to show what the current reading is.

  delay(600000) //water for ten minutes

Your problem here is that the sketch will be totally unresponsive (it would not react to your changing the moisture level) during the time you are watering. You might want to read How to do multiple things at once which shows how you can keep doing other things, while waiting for time to elapse.


Serializing data created by ATTiny85 for use on PC Have an AES-128 implementation I'd like to install on an ATTiny85 for embedded use but need to come up with a way to communicate with it from a PC as you would do via Serial on Arduino Uno. For example, I'd like to stream 16 bytes of plaintext and get back 16 bytes of ciphertext (or signature hash, etc.).

The faster the transfer rate, the better obviously, but it would of course need to fit on the remaining space on an ATTiny85.

Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

So thanks to Ignacio Vazquez-Abrams' tip, it looks like I'll be able to accomplish this with V-USB:

  V-USB is a software-only implementation of a low-speed USB device for
  Atmel’s AVR® microcontrollers, making it possible to build USB
  hardware with almost any AVR® microcontroller, not requiring any
  additional chip.

Requirements: AVR microcontroller with at least 2 kB of Flash memory, 128 bytes RAM and a clock rate of at least 12 MHz.

Taken from ATTiny85's Datasheet:

  8K Bytes of In-System Programmable Program Memory Flash
  512 Bytes In-System Programmable EEPROM (enough for third-two 16-byte keys)
  512 Bytes Internal SRAM

Looking forward to trying it out :)


ERROR on SIM900AT comand HTTPDATA (POST method) Good day community, I have a project which is VEHICLE GPS Tracker and I'm using Arduino Mega, NEO GPS6MV2 and SIM900. I'm using SIM900 to send the GPS coordinates on a web server. I'm using the POST method and SIM900 is capable of this by using AT commands. I will also save the coordinates on a MySQL database.
My problem here is I can't send the data on the MySQL database. As you can see on the latter part of the commands, it response "ERROR".  That's why the coordinates failed to enter on the database. This is what I have on the database: What do you think is the problem here?

If you say you are going to send 90 characters you must send 90 characters. No more, no less. I count 70 there.
You have to send them immediately the modem responds DOWNLOAD otherwise it times out (10 seconds) and you get ERROR. It looks to me like you're not sending anything (except maybe a blank line) for those 10 seconds and only trying to send once it has errored.


Formula for current through shift register Hi

I am programmer that just started learning electronics and Arduino. I built this simple circuit on Autodesk Circuits earlier. Originally I used 220 ohm resistors. Then when I ran the simulation and turned on more than 4 of the leds the simulator warned that I exceeded the max current for the shift register.

I then upgraded to 560 ohm resistors which solved the problem.

What I would like to know is how can I calculate the current through the shift register for each n-number of leds I turn on? That way I can calculate the right resistor that I need before I burn out my electronics.

Thanks for the help on this.

It's just N×IL+IQ where N is the number of LEDs, IL is the current through each LED and IQ is the current the shift register needs to operate (quiescent current).

The current through each LED is just (VIN - VLED) ÷ R, where VIN is 5V, VLED is the forward voltage drop of the LED, and R is the value of your resistor.

So you can combine it to be a single formula, if all your LEDs are the same and your resistors are the same, to:

IT = N × ((VIN - VLED) ÷ R) + IQ


Freeze with VCNL 4000 Proximity Sensor I've the VCNL 4000 Proximity Sensor I use some sample code and at the very beginning
the following code hangs (never finishes)
 readVCNLByte(0x81); is called

Can this problem be caused because the contact of the pin isn't very good.
I only but the part with pins in the sensor without to solder it.
Is it likely that this may be the problem ? I have not many experince with solder and the sensor is really small so i'd like to avoid it for first tests ;)
Here the code. The last output in the Serial window is "pre product"
  Serial.println("VCNL");
  Wire.begin();
  Serial.println("pre product");
  uint8_t rev = read8(VCNL4000_PRODUCTID);
   Serial.println("post product");
  if ((rev & 0xF0) != 0x10) {
    Serial.println("Sensor not found :(");
    while (1);
  }

You really can't expect this to work unsoldered. The contacts will be at best intermittent, and poor contact. Even a 'dry joint' where the pin is mostly surrounded by solder doesn't work well, these are the ultimate examples! You could however use an edge-connector, if you can find one; not something you see often nowadays.


SoftwareSerial response is semi-gibberish using ESP8266 I have a working SoftwareSerial connection to my ESP8266 module on my Arduino UNO board. However, the response I get from the ESP8266 using the SoftwareSerial library is semi-gibberish.

So I do get the correct response, but some characters are changed.
For example when I ask the IP of the module, it sometimes returns the right IP, but most of the times just alters the IP, for example 092.168/123.5.

So what am I doing wrong?

This is the code I'm currently using:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");
}

void loop() {
  if (esp8266.available()) {
    Serial.println(esp8266.readStringUntil("\n"));
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

When I send the AT command, I sometimes get OK□ or some other extra random characters.

So how do I make the SoftwareSerial show (or receive) the correct response?

Try lowering your baudrate to 9600.

https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/


Writing to flash memory fails with Optiboot I am having some issue writing to flash memory on Arduino Uno.

I burned the optiboot bootloader that ships with the IDE 1.8.3 to the chip, then uploaded the test_dospm sketch to write content to flash memory but appears to reset the device instead.

Any idea why this might be happening?

The bootloader which ships with Arduino IDE is version 4 which was already in the Uno from factory. To use the do_spm function you need Optiboot 8 build with this support enabled. It is not enabled in the default builds, because it doesn't fit in the usual Optiboot size for Uno.

The hex file of the bootloader is here. Simply replace the hex file in AVR boards package with this one.


How does one wire OV7670 camera with Arduino Due? The parts that I want to interface together are:

Arduino Due
OV7670 Camera Module
3.5" TFT Touchscreen LCD (uses MCUFRIEND_kbv library)

My goal is to get the video feed from the camera to the LCD screen. Any help will be appreciated.

I am working with small project same in little bit like what you trying to do..
starting with..
1- Arduino UNO + OV7670 + 2.4" TFT LCD (I got not clear live Image)..
so I made some changes..
2- Arduino DUE + OV7670 Live Image (still working with, having problem in reading Image) want to compile the result Image (convert it to text) then sending the result to (3) by serial Port
3- Arduino UNO + 3.5" TFT LCD (it works)..
by the way  Arduino UNO + OV7670 Live Image (worked perfectly), but I am trying to get same project using DUE.. (faster speed & maybe could deal with Image too..)
here link of how OV7670 work with Arduino DUE..
https://www.instructables.com/How-to-Connect-OV7670-to-Arduino-Due/
.....


How to read main code inside main code in Arduino? How can I read the hex code of the main programme stored inside flash memory inside my running Arduino programme?

So far I am able to read the Flash at any given address by using PROGMEM

unsigned int displayInt;
int k;    // counter variable

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(k = 0; k < 5; k++) {
    displayInt = pgm_read_word_near(k);
    Serial.println(displayInt);
  }
}

void loop() {
}

The output is

37900
13716
53
3072
37900

But this not hex code.

I am implementing the OTA (over the air) feature. I will get the new version of a code from GPRS. It will be huge code so I will write it to flash by using the custom bootloader mentioned in this thread. I am able to write to the flash memory. Now I would like to read the data from flash. To begin with I would like to read the main programme inside my main programme.

Interesting. If you want hex you have to tell it to print in hex. If I change your display line to:

Serial.println(displayInt, HEX);

Then I get:

940C
3594
35
C00
940C

Compare this to what the decompiled file looks like:

   0:   0c 94 35 00     jmp 0x6a    ; 0x6a <__ctors_end>
   4:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>
   8:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>

If you take the endianness into account (you are reading words, not bytes) then it is the same.

If you change it to read bytes it looks better:

void setup() {
  Serial.begin(115200);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(int k = 0; k < 12; k++) {
    byte c = pgm_read_byte(k);
    char buf [3];
    sprintf (buf, "%02X", c);
    Serial.println(buf);
  }
}

void loop() {
}

I increased the baud rate to 115200. I'm always puzzled when people use 9600 baud. Do you hanker for the olden days, when 9600 baud modems were the fastest you could get?

That gives this result:

0C
94
35
00
0C
94
5D
00
0C
94
5D
00

As you can see, it is exactly correct.


Can a 12V sensor connected to a 5V output signal of an Arduino Uno I am doing a project for object detection. But my problem is I'm using a 12V photoelectric OMRON sensor to connect with 5V Digital PWM port 3 on Arduino using normal coding. Do I need an extra circuit to step down the voltage to 5V? Can it work because the only connection between the sensor and Arduino is the output signal, the VCC and Ground are from external power. Link to the datasheet Please help me

My favorite solution for such an application is to use an optoisolation module. In this case, the signal can have a voltage of 12 V and the output of the optoisolation module can be connected to the input of the Arduino, where the input is configured as INPUT_PULLUP.
Example of the optoisolation module:

In this way it is possible to connect other types of sensors and switches and the solution is universal also for other development kits, e.g. with 3V3 logic.


What functions are disabled with noInterrupts()? The Arduino page for noInterrupts() says:

  Some functions will not work while interrupts are disabled, and incoming communication may be ignored.

While it may not be possible to give a complete listing of what would be disabled, having an incomplete list of functions which definitely are disabled would be useful.

I was thinking of calling a DHT sensor library which internally uses millis() while interrupts were disabled to avoid both bit banging and servicing interrupts simultaneously if possible (the interrupt would hold and be processed after).

Which functions are definitely disabled when interrupts are disabled?

What about incoming communication? My guess is that it would be slightly worse on the ATmega32U4 (eg Leonardo) as the one processor does USB and everything else as well.

From what I found turning off interrupts will definitely disable incrementing values of micros() and millis() This means that also every method that uses them like delay() will also not work correctly.

Of course manually attached interrupts using attachInterrupt() will also not work as intended.

According to comments by @Juraj Things that also will not work are Serial interrupts. Also libraries like Wire require interrupts for their logic.

EDIT: @EdgarBonet You are right, I removed incorrect info.


Correct position for buttonState in my FSM I wrote a FSM with the help of some tutorials through out the world wide web and so far it does what I want to do with it.

But one thing that is not the way I want to be, is to exit the state noLightPause during the non blocking delay with the button to enter the yellowLight state again.
I cannot figure out where to put the buttonState inside my code, if it should be that simple to exit that state, because it was hard enought for me to get my machine going to that point :D.

Do not get confused, I soldered the button from ground to the pin, so LOW gets the input :).

Hope you guys can help me with that problem to get me further with my machine.

Thanks in advance for all your help, here is my code:

#include <FastLED.h>

#define NUM_LEDS 16

CRGB ledStrip [NUM_LEDS];

const int buttonPin = 4;
const int ledStripPin = 8;
const int ledOnBoard = 13;
const int interval = 100;

int buttonState = 0;
int lastButtonState = 0;

int ledOnBoardState = LOW;

unsigned long previousMillis = 0;
static unsigned long noDelayPause;

enum statusType {whiteLight, yellowLight, noLightPause, noLight};

statusType currentStatus = whiteLight;

void setup() {

  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledStrip, OUTPUT);
  pinMode(ledOnBoard, OUTPUT);

  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS).setCorrection(DirectSunlight);
  FastLED.show();
}

void loop() {

  //----------------------------------------
  // just to see if the machine is blocking something

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    if (ledOnBoardState == LOW) {
      ledOnBoardState = HIGH;
    } else {
      ledOnBoardState = LOW;
    }
    digitalWrite(ledOnBoard, ledOnBoardState);
  }

  //----------------------------------------

  switch (currentStatus) {

    case whiteLight:
      currentStatus = whiteLightFunction();
      break;

    case yellowLight:
      currentStatus = yellowLightFunction();
      break;

    case noLightPause:
      noDelayPause = millis();
      currentStatus = noLightPauseFunction();
      break;

    case noLight:
      if (millis() - noDelayPause > 1000) {
        currentStatus = noLightFunction();
        break;
      }
  }
}

statusType whiteLightFunction() {

  if (digitalRead(buttonPin) == LOW) {

    return (yellowLight);

  } else {

    fill_solid(ledStrip, NUM_LEDS, CRGB::White);
    FastLED.setBrightness(100);
    FastLED.show();

    return (whiteLight);
  }
}

statusType yellowLightFunction() {

  if (digitalRead(buttonPin) == LOW) {

    fill_solid(ledStrip, NUM_LEDS, CRGB::Yellow);
    FastLED.setBrightness(100);
    FastLED.show();

    return (yellowLight);

  } else {

    return (noLightPause);
  }
}

statusType noLightPauseFunction() {

  fill_solid(ledStrip, NUM_LEDS, CRGB::Black);
  FastLED.show();

  if (digitalRead(buttonPin) == LOW) {

    return (yellowLight);

  } else {

    if (digitalRead(buttonPin) == HIGH) {

      return (noLight);
    }
  }
}

statusType noLightFunction() {

  if (digitalRead(buttonPin) == LOW) {

    return (yellowLight);

  } else {

    return (whiteLight);
  }
}

You should also introduce a button state to have the FSM working as a FSM

 bool buttonState = false;

in the loop you check for the press/release and change the state:

if (digitalRead(buttonPin) == LOW && buttonState == true) buttonState == false;
if (digitalRead(buttonPin) == HIGH && buttonState == false) buttonState == true;

inside your function you only go for buttonState eg

statusType noLightFunction() {
if (buttonState == false) {  // Button is NOT pressed

    return (yellowLight);

  } else {       // Button is pressed

    return (whiteLight);
  }
}

The button acts as a toogle switch as long as you keep it pressed (or released) nothing will change only the state changes caise an action to happen. I personally use "speaking" vars I still know years later so instead of
buttonState I use buttonIsPressed but thats flavour


Compare the new sample in a high sampling rate datalogger I am using sdFat library the analog bin logger example,

Github: SdFat/SdFat/examples/AnalogBinLogger/

The program is working fine and every thing but the thing is, this high speed datalogger uses interrupts and timers to make the ADC work at a pre-determined sampling frequency and it DOES NOT use the normal analogRead ()

What I want is, when the input of some analog pin is bellow a pre-determined value, I want to write HIGH or LOW to some digital pin,
my question is, how can I compare the new sample in the analog bin logger example as I simply want to compare the new sample as in:

if ( analogRead() < 256 ) {// do something}

knowing that there is no analogRead() in the program because it uses timers and interrupts.

In the function

ISR(ADC_vect) {

the variable d contains the current sample:

  // Read ADC data.
#if RECORD_EIGHT_BITS
  uint8_t d = ADCH;
#else  // RECORD_EIGHT_BITS
  // This will access ADCL first.
  uint16_t d = ADC;
#endif  // RECORD_EIGHT_BITS

So you can just "do something" depending on what is in d.  Of course, since this is a timer interrupt you have limited time to do anything, so you need to make sure that whatever you do is fast and efficient - so really you want to be using direct port access instead of digitalWrite().


Arduino RTC - getting the time from RTC after the power is cut off I have a new DS1307 (original, not a Chinese rip off), with a new battery. It is working great, but when I turn the Arduino off (it is currently connected to laptop) and then turn it back on, it resets the time.

The line that sets the time is (in setup part of code):

setDS1307time(30, 42, 21, 4, 26, 11, 14);

So, when the Arduino gets the power back it runs the program again and it overrides the correct current time.

How can I avoid this?

Without knowing the DS1307 well, I think there are two options:

Make the setting of the clock a UI function (you should probably do this in any case since you will want users to have the ability to set the clock). The user would have to initiate the action (and put in the time to set) so there would be no problems the clock getting reset inappropriately, or
Do a check for sanity of the clock before you run that line. You might be able to do that through the clock API (e.g., make a call to check the time, or to get the clock status and see if it makes sense) or you could do it by storing the clock status in nonvolatile memory. The very worst case would be that you store the time of last boot and check that it seems reasonable (e.g., the time you get from the RTC is after the last boot and is within reason – say no more than a month or a year ago). If the time is too far off to feel confident you could issue a "check time" warning.

If you have a network connection using NTP as well as the RTC would be a very smart option. NTP can hold the time within a few milliseconds. The RTC would then provide you with protection against a network outage.

If you are using the Arduino to manage scheduled events one thing you'll want to think about is events that are scheduled in a moment of time that is either "skipped" as you advance the clock or that "repeats" if you set the clock back. One way to handle that is to never "jump" time, but to always just speed it up or slow it down.


My code isn't adjusting the speed of one of the motors and i'm not sure why I'm trying to change the speed of motors depending on the amount of light hitting the LDRs. Here i'm trying to make it so that if the LDR has a high value than another, then the motor associated with that LDR slows down so it turns towards the light.

const int motorDirectionA = 9;
const int motorEnableA = 10;
const int motorDirectionB = 5;
const int motorEnableB = 6;

const int leftLDR = A0;
const int rightLDR = A1;

int motorSpeedA = 250;
int motorSpeedB = 250;

void setup()
{
  Serial.begin(9600);
  pinMode(motorDirectionA,OUTPUT);
  pinMode(motorEnableA, OUTPUT);
  pinMode(motorDirectionB,OUTPUT);
  pinMode(motorEnableB, OUTPUT);

  pinMode(leftLDR, INPUT);
  pinMode(rightLDR, INPUT);

}

void loop()
{
  int ldrReadL = analogRead(leftLDR);
  int ldrReadR = analogRead(rightLDR);
  int leftLDRread = ldrReadL;
  int rightLDRread = ldrReadR;

  digitalWrite(motorDirectionA, LOW);
  analogWrite(motorEnableA, motorSpeedA);
  digitalWrite(motorDirectionB, HIGH);
  analogWrite(motorEnableB, motorSpeedB);

  Serial.print("Left LDR reading: ");
  Serial.println(ldrReadL);
  Serial.print("Right LDR reading: ");
  Serial.println(ldrReadR);

  if (leftLDRread > rightLDRread)
  {
    motorSpeedA = 80;
    motorSpeedB = 210;
  }
     else
     {
        motorSpeedA = 210;
        motorSpeedB = 210;
     }

  if (leftLDRread < rightLDRread)
  {
    motorSpeedB = 80;
    motorSpeedA = 210;
  }
      else
     {
       motorSpeedA = 210;
       motorSpeedB = 210;
     }
}

@Maximillian Gerhardt If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.

If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.

  If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

In code you would express this as

void loop()
{
    int ldrReadL = analogRead(leftLDR);
    int ldrReadR = analogRead(rightLDR);
    int leftLDRread = ldrReadL;
    int rightLDRread = ldrReadR;

    digitalWrite(motorDirectionA, LOW);
    analogWrite(motorEnableA, motorSpeedA);
    digitalWrite(motorDirectionB, HIGH);
    analogWrite(motorEnableB, motorSpeedB);

    Serial.print("Left LDR reading: ");
    Serial.println(ldrReadL);
    Serial.print("Right LDR reading: ");
    Serial.println(ldrReadR);

    //assuming motorSpeedA is the left motor
    // left > right
    if (leftLDRread > rightLDRread) {
        motorSpeedA = 80;
        motorSpeedB = 210;
    } else if( leftLDRread < rightLDRread ) {
        //left < right
        motorSpeedA = 210;
        motorSpeedB = 80;
    } else {
        // left == right
        motorSpeedA = 210;
        motorSpeedB = 210;
    }
}

Also note that this is a quite primitive form of a PID controller. You want to respond to environmental influences in some kind of way, for which a PID is for.

You might find these videos interesting:

https://www.youtube.com/watch?v=1pKJ-KcHZ8g
https://www.youtube.com/watch?v=VVOi2dbtxC0

Edit: The code was fixed, a wrong variable was used (the pin number vs the read value)


what is the difference between providing 7 volts or 12 volts to arduino uno? according to this the recommended input voltage is between 7 and 12 volts.
The question is what is the difference between providing 7 volts(minimum recommended volts) and 12 volts(maximum recommended volts) ?.

The amount of heat dissipated by the voltage regulator.  The higher the voltage you supply the hotter the regulator will get.


Modify the call stack of interrupts on Arduino I'm working with Arduino's libraries. And my interest in the possibility to change the call stack of the SPI interrupt, this because I want: after the interrupt happen, the program could jump to other function and not to the interrupted address.

I mean:
This is the Main code.

void loop ()
{
    func();
}

void func()
{
   // code
   // here happens the ISR interrupt
}

ISR happens inside func()

ISR(SPI_STC_vect)
{
    // code
    // SPDR = 0x00; // MY ANSWER to SPI
    // MODIFY CALL STACK TO GO TO LOOP()
}

Now, after answering the SPI, I want to go back to loop() instead of continue func().

How can I do this?

Thanks for your help.

Arduino is open source, so just modify the ISR to set a global flag when ran. Within func() just check for this flag and return when the condition is met. Little can be offered as little contextual information is given. To modify the stack you would have to work with avr assembly, but either way you must modify the ISR

Something like the following would work, but performance depends heavily on your application.

#define SPI_ISR_RAN 0x00
static volatile uint8_t flagByte;

void loop(){
    func();
}

void func(){
    uint8_t indicator;
    do {
        // Do something

        //Check for SPI condition
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ //Atomic access is required
            indicator = flagByte;
        }
    }while( !(indicator & 1<<SPI_ISR_RAN) );

    ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
        flagByte &= ~(1<<SPI_ISR_RAN); //Don't forget to clear the flag!
    }
}

ISR(SPI_STC_vect){
    // Do ISR necessities

    // Set flag when appropriate
    flagByte & 1<<SPI_ISR_RAN;
}


do i need to also connect GND and 3.3v I am trying to run this code:
https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino

Using an ESP8266 based D1 board and an RFID-RC522.

I am not able to get it to detect the rfid tags ...
the serial monitor just shows:

 ets Jan  8 2013,rst cause:4, boot mode:(3,4)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v00000000
~ld

The "Typical pin layout used" section of the above document does not mention any connections on the 3.3V & GND pins of the RFID-RC522 card.

Does this mean that I do not need to connect them?
Or is is just so obvious that I should connect them that they did not bother to write it in that section?

It is just so obvious that you should connect them that they did not bother to write it down.

The reader needs power. That is taken as read. Without power it can do nothing. Why would they bother to waste time telling you to connect the things that you have to connect regardless? The only things that they tell you to connect are things that are specific to the sketch - i.e., which IO pins to connect to which function on the reader. Power doesn't change - it's the same from sketch to sketch and from person to person. The IO pins do, though, and need to be detailed. Power and ground don't.


snprintf doesn't display float values I don't understand why the formatted string is displaying ?? instead of float values.
My code:
#include <Arduino.h>
#include <Wire.h>
#include "SparkFunCCS811.h"
#include <DFRobot_SHT3x.h>

DFRobot_SHT3x sht3x(&Wire, /*address=*/0x44, /*RST=*/4);

//* Get SHT31 readings

void readSHT(float &temp, float &humid)
{

    DFRobot_SHT3x::sRHAndTemp_t data = sht3x.readTemperatureAndHumidity(sht3x.eRepeatability_High);

    char shtVal[50];

    if (data.ERR == 0)
    {
        temp = data.TemperatureC;
        humid = data.Humidity;

        Serial.println(data.TemperatureC);
        Serial.println(data.Humidity);
    }

    snprintf(shtVal, 50, "Temp = %f  Humidity = %f", temp, humid);
    Serial.println(shtVal);
}

void setup()
{

    Serial.begin(115200);

    //*Initialize the chip
    while (sht3x.begin() != 0)
    {
        Serial.println("SHT31 Initialization Failed");
        delay(1000);

        Serial.print("Chip serial number");
        Serial.println(sht3x.readSerialNumber());

        if (!sht3x.softReset())
        {

            Serial.println("Failed to Initialize the chip....");
        }
    }
}

void loop()
{

    unsigned long newTime = millis();
    static unsigned long oldTime = 0;

    if (newTime - oldTime >= 5000)
    {

        float temp = 0.0;
        float humid = 0.0;

        oldTime = newTime;

        readSHT(temp, humid);
    }
}

& here is the output:
Here is what I get as output:
21.23
41.06
Temp = ?  Humidity = ?

The function readSHT()has no problem displaying the actual values but why the formatted string shows ???. Am I doing something wrong?

The standard avr-libc does not have float support enabled in the printf family of functions. This is because float support would bloat your code massively, and most people don't need it.
It is possible to enable it through some black magic (I don't know what, but someone else may), but in general you don't want to since there are better ways.
Typically you would use dtostrf() to format your float into a char array separately. Or if all you are doing is printing to serial then you wouldn't even format it into a string in the first place.
Serial.print(F("Temp = "));
Serial.print(temp);
Serial.print(F("  Humidity = "));
Serial.println(humid);


USB upload to Pro Micro (32u4) My project is based around the ATMEGA32u4 microcontroller.

I followed the Arduino Pro Micro schematic to design my own board layout and build a custom PCB, soldered on the components.  Then I used the Arduino IDE to successfully upload the Arduino bootloader with SPI.

Currently I can also upload programs to my `32u4 over SPI (using "in-serial programming").  Tested that with Blink.

But I cannot upload programs with the USB, like you would normally be able to do with a Pro Micro.  What things should I look for to debug this?

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\Myname\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

     Using Port                    : COM12
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

The answer, as kindly pointed out by Gerben, is that ISP program upload overwrites the bootloader.

Only upload the bootloader via ISP, then switch to USB for uploading Arduino sketches.


Raspberry Pi Arduino Installer broken I am tring to use ShorTie8's new arduino ARM installer on my RPI B+ by copying this into my terminal:

  cd

  sudo apt-get update -y && sudo apt-get dist-upgrade -y

  wget https://raw.githubusercontent.com/ShorTie8/Arduino_IDE/master/Arduino_IDE_builder.bash

  chmod +x Arduino_IDE_builder.bash

  sudo ./Arduino_IDE_builder.bash

  sudo Arduino/build/linux/work/./arduino

  sudo Arduino/build/linux/work/./install.sh

  sudo apt-get install -y mercurial subversion build-essential gperf bison ant texinfo zip automake flex libusb-dev libusb-1.0-0-dev libtinfo-dev pkg-config libwxbase3.0-dev libtools

But Getting The following Error at sudo ./Arduino_IDE_builder.bash

  echo -e '\n\nConfiguration values\n\n'

  Configuration values

  Stable=1.6.7
  Update_me=yes
  Silence_is_Golden=yes
  echo -e '\n\nSystem check\n\n'

  System check

  ++ date
  + start_time='Sat 13 Feb 11:12:37 GMT 2016'
  ++ pwd
  + Start_Directory=/home/pi
  ++ pwd
  + Working_Directory=/home/pi/Arduino/build
  + echo -e '\n\nChecking for root .. \n'

  Checking for root ..

  ++ id -u
  + '[' 0 '!=' 0 ']'
  + echo 'Yuppers .. :)~'
  Yuppers .. :)~
  + [[ yes == \y\e\s ]]
  + echo -e '\n\nChecking to see if I'\''m update\n'

  Checking to see if I'm update

  git remote update
  fatal: Not a git repository (or any of the parent directories): .git

Instead of manually downloading a file from the github repository, check out the repository properly with git clone 《repository》


Arduino MKR GMS alternative I’m starting on a project about monitoring the soil in the agriculture field and also to visualise the data remotely. The aim of this project is collect the atmospheric data as well as the soil related parameters and then send them to cloud where they’ll be presented on the dashboard. I decide to use Arduino as my development board and Arduino MKR GMS 1400 would be perfect for this project. However this board is quite expensive. So just wondering that are there any alternative I can use for this project
Thank you

There are multiple options for this project as you just want to send/ upload data on the cloud server rather than using Arduino MKR 1400 you can use any of the following.

Arduino UNO with GSM module: As per your requirement you can use Arduino UNO to read the data from the sensor and the GSM module will be used to upload the same on the cloud server. There are various GSM modules available in the market which are cheap also and good. You can also use SIM800 one of the GSM module.

Other GSM modules which you could use can be,
SIM900, Quectel EC-20, Quectel M95. You can also visit SIMCONN website where you can find multiple GSM module options.

You can also use ESP8266 or ESP32 which are Wi-Fi modules but in this case you will require a internet/ Wi-Fi connection near the controller. ESP8266/ ESP32 will read data from the sensors and can also upload the same to the cloud servers. But as you said you are using them to monitor agriculture field it won't be possible to have a Wi-Fi which will cover such long range.

One of the possible solutions to the problem is to use RF-link to transmit data and collect it at a base-station and from the base station you can upload/ send them to the server.

You can also make use of the LoRa Network to communicate along the fields and then receive data from the whole field at a base station and then upload them to the server. But this could be a more expensive solution.


Is there any good working MODBUS TCP master library available for Arduino? I would like to connect with Fronius solar inverter through MODBUS TCP with Arduino to READ and WRITE register values only. I want to set the Arduino as master and the Inverter as slave. I want to use only two functions "Read Holding Registers" and "Write Single Holding Register" function code '3' and function code '6' respectively. Is there any good and working library available for these? And also an example.

Check out the library Modbus-TCP on Github. It has the facility for all the function codes as asked. It has provision for Wiznet W5100 and ENC28J60 Ethernet IC. All tested with Arduino Mega. See the well documented example code for the Wiznet module in the library.

For detailed knowledge about the library, read the index.html inside the doc folder of the library.

Here is an example code explaining a few function codes for the Arduino Mega and a W5100 module.

/*
  This is Modbus test code to demonstrate all the Modbus functions with
  with Ethernet IC WIZNET W5100

  ModbusTCP is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ModbusTCP is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ModbusTCP.  If not, see <http://www.gnu.org/licenses/>.

  Adopted from ModbusMaster for RTU over RS-485 by Doc Walker
  Modified by Narendra Dehury for TCP.
  copyright @ phoenixrobotix.com

*/
#define WIZNET_W5100 1

unsigned int param_value_int[7];
#include <Ethernet.h>

IPAddress ModbusDeviceIP(10, 10, 108, 211);  // Put IP Address of PLC here
IPAddress moduleIPAddress(10, 10, 108, 23);  // Assign Anything other than the PLC IP Address

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1 };

#include <ModbusTCP.h>

ModbusTCP node(1);                            // Unit Identifier.

void setup()
{

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);                      // To disable slave select for SD card; depricated.

  Serial.begin(9600);
  delay(1000);
  Ethernet.begin(mac, moduleIPAddress);
  node.setServerIPAddress(ModbusDeviceIP);
  delay(6000);                                // To provide sufficient time to initialize.

}

void loop()
{
  uint8_t result;

  node.setTransactionID(random(100));           // Not necessary; but good to distinguish each frame individually.
  result = node.readHoldingRegisters(1, 12);    // Read Holding Registers

  Serial.println(result, HEX);
  if(result != 0)
  {
    Serial.println("TimeOut");

    delay(6000);
  }

  int len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));// See the length of data packet received.
  for (byte j = 0; j < len; j++)
  {
    Serial.print(node.getResponseBuffer(j));       // Inspect the data.
    Serial.print(" ");
  }
  Serial.println();
  node.clearResponseBuffer();
  delay(100);

  node.writeSingleRegister(5, 3);                  // Write single register
  Serial.println(result, HEX);
  delay(500);

  for (byte i = 0; i < 5; i++)
  {
    node.setTransmitBuffer(i, (i+100));
  }
  node.writeMultipleRegisters(2, 5);               // Write multiple register
  Serial.println(result, HEX);
  delay(500);

  node.writeSingleCoil(20, 1);                     // Write Single coil
  delay(500);

  node.setTransmitBuffer(0, 0b1010101001010101);

  node.writeMultipleCoils(20, 16);                 // Write multiple coils
  delay(500);
  result = node.readCoils(20, 18);
  len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));
  Serial.println(node.getResponseBuffer(0), BIN);

  node.clearResponseBuffer();
  delay(5000);
}


Starting usb on pro micro after deep sleep (ATmega32u4) I have just started playing with a low power arduino project, and have managed to get the power drain down to about 220uA using powerDown from LowPower.

What I would love to be able to do is start the USB controller and send some data every 8 seconds, but I cant seem to send anything...

Any idea would be greatly appreciated :)

Her is my code:

// **** INCLUDES *****
#include <LowPower.h>

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

void setup()
{
  DDRD = B00100000;       // PORTD5 = TXLED
  DDRB = B00000001;        // PORTB0 = RXLed

  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("Starter...");
  delay(100);
  Serial.end();

  /*
  *  IKKE FJERN DENNE!!! Da greier vi ikke å omprogramere kortet...
  */
  delay(10000);
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("low-power...");
  delay(100);
  Serial.end();
  flash();
}

void loop()
{
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER4_OFF, TIMER3_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART1_OFF, TWI_OFF, USB_OFF);//, USB_OFF);
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  //USBCON &= B11011111; //Disable USB Freeze clock USBCON.FRZCLK
  //USBCON |= B10010001; //SET USB_MACRO_ENABLE_BIT USBCON.USBE

    PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
    while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
    USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
    //-Clear Resume information ???

  flash();

  /*
  * Test USB kommunikasjon :)
  */
  Serial.begin(9600);
  while (!Serial);
  delay(5);
  Serial.println("Hello world!!!");
  delay(5);
  Serial.end();
   PORTD |= B00100000;
   PORTB |= B00000001;
}

void flash() {

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);
}

Best regards, Richard

EDIT

The manual specifies this resume protocol:
Resuming the USB interface (21.13 USB Software Operating Modes)

Enable PLL
Wait PLL lock
Unfreeze USB clock
Clear Resume Informtion

which I have translated into this:

PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
//-Clear Resume information ???

It have no effect whatsoever, have no idea how to clear resume information though...

Also, for the record, the LEDs are flashing happily every 8 seconds.

I found an answer to a similar question here:
https://forum.sparkfun.com/viewtopic.php?f=32&t=39214&start=15#p175098

Note: it requires you to close and open the serial monitor at proper timings.

// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);


Get pin input status without using the arduino library I am not allowed to use the Arduino Library (or any Library) for this program. How would I check the input of a pin?

I found two different functions:

In Arduino.h:

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

Following digitalRead back to pgmspace.h:

#define __LPM_enhanced__(addr)  \
(__extension__({                \
    uint16_t __addr16 = (uint16_t)(addr); \
    uint8_t __result;           \
    __asm__ __volatile__        \
    (                           \
        "lpm %0, Z" "\n\t"      \
        : "=r" (__result)       \
        : "z" (__addr16)        \
    );                          \
    __result;                   \
}))

For the first one, I don't know where bit and value come from and I just don't understand the second one at all.

For reading, e.g., PB2, you would test

PINB & _BV(PB2)

where PINB is the port input register and _BV(x) is a macro defined as
(1 << (x)).

C.f. the datasheet for the relevant port names.

See also the Arduino tutorial on
port manipulation.


Setting a number inside a struct causes timer to misbehave The following code:

struct l{
    uint8_t pin;
    uint8_t sensePin;
    float brightnessTarget;
    uint8_t PWMvalue;
    uint8_t inc;
};
typedef struct l led;

led* redLed;
led* whiteLed;
unsigned long secondsOfDay = 79140;
unsigned long minutesOfDay = 0;
unsigned int hoursOfDay = 0;
uint8_t interrupted=0;
uint8_t runPID;
int pin13=0;

void setup() {
  cli();
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = OCR1A_val;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  pinMode(13,OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  sei();
}

void loop() {
  if (runPID){
    PIControl(redLed);
    PIControl(whiteLed);
    pin13 = (~pin13 & 1);
    digitalWrite(13, pin13);
    runPID=0;
  }
}

SIGNAL(TIMER1_COMPA_vect){ //1 second timer fire
  runPID = 1;
}

Toggles a pin. However, if I add:

redLed->pin = 3;
whiteLed->pin = 4;
redLed->sensePin = 0;
whiteLed->sensePin = 1;

In the setup anywhere (before cli(), after sei(), or within the block), the interrupt no longer toggles.

I'm absolutely baffled, and I have no idea what's going on.

Edit: everything but whiteLed->sensePin is fine. That line is what is causing the issue (and I still don't understand)

This:

led* redLed;

defines a global variable implicitly initialized to zero (i.e. a NULL
pointer). This is an invalid pointer you are not allowed to use until
you properly initialize it.

Here:

redLed->pin = 3;

you are writing to the memory pointed to by this invalid pointer. This
invokes what the C and C++ standards call undefined behavior. What
that means is that, according to the definition of the C++ language, the
behavior of your program is not defined. In other words, anything can
happen. Typically you get a program crash, but even that behavior is not
guaranteed.

Do not ever access memory through an invalid pointer.


How to Write a function or Loop or program to receive fixed number of Integers or characters over Serial? I am want to receive a 5 character hexadecimal input from user over serial port of arduino Uno.

int count = 0;                                    // count = 0
char userInput[5];

void setup()
{
  delay(1000);
  Serial.begin(19200);                            // begin serial port with baud rate 9600bps

}
void loop()
{
  if (Serial.available() > 5)
  {
    Serial.read();
  }

  else if (Serial.available() < 4)
  {
    Serial.read();
  }

  else if (Serial.available() == 5)
  {
    for (int i = 0; i < 5; i++)
    {
      userInput[i] = Serial.read();
    }

    Serial.print("User Input - ");
    Serial.println(userInput);
  }

  delayMicroseconds(10000);
}

But I want to discard the input if user inters less than 5 characters or more than 5?

Since the Serial.flush() have a different meaning now, I can not clear the buffer if user enters less than or more than 5 characters and the characters gets added to next input.

e.g. If I upload above program and entered input in following sequence:

abcde
abcd
abcd
abcd
abcd
abcdef
abcde

I got the following output:

User Input - abcde
User Input - dabcd
User Input - dacbd
User Input - bcdef
User Input - abcde

Two invisible characters appear in output which are not visible but when I copied the output from serial monitor but these characters appear when I copy paste the output into Text Editor.

So How can I modify the program to receive only 5 hex character input from user (Which user will input from Hex Keypad)? And if user enters more or less character I want to clear the input buffer for next user input so that characters from previous input doesn't get added to next one.

As noted in the comments, since your prototype is receiving data from the serial port, you need some way for the user to indicate to the program that they are finished entry, since a 4-character entry is a necessary point along the way to a 5-character entry.

What you are doing now, by checking if Serial.available()>5 is letting the serial buffer hold 6 characters before you read from it (note: 5 is not >5), but then your else statement:

else if (Serial.available() < 4)
{
  Serial.read();
}

Clears out the buffer (Serial.read() removes one character from the buffer), so you will never get to 5 characters anyway, unless all 6 characters come in between runs of loop(), which is not likely at 19200 baud.

Not to mention that while data is sitting in the buffer, you don't know what it is and can't act on it. It is better to use the buffer as intended, which is to allow the Arduino to collect serial data, even while your program is working on other things, and then grab any pending data from the buffer as the program loop()s.

You have declared the userInput[5] array to hold user input, but note that if you only declare it at 5 chars long, it cannot hold the null-character terminator that is standard for C-style strings. It would be better to declare this as:

char userInput[6];  // Holds 5 user characters, plus null terminator.

In your loop(), you should copy out the contents of the buffer into your userInput, check the length or for a termination character, such as a carriage return or newline (i.e., pressing 'Enter' on the serial terminal.) and act accordingly. Here is an example, showing just the relevant bits for the user input and hiding the rest in [...]:

char userInput[6];  // Holds 5 user characters, plus null terminator.

void setup() {
  userInput[0] = '\0';  // Initialize string to empty
  Serial.begin(9600);
}

void loop() {
  uint8_t processInput = 0;   // Set to 1 if we have complete entry
  while (Serial.available()>0) {
    char input = Serial.read();
    if (input=='\r' || input=='\n') {
      // Have received a terminating character,
      // Flush the rest of the buffer
      while (Serial.available()) {
        Serial.read();
      }

      processInput = 1;

    } else {
      int s_len = strnlen(userInput, 5); // Get current length of userInput
      if (s_len<5) {
        userInput[s_len++] = input;      // Append character
        userInput[s_len] = '\0';         // Null-terminate string
      } else {
        // User has entered more than 5 characters and no terminating
        // character; here is where you can decide to clear the userInput
        // and start over, or just drop the first character and care
        // about the most recent 5, etc. Here, we will clear the input
        // and start over; The 6th character is dropped/ignored and
        // user input starts again. It is as though the 6th character
        // entered is like pressing Enter, but it does not process
        // the incoming data, beacuse 6 characters is an invalid input.
        userInput[0] = '\0';
        s_len = 0;
        processInput = 0;
        // Invalid input
        Serial.println("Error: invalid data");
      }
    }
  }

  if (processInput) {
    Serial.print("User input - ");
    Serial.println(userInput);

    if (strnlen(userInput, 5)==5) {
      // Do something **here** with the input string!!

      // Reset input string
      userInput[0] = '\0';
    } else {
      // Invalid input
      userInput[0] = '\0';
      Serial.println("Error: invalid data");
    }
    processInput = 0;
  }
}

Note, this code is not fully tested and may contain bugs. In particular, I did not intensely check if the while (Serial.available()) {} properly handles a lot of extra data.

One final note, you don't need the delay() with this code.

EDIT:

I tried the sample code above and it had a couple of bugs, one of which was that after a successful 5-digit entry, the input string was not reset to empty. I have now updated the code and it's a valid, working program to receive and process a 5-character input on the serial port and to toss an error if fewer than 5 or more than 5 characters are entered. Entry is terminated with a carriage return or newline (enter key).


EEPROM - Storing Static Data I'm trying to store four items to EEPROM.  I can do one item no problem, I just don't know how to make the jump to multiple items.

My code:

#include <EEPROM.h>
char sgrpID[31] = "acpilot's arduino";
char addrID[51] = "123 any street rd";
char zpcdID[11] = "12345";
char gwayID[31] = "what a cool toy!";

void setup()
{
  Serial.begin(9600);
  for (int i = 0; i < 6; i++) {
    EEPROM.write(i, sgrpID[i]);
    EEPROM.write(i, addrID[i]);
    EEPROM.write(i, zpcdID[i]);
    EEPROM.write(i, gwayID[i]);
  }
}

void loop() {
  Serial.println(sgrpID);
  Serial.println(addrID);
  Serial.println(zpcdID);
  Serial.println(gwayID);
  delay(99999);
}

I want to be able to call on these in a sketch and post them to a db along with dynamic data of some flavor (TBD).

Am  on the right path?  Any help, corrections, or general guidance is appreciated.  I've moved beyond the "novice" stage of basic Arduino programming but an completely new to EEPROM.  If in doubt, SLOWER AND LOUDER is by far the best way to communicate key EEPROM concepts to me.

I have reviewed the Arduino EEPROM library but I was reading Greek.  I keep reading it and I'm sure at somepoint I'll recognize a pattrn and start to "get it."

Some things I noticed in your code:

You are writing everything to the same address (is that intentional?)
You are only writing the first 6 six bytes of your arrays (I am pretty sure that is intentional)
You are declaring these arrays to be bigger than what you are putting in them (this is again probably intentional, but I am just guessing)

So here is an example of how I would handle the eeprom:

#include <EEPROM.h>

char sgrpID[31] = "acpilot's arduino";
char addrID[51] = "123 any street rd";
char zpcdID[11] = "12345";
char gwayID[31] = "what a cool toy!";

//These are the definitions of what goes where in memory
//You do not want everything to have the same number
const size_t SGRP_ID_EE_START = (0);  //Zero is good address to start
//To get the next address we merely add the size of the first item
//With the address of the first item
const size_t ADDR_ID_EE_START = (sizeof(sgrpID) + SGRP_ID_EE_START);
//And so on and so forth
const size_t ZPCD_ID_EE_START = (sizeof(addrID) + ADDR_ID_EE_START);
const size_t GWAY_ID_EE_START = (sizeof(zpcdID) + ZPCD_ID_EE_START);

//Use this function to write a char array to the EEPROM at
//The address "address" (and the size of "len")
void WriteEepromArray(size_t address,char* arr,size_t len){
  for (size_t x = 0; x < len; x++){
    EEPROM.write(address+x,arr[x]);
  }
}
//Use this function to load your char array with values from
//The EEPROM
void LoadFromEeprom(size_t address,char* arr,size_t len){  //Be aware that this function modifys the data pointed to by "arr"
  for (size_t x = 0; x < len; x++){
    arr[x] = EEPROM.read(address+x);
  }
}

void setup()
{
  Serial.begin(9600);
  //Some sample writes
  //               starting address----array-----size of the array
  WriteEepromArray(SGRP_ID_EE_START   ,sgrpID   ,sizeof(sgrpID));
  WriteEepromArray(ADDR_ID_EE_START   ,addrID   ,sizeof(addrID));
  WriteEepromArray(ZPCD_ID_EE_START   ,zpcdID   ,sizeof(zpcdID));
  WriteEepromArray(GWAY_ID_EE_START   ,gwayID   ,sizeof(gwayID));
  //Use the following to load:
  LoadFromEeprom(SGRP_ID_EE_START,sgrpID,sizeof(sgrpID));
  Serial.println(sgrpID);   //Now it should be loaded

}

The comments I hope help....otherwise comment below with what I left out.


Why the global variables info is not shown for Arduino Due in IDE? If I compile a sketch for the Arduino Mega:

Sketch uses 1804 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 188 bytes (2%) of dynamic memory,
leaving 8004 bytes for local variables. Maximum is 8192 bytes.

If I compile the same sketch for the Arduino Due:

Sketch uses 26304 bytes (5%) of program storage space. Maximum is 524288 bytes.

Why is the global variables part not supported for the Due, it seems to me it's quite important (even more than the sketch size).

Or can I enable this option somehow? (and if yes, how)

There is a difference in how the build system calculates the memory size for AVR and SAM. The platform.txt file contains the rule for calculating the size. There is a difference how this is done for SAM (Arduino Due).

The AVR size rules (https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L79) are:

## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*
recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*

And the rules for SAM (https://github.com/arduino/ArduinoCore-sam/blob/master/platform.txt#L91) are:

recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=\.text\s+([0-9]+).*

They may be updated to give more information about the memory size. A good reference on the subject is http://www.support.code-red-tech.com/CodeRedWiki/FlashRamSize which shows that the output from size command for SAM contains much more information.

I assume that from the above information you see how this could be updated.

Cheers!


DS18B20 with only OneWire library Peter Scargill found a way to use DS18B20 temperature sensor without any library and just using OneWire library, and it's amazing how blazing fast it is! (it's an old article from 2013)

#include <OneWire.h>
int16_t dallas(int x,byte start){
    OneWire ds(x);
    byte i;
    byte data[2];
    int16_t result;
    do{
        ds.reset();
        ds.write(0xCC);
        ds.write(0xBE);
        for (int i = 0; i < 2; i++) data[i] = ds.read();
        result=(data[1]<<8) |data[0];
        result>>=4; if (data[1]&128) result |=61440;
        if (data[0]&8) ++result;
        ds.reset();
        ds.write(0xCC);
        ds.write(0x44, 1);
        if (start) delay(1000);
    } while (start--);
    return result;
}
void setup (){
  dallas(A0,1);
}
void loop (){
  float currentTemp = dallas(A0,0);
}

Problem is The accuracy, he converts float to int to get accuracy of 1 degree and it's working just fine.

How can i get accuracy of .5 (or .2?) degree using this semi library?

Actually he isn't really converting float to int. He never uses float since he don't need it. The datasheet of the DS18B20 shows at page 6, how the data is formatted:

The 4 highest bits just resemble the sign bit 11.
The first digit with full degrees is bit 4. Every bit below that has values below 1°C

So the data bytes 0b1111100001010000 will represent a temperature of -123°C and 0b1111100001011000 -122.5°C.

The author from the link then shifts this data 4 bits to the right, so that all bits representing values under 1 vanish. You can convert the received value per hand to float by also using this.

int16_t whole_degree = (result & 0x07FF) >> 4;
float temperature = whole_degree + 0.5*((data[0]&0x8)>>3) + 0.25*((data[0]&0x4)>>2) + 0.125*((data[0]&0x2)>>1) + 0.625*(data[0]&0x1);
if (data[1]&128) temperature*=-1;

As float does not have the same structure, as the data, we need to convert them. So I calculate first the number of whole degrees analog the your code. Then I add this up with the values of the lowest 4 bits. ((data[0]&0x8)>>3) and it's siblings will be 1, when the corresponding bit is set, and 0, if not.

So you get the full precision of the sensor (12 bits). Please note, that for this to work, you should not configure the sensor to less resolution. In that case you would have to ignore the corresponding lowest bits. But the sensor is in 12 bit mode at power up anyway and your code does not configure it otherwise.

Note: I'm unsure about the line result |=61440; in the original code. This sets the 4 highest bits of a 16 bit value to 1. I don't see, why this should be correct here, since a normal 16bit integer does only have 1 sign bit. In my understanding the original code would lead to false readings (way off), when reading temperatures below zero. I instead simply multiplied the resulting temperature with -1.

The whole code would look like this (I also added the statement for printing out the pure received data as binary, as I requested it in my comment. These statements are currently commented out):

#include <OneWire.h>
float dallas(int x,byte start){
    OneWire ds(x);
    byte i;
    byte data[2];
    int16_t result;
    float temperature;
    do{
        ds.reset();
        ds.write(0xCC);
        ds.write(0xBE);
        for (int i = 0; i < 2; i++) data[i] = ds.read();
        result=(data[1]<<8) |data[0];
        // Here you could print out the received bytes as binary, as requested in my comment:
        // Serial.println(result, BIN);
        int16_t whole_degree = (result & 0x07FF) >> 4; // cut out sign bits and shift
        temperature = whole_degree + 0.5*((data[0]&0x8)>>3) + 0.25*((data[0]&0x4)>>2) + 0.125*((data[0]&0x2)>>1) + 0.625*(data[0]&0x1);
        if (data[1]&128) temperature*=-1;
        ds.reset();
        ds.write(0xCC);
        ds.write(0x44, 1);
        if (start) delay(1000);
    } while (start--);
    return temperature;
}
void setup{
  //Adding Serial.begin(9600); for printing the received bytes here
  //Serial.begin(9600);
  dallas(A0,1);
}
void loop{
  float currentTemp = dallas(A0,0);
}


Cannot receive and transmit at the same time I have 2 arduinos I made some code and I managed to send from the first to the second and from the second to the first with two different pairs of code. What I want to do is to send from the first to the second and from the second to the first with no code change. I added in my current code some monitoring commands but what I can see in my Serial monitor is that not all characters are passed thru. I attach something like my code below only more simplified because it is a big project.

1st arduino:

radio.stopListening();
  for(int i=0; i<lnth; i++){
      chartosend=data.charAt(i);
      radio.write( &chartosend, sizeof(chartosend) );
  }
  radio.write(&endchar,1);
radio.startListening();
  if(radio.available()){
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    //Serial.println(inchar);
  }

2nd Arduino:

radio.startListening();
  if(radio.available()){
    radio.read( &data, sizeof(data) );
    inradio+=data;
  }
radio.stopListening();
  if(analogRead(0)>20){
     for(int i=0; i<6; i++){
      chartosend=pir1.charAt(i);
      radio.write( &chartosend, sizeof(chartosend) );
    }
    radio.write( &endchar, sizeof(endchar) );
  }

Where is the problem and how I could solve this?

I dunno know about the radio interface you are using. But I can see something which will break your code for sure.

The sections, where you read data from the interface on both Arduinos are passed without a delay, interrupt, polling loop or something else.

Which means: your "read" code section is in no way synchronised with the write code section on the other arduino and vice versa. At the point when you call the function "radio.available()" (which probably tests if there's any data available at the receiver fifo) there is possibly one or any number of bytes available, but not necessary the whole transmission from the other arduino. You have to make sure — somehow — that the transmission is finished, before you can call it a day and go on with processing the received data.

To do this you have to

synchronise the beginning and the end of your transmissions on both Arduinos
poll the data on the respective receiver side, until you are satisfied
or run into a timeout you have to apply in case there's a byte or more lost by chance.

I hope this gives you a little bit of orientation where to start.


Power consumption for arduino I am using an Arduino SMD UNO r3 board ,and connecting thermal sensor MLX 90614 , wifi modem ESP 8266 , a buzzer and an arduino based sound sensor .
How much power distribution will it require ?
What should be the capacity of the battery ?

You need to create a power budget. This means pouring through the datasheets of each component and finding the max and nominal current consumption info and then summing it up. From this, you should be able to come up with a battery capacity value.
There is a great article called "What is a Power Budget" written by Chris Gammell (from The Amp Hour) that goes into power budgets in more detail. Here are the key items from that page:

So what is a power budget? Much like a budget you might have for your personal finances, a power budget shows where all the possible power will be used by a device to by breaking it down into components and categories.
As you can see, not much more is required than your datasheets and a spreadsheet type program. ... The first two columns (A&B) are simply identifiers to allow you to recognize which components correspond to which set of data. The next two columns (C&D) determine the multiplicative factor. If you have 5 components that contain 4 op amps per, then that will consume 20x the power of a device that has the same supply current needs but only one op amp per and there is only one on the board.  The next two columns (E&F) show how much current each individual component contributes and then the sum of all the components of that type contribute. Note that this parameter on a data sheet would be listed as “supply current” or “active current”. The “quiescient” number is when the device is in a resting state and will likely be much less than the active number (and not relevant for this example). Finally, the supply voltage is listed (in column G) to calculate power (using the formula P=I*V) which is listed in column I per device. All of these contributors are summed, an efficiency is estimated (I assumed a poor efficiency linear type supply) and the total power required input to the device is given. Further calculations could result from much of this initial data.


What is the purpose of putting a data type in brackets before a calculation? sorry for the nooby question but I can't seem to find the answer to this anywhere, probably because I'm unsure what to search for with this problem!
I'm just wondering what the reason is for including a data type in brackets before a calculation takes place? In the code below, all the variables have already been declared at the top of the program, so I'm unsure what the reason / effect of including the (float) has. acc_y and angle_pitch_acc have been declared as floats and acc_total_vector has been declared as long
angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;

Thanks!

It's called casting. It changes the data type temporarily. In this instance it's being used to change an integer type into a floating point type, which means that the whole calculation is done using floating point mathematics. However acc_y is supposedly already a float, but maybe it wasn't at the time the author wrote that line. Maybe things, as they often do in a program, evolved. Only the author knows.


SoftwareSerial receives beginning of data mangled I'm using SoftwareSerial to communicate with a Sigfox module. Documentation for the read function assigns its value to a char. However using it I get mangled characters and also have read in other question that I should assign it to int as it can return -1 for no data and [0;255] for received character.
This is my basic troubleshooting example:
#include <SoftwareSerial.h>
SoftwareSerial Sigfox(11,10);

void setup() {
  Serial.begin(9600); // HW serial
  Sigfox.begin(9600); // SW serial --> sigfox
}

void loop() {
  if(Sigfox.available()) {
    int c = Sigfox.read();
    Serial.write(c);
  }
  if(Serial.available()) Sigfox.write(Serial.read());
}

When c is char, I get -5 instead of OK. Also other output is mangled. When c is int, it receives the data OK.
My question is - why they use char in the example in documentation? Why is char signed in Arduino?
I want to read the entire line of text from serial port and store it into array. How to define that array? I have found an example on web that uses char buffer[32], but then again I get mangled data when I assign to it. If I use array of byte/int/unsigned char, I can't print it as Serial.write(SF_buffer); won't compile because of no matching function for call to 'write(unsigned char [32])'.
So what variable types should I use to receive and store the text from SoftwareSerial correctly?
Here is my function for reading the whole line:
unsigned char SF_buffer [32]; // max length of line to read from serial
bool SigfoxReadine() { // return true when whole line was received and is in buffer
  static int SF_cnt=0;
  while (Sigfox.available()) {
    int c = Sigfox.read();
    SF_buffer[SF_cnt++] = c;
    if ((c == '\n') || (SF_cnt == sizeof(SF_buffer)-1)) {
       SF_buffer[SF_cnt] = '\0';
       SF_cnt = 0;
       return(true);
    }
  }
  return(false);
}

UPDATE:
Trying readBytesUntil - the same result, but I have found that issue is only when I send data to module using println as in this example:
#include <SoftwareSerial.h>
SoftwareSerial Sigfox(11,10);

void setup() {
  Serial.begin(9600); // HW serial
  Sigfox.begin(9600); // SW serial --> sigfox
  Sigfox.println("AT$I=11");
}

void loop() {
  if(Serial.available()) Sigfox.write(Serial.read());
  SF_read();
}

void SF_read() {
  if (Sigfox.available()) {
    char buff[32];
    int l = Sigfox.readBytesUntil('\n', buff, sizeof(buff));
    if (l > 0 && buff[l - 1] == '\r') {
      l--; // to remove \r if it is there
    }
    buff[l] = 0; // terminate the string
    Serial.println(buff);
  }
}

The response to first command (in setup) is mangled. The response to the same AT command manually written into serial monitor (and sent to module via Sigfox.write in loop) is OK.

ӂ*⸮FBB1E27EE7
3430E2FBB1E27EE7

Also maybe I'm little lost in when to use print and when write... Example says to use write() to send back the char that was read(). Juraj's response uses println() to print the null-terminated buffer. What is the difference when I write/println this buffer?

I like the readBytes or readBytesUntil function. It doesn't end on a small gap between received bytes and fills the buffer. This functions are blocking with timeout, but if read some other device the input is usually fast and terminated reliably.

example for readBytesUntil:

if (Serial.available()) {
  char buff[32];
  int l = Serial.readBytesUntil('\n', buff, sizeof(buff));
  if (l > 0 && buff[l - 1] == '\r') {
    l--; // to remove \r if it is there
  }
  buff[l] = 0; // terminate the string
  Serial.println(buff);
}


Calculating Angles from MPU6050 I've been playing with a GY521 breakout recently with the MPU6050 chip on it, though i've hit a bit of a problem that I can't quite work out

I know when I rotated the board I rotated ~90 degrees about the Y axis, and using the sensitivity numbers from the datasheet (131) and integrating i've managed to get something that looks believable from the gyroscope, but am having problems with the accelerometer.

From a number of sources, this being one of them, I've managed to get the three equations seen on here, however when I apply them to either the raw or scaled data (as they're scalers is shouldn't make a difference?) I get a set of data that varies from 0 to 90, but only on the X and Z axes, while nothing happens to the Y.

Updated to include code:

#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

MPU6050 accelgyro;

int16_t ax, ay, az, gx, gy, gz;

double timeStep, time, timePrev;
double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

int i;
double gyroScale = 131;

void setup() {

  Wire.begin();
  Serial.begin(9600);
  accelgyro.initialize();

  time = millis();

  i = 1;

}

void loop() {

  // set up time for integration
  timePrev = time;
  time = millis();
  timeStep = (time - timePrev) / 1000; // time-step in s

  // collect readings
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // apply gyro scale from datasheet
  gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;

  // calculate accelerometer angles
  arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
  arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);

  // set initial values equal to accel values
  if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
  }
  // integrate to find the gyro angle
  else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
  }

  // apply filter
  rx = (0.1 * arx) + (0.9 * grx);
  ry = (0.1 * ary) + (0.9 * gry);
  rz = (0.1 * arz) + (0.9 * grz);

  // print result
  Serial.print(i);   Serial.print("\t");
  Serial.print(timePrev);   Serial.print("\t");
  Serial.print(time);   Serial.print("\t");
  Serial.print(timeStep, 5);   Serial.print("\t\t");
  Serial.print(ax);   Serial.print("\t");
  Serial.print(ay);   Serial.print("\t");
  Serial.print(az);   Serial.print("\t\t");
  Serial.print(gx);   Serial.print("\t");
  Serial.print(gy);   Serial.print("\t");
  Serial.print(gz);   Serial.print("\t\t");
  Serial.print(arx);   Serial.print("\t");
  Serial.print(ary);   Serial.print("\t");
  Serial.print(arz);   Serial.print("\t\t");
  Serial.print(grx);   Serial.print("\t");
  Serial.print(gry);   Serial.print("\t");
  Serial.print(grz);   Serial.print("\t\t");
  Serial.print(rx);   Serial.print("\t");
  Serial.print(ry);   Serial.print("\t");
  Serial.println(rz);

  i = i + 1;
  delay(50);

}

Results:

Strikes me as a little odd, as I was expecting only a rotational change in Y.  Any suggestions?

If I understand your question, the main issues are that the axis don't match up, and z from the accel is not accurate?

with respect to the axis: just swap the values. Rotation math is self-consistent and "correct" in many different permutations. What makes it correct is the set of equations, not any single equation; So, copying equations from one reference frame to another will yield incorrect results even if they were correct originally.

your link addresses this difference:

  "Interpreting the diagram at left is a little tricky, since the tilt
  of the X-axis actually shows rotation around the Y-axis, and the
  angling of the Y-axis shows (negative) rotation around the X-axis."

  ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));

should work better for you

On the second point: accelerometers can't measure yaw, the "z" equation can safely be ignored. that isn't yaw it calculates. Calculating z from the gyro alone should fix your second issue.

Other considerations:

The gyroscope tracking can be made more accurate by using the midpoint rule in your integration
Your code is not integrating the gyroscope's signal with the best estimate of its last position (rx, ry, rz), instead it integrates the gyro with separate numbers (grx, gry, grz). In effect information from the accelerometer is discarded each loop and gyro drift is not corrected for.
Thanks for including those graphs with your code samples =] rotation math is extremely tricky, and graphs help a lot