Grbl on Arduino Uno (Elegoo) with DM542 + nema24 stepper motor not working i've already searched and tried for a quite depressing amount of hours, but am not able to solve this problem:

The parts are the following:
 - Elegoo Arduino Uno, on wich i flashed GRBL
 - 24v Power Supply (wich powers the stepper motor(s)
 - Nema24 3nm stepper motor
 - A DM542 Driver
 - bCNC (exe-build on win7 and win10)

Now, i connected one stepper-driver and stepper-motor as x-axis to the arduino.
The wiring is as following:
 - 5v from arduino to the three + Pins (ENA, DIR and PUL)
 - Pin 2 to PUL, Pin 5 to DIR, Pin 8 to ENA
 - 24V go to + and ground port of the driver, the 4 motor-wires are wired accordingly to the driver

I downloaded GRBL from Github and flashed it to the Arduino (i can run grbl-commands from the serial monitor inside the arduino ide, grbl is unlocked), connected everything and opened up bCNC, searched for the arduino on com-port, wich is shown correctly, and connected wich works fine (in the main screen "connected" shows up).
However when i try to move the x-axis under the control-panel in bcnc, nothing moves, on the screen the numbers change correctly and i get an ok in the logs, but the motor does not move a bit.
I double checked the wiring and tried to write a little program in arduino ide to move the stepper motor without grbl (deleted grbl, wrote a little program wich manually set the intervals ecc), without changing the wiring, that worked...
How can i debug this? Any suggestions?

Thanks in advance!

As you wrote, that you connected the positive pins of ENA, DIR and PUL to 5V, I guess you use the common anode connection scheme from the DM542's datasheet (the driver seems to have optocouplers for the inputs). That would mean the inputs are active low (a Pulse would be a transition from HIGH to LOW and then back to HIGH).

GRBL v1.1 has by default an active high pulse signal:

  By default, a step signal starts at normal-low and goes high upon a step pulse event. After a step pulse time set by $0, the pin resets to low, until the next step pulse event.

(from the GRBL github wiki). I guess, this is the problem. Please try to set GRBL for inverting the pulse signal with $2 (you may well find a corresponding setting inside bCNC.

Be sure, that GRBL is outputting the signals, that your driver is expecting in your connection scheme.


Get ESP32 Chip ID into a string variable (Arduino/C++ newbie here) It's just a few days since I started using Arduino IDE ( programming an ESP32 ). As I learn, I am trying to write some snippets. I wanted to store the Chip ID of ESP32 into a variable (preferably string?) so that I can generate an unique device name. I looked through the ESP32 example programs and came across this program which just prints the Chip ID to the serial console.

  uint64_t chipid;

  chipid = ESP.getEfuseMac(); //The chip ID is essentially its MAC address(length: 6 bytes).
  Serial.printf("ESP32 Chip ID = %04X", (uint16_t)(chipid >> 32)); //print High 2 bytes
  Serial.printf("%08X\n", (uint32_t)chipid); //print Low 4bytes.

Now this works fine but I needed to store it into a variable in the following format "ESP32-0A1B3C4D5E6F" ( the last part of which is the Chip/MAC ID which is 6 bytes ). I went about some reading and currently reading and managed to get this far

  char ssid1[15];
  char ssid2[15];

  uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
  uint16_t chip = (uint16_t)(chipid >> 32);

  snprintf(ssid1, 15, "%04X", chip);
  snprintf(ssid2, 15, "%08X", (uint32_t)chipid);

  Serial.print(ssid1);
  Serial.println(ssid2);

I am trying to read this which seems to be an excellent article on handling Arduino strings but just being a few days old with Arduino/c++ I am having some difficulty in wrapping my head around some of the concepts. I come from a Python, PHP, Javascript background so I guess this is gona take a little bit of a time. I am getting the output that I want in the serial console but now I would need this in this format (MCUDEVICE-0A1B3C4D5E6F). I am sure this code can be written in a much nicer, cleaner manner but for now I need this to proceed with another snippet (which relies on device name in the above mentioned format). Can anyone provide some pointers while I try check out the different ways I could achieve this? I just want to be sure that I am not writing ugly (and dangerous code - crashes, buffer overruns etc). Greatly appreciate any pointers. I guess I am starting to get a little paranoid about handling strings ( especially on low memory devices like typical mcus ).

You can combine all your work into one single line with the snprintf. You aren't limited to just one variable, and you can add plain text:

char ssid[23];

snprintf(ssid, 23, "MCUDEVICE-%04X%08X", chip, (uint32_t)chipid);


Renaming folders in Arduino Uno' SD card I want to rename folders through the SD shield but it does not rename them, because It renames It in another default name
How Can i rename it using the name that I want?

According to this post (https://forum.arduino.cc/index.php?topic=73265.0) this library should be able to rename the folders (https://github.com/greiman?tab=repositories) but there are a lot of posts out there saying they are having problems.

It might be worth checking you can rename them on a PC, there may be problems with name lengths etc that will just complicate matters.


working with ultrasonic sensors I have a little problem dealing with ultrasonic sensor
I want a simple thing , when the sensor read High pulse then after it low pulse , turns on the led
so I try to make it with a 5cm distance and a flag , but it's dose not work
help me please!
    #define echoPin 5
    #define trigPin 7
    int GREEN = 2;
    int YELLOW = 3;
    int RED = 4;
    int pos = 0;
    int flag = 0 ;
    long duration;
    int distance;
    void setup() {

  // put your setup code here, to run once:
    pinMode(GREEN, OUTPUT);
    pinMode(YELLOW, OUTPUT);
    pinMode(RED, OUTPUT);
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
    pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
     }

    void loop() {

    ultra();

    if ( distance <= 5 && flag == 0)
    {//H
      flag = 1 ;}
    } //high pulse (When the distance <=5)

    if ( distance >5 && flag == 1)
    {//L
      red_light(); }

    }//the led should turned on when low pulse appears (When the distance >5)

    void red_light()
    { digitalWrite(GREEN, LOW);
    digitalWrite(YELLOW, LOW);
    digitalWrite(RED, HIGH); }

    void ultra()
    { digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration*0.034/2; }

//this is my code

what actually happens with this code is when I put something near the sensor <= 5 , the led is on without i removed the thing , but I want the led on when I put then remove the thing

Here is my theory on what happens here. You can confirm it by using one of the solutions, that I will explain below.
Currently your code is measuring the distance as fast as it can. The measurement is what takes the longest time in one iteration of the loop() function. Thus you get many many measurements per second. But such distance measurements are always noisy, meaning that the values change randomly in a specific range. When you put the object in front of the sensor, you expect the values to just go down, but actually they are sometimes rising again for 1 or 2 values because of the noise. So the measured values might look something like this (only imagined for making the point; not real values):
5.4 --> 5.2 --> 4.99 --> 5.001 --> 4.89 --> 4.90 --> 4.5

Overall the values go down, but you are comparing always the current value with the fixed threshold of 5cm. When the noise just raises the value again, while you pass 5cm, you will get a false "put and removed again" outcome. At the probability  of the noise doing that is really high, since you measure that often and ultrasonic sensors are not accurate down to millimeters. You could even have the distance pass 5cm multiple times due to the noise.
There are some possibilities to reduce noise or to handle it.

Hysteresis: The first, that I would implement here is hysteresis. That means, that you set the "put" distance different than the "remove" distance. For example you could use 5cm as the distance to register, that the object is put in front of the sensor, but then you wait for the distance to go above 7cm to actually treat the object as "removed". You need to choose the difference between the distances larger than the noise (you can find that out via experimenting). This principle is also used directly with noisy digital signals on the Arduinos input pins. An Arduino Uno will treat voltages above about 2.6V as digital 1 (HIGH signal), and a value below 2.1V as digital 0 (LOW signal) (taken from the datasheet of the Atmega328P, which is the microcontroller on an Arduino Uno, while assuming the controller running on 5V like in an Arduino Uno). In electrical terms this is called a Schmitt-Trigger.
For implementing this, you can just change the threshold values in your if statements.

You can reduce the noise by always measuring multiple times in a row and then calculating the mean value from it. Since a part of the noise is random, you can smoothe out this part a bit through taking the mean. That also reduces your time resolution, but in such a simple use case that mostly doesn't matter that much.

If the reaction time doesn't matter that much, you could reduce the frequency of measurements, so that subsequent distance measurements are already to far away from each other for the noise to create false triggers. This is worse than the other solutions, since it also depends on how fast you put the object in front of the sensor, but it is really easy to implement (just a simple delay() call, or better using millis() like in the BlinkWithoutDelay example for non-blocking code)

I would first implement the hysteresis. Then, if the difference in distances, that you need for it to work good, is too big for you, you can take the mean of multiple value to reduce the noise.

And just for protocol, as it already was said in the comments: Your first if statement has an extra closing bracket } which should not be there.


How to detect pinout at run-time Is it possible to query the pin-out and each pin's attributes at run-time with Arduino?

If not, can it be done at compile-time?

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

I am looking for something like this:

PinProperties props= getPinProperties(pinNumber);

props.supportsDigitalInput();
props.supportsDigitalOutput();
props.supportsAnalogInput();
props.supportsAnalogOutput();
props.supportsPWM();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

etc.

NOTE: This question is similar and I might use the board model to look up a pre-stored pin-out.

pins_arduino.h has some standard macros that can be used for some of what you're looking to do. Using the arduino:standard variant used by Uno for example:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L35:

#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)

Or if you want to use your naming scheme:

#define supportsPWM(p) digitalPinHasPWM(p)

After that it gets a bit more sketchy:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L28

#define NUM_DIGITAL_PINS 20

So, assuming that Arduino digital pins will always be numbered consecutively from 0 and any pin that supports digital input also supports digital output(which is the case in any variant I'm familiar with), you could use that to write some macros:

#define supportsDigitalInput(p) ((p) < NUM_DIGITAL_PINS)
#define supportsDigitalOutput(p) supportsDigitalInput(p)

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L29

#define NUM_ANALOG_INPUTS 6

Could be used to write this macro(with numbering assumption):

#define supportsAnalogInput(p) ((p) < NUM_ANALOG_INPUTS)

Note that this will not work for the An analog pin names(e.g. A0 vs 0).

As for:

props.supportsAnalogOutput();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

I'm don't know of pre-existing code for those. There is probably a way to get it for the first three in an architecture specific manner. The last two you'd most likely need to get the information from datasheets for all of your target microcontrollers and define then using processor specific macros.


Receive an array of characters using SIM900 module I tried to receive an array of characters using SIM900, but I couldn't. I can receive just one character like 'G', but I want to receive a string "abcd". When I used char* to save the SMS, I failed.

Does anyone know how?

My code:

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
    pinMode(3,OUTPUT);
    Serial.begin(19200); // for serial monitor
    SIM900.begin(19200); // for GSM shield
    SIM900power(); // turn on shield
    delay(20000); // give time to log on to network. `
    SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
    delay(100);
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button24
{
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(7000);
}

void loop()
{
    // Now we simply display any text that the GSM shield sends out on the serial monitor
    if(SIM900.available() >0)
    {
        char *in = SIM900.read();
        if (in =="abcd") digitalWrite(3,HIGH);
        if (in == "00") digitalWrite(3,LOW);
    }
}

#use this code and then inform me"
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
    pinMode(3,OUTPUT);
    Serial.begin(19200); // for serial monitor
    SIM900.begin(19200); // for GSM shield
    SIM900power(); // turn on shield
    delay(20000); // give time to log on to network. `
    SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
    SIM900.write(0x22);
    SIM900.write(0x0D);
    SIM900.write(0x0A);
    delay(100);
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button24
{
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(7000);
}

void loop()
{
    // Now we simply display any text that the GSM shield sends out on the serial monitor
    if(SIM900.available() >0)
    {
        char *in = SIM900.read();
        if (in =="abcd") digitalWrite(3,HIGH);
        if (in == "00") digitalWrite(3,LOW);
    }
}


Why are LED 0 and 1 on as well? I was just playing around a bit and ran into a strange problem. LED 3, 5, 6, 9 and 10 are on, as intended. For some reason LED 0 and 1 are on as well. Can someone explain why this is happening?

int ledPins[] = {3, 5, 6, 9, 10};
int pinCount = sizeof(ledPins);

void setup(){
  for (int i = 0; i < pinCount; i++){
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop(){
   for (int i = 0; i < pinCount; i++){
     digitalWrite(ledPins[i], 1);
   }
}

The behaviour of your program is undefined because you're reading past the end of your array.

In C/C++, the sizeof operator always gives you the size of something in bytes. It doesn't directly tell you the number of items in an array. Since int is usually 2 bytes for Arduino programming, the pinCount variable is actually being initialised to 10 (5 items x 2 bytes each).

The result is that each for loop is actually doing 10 iterations. The first 5 iterations are OK, reading correctly from the ledPins array. However, the rest of the iterations are reading whatever data happens to be in memory after that. This means it could be trying to initialise and switch on any pin, potentially including 0 and 1.

I can't guarantee that this is the source of the problem, but it's certainly very important to fix.

The solution is quite easy though. Divide the total size of the array by the size of a single element:

int pinCount = sizeof(ledPins) / sizeof(int);


Burn normal bootloader onto Atmega328P configured to use internal 8MHz clock I have an Atmega328P that I have previously burned with a bootloader configured to use the 8MHz internal clock as described here. I would like to now burn the normal Duemilanove bootloader configured to use an external 16MHz clock onto the chip. However, when I try following the normal procedure, it says "Invalid device signature". I can still upload programs to the chip and they will run, but I would like it to use the 16MHz external clock. How do I do this?

I have a sketch that will upload the Optiboot bootloader - that will work perfectly well on the Duemilanove.

The latest version will be available on GitHub.

This particular sketch is in the "Atmega_Board_Programmer" subdirectory.

You need to run this sketch on another Arduino (like a Uno) and connect it up like this:


Weird characters at the end of LCD I have written a simple sketch that displays temperature and humidity on a 16x2 LCD. Here's its output:

Temp: 28▒▒
Humidity: 68▒▒

The library I used for DHT11 sensor is not from Adafruit. This is the sketch:

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

#define DHT11_PIN 12
#define I2C_ADDR       0x3F
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define SCL_PIN        12
#define SDO_PIN        11

dht DHT;
LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

void setup() {
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
  lcd.begin (16, 2);
  lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home ();
}

void loop() {
  lcd.setCursor(0, 0);
  int chk = DHT.read11(DHT11_PIN);
  lcd.print("Temp: ");
  lcd.println(DHT.temperature,0);
  lcd.setCursor(0, 1);
  lcd.print("Humidity: ");
  lcd.println(DHT.humidity,0);
  delay(2000);
}

The function println usually appends a carriage-return and linefeed to what it prints. It wouldn't surprise me if those two extra characters are its attempt to "render" that.

Try replacing println with print and see what happens.


Declaring literal strings When I want to write a literal string in Python, I use r before the string (or @ in C#):

in [1]: print r'\no esca\pe ch\ara\cters'
out [1]: \no esca\pe ch\ara\cters

In straight c++ I can use R, but in the Arduino IDE, this throws the following error:

Serial.begin(9600);
Serial.println(R"\no esca\pe ch\ara\cters");

<output> invalid character '\'in raw string delimiter

So how do I do the same in Arduino c++?

Raw strings in C++11 must have parens within the quotes in order to allow for a custom delimiter. Since your string lacks those parens, it is not valid.

Serial.println(R"(\no esca\pe ch\ara\cters)");


Getting two Arduinos to talk to each other via an optocoupler I've setup two Arduinos connected via an optocoupler on a breadboard.

One Arduino is a sender and sends pulses to the optocoupler causing the diode to turn on.

When this happens the other Arduino has it's input connected to the emitter. This is interpreted as 1 on the receiver side. Or if the diode is off it's a 0 on the receiver side.

My problem is getting them to sync. I'm currently using delay which I'm starting to realize is a horrible idea since they go out of sync after about 2 characters have been sent. So I wonder are there any better solutions to syncing them?

In order to synchronize two deices transmitting any information you need a CLK signal. CLK stands for clock so basically you send a 1 each time you want to send a bit of data. But in order to do so you need one more wire and a CLK generator (usually the transmitter).
It is described very well in the video of Ben Eater about Reliable data transmission. So I recommend you watching the video since Ben covers a lot of important topics on data transmission and shows a arduino example of how to transmit and receive data properly.


How to read NodeMCU GPIO pin status? I am setting up a page on NodeMCU running as a web server and I want to be able to turn on and off a light based on the url being clicked.

I want to know how I can get the status so that I can set the URL based on the pin status as well as pass  the GPIO pin status in the JSON from the NodeMCU web server.

The code is here.

Independent of the setting of port direction (input or output), pin can be read through the digitalRead():

int pin_light = 3;
int status = digitalRead(pin_light);


To update GPS after every 30seconds using NeoGPS and NeoSWSerial Libray I am using Adafruit Ulitimate Breakout GPS module and NeoGPS and NeoSWSerial Library. Now I want the GPS to update in 30seconds once (1time in 30seconds).After it is updated I want to check the location if new location is equal to old location then it should be updated in 60seconds once(1time in 60seconds).If not the location should be new location. It should display the location every 60seconds.
I tried this flow on Adafruit GPS Library, which works but I want to use NeoGPS library and do the same.
Below is my adafruit library code:

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(11, 10);
Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true
uint32_t timer = millis();
float old_lat,old_lon,new_lat,new_lon;

void setup()
{

  Serial.begin(9600);
  delay(1000);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand("$PMTK220,30000*1F");
  mySerial.println(PMTK_Q_RELEASE);
}

void loop()                     // run over and over again
{
  char c = GPS.read();
  if (GPS.newNMEAreceived()) {
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

if (GPS.fix) {

      old_lat = GPS.latitudeDegrees;
      old_lon = GPS.longitudeDegrees;
      if (timer > millis())  timer = millis();
      if (millis() - timer > 60000) {
        timer = millis();
          Serial.println("Location 1 minute:");
          displaytime();
          new_lat = GPS.latitudeDegrees;
          new_lon = GPS.longitudeDegrees;

          if (new_lat == old_lat){
            new_lat = old_lat;
          }
          else{
            new_lat = GPS.latitudeDegrees;
          }
          Serial.print("Final Latitude: ");
          Serial.println(new_lat,6);

          if (new_lon == old_lon){
            new_lon = old_lon;
          }
          else{
            new_lon = GPS.longitudeDegrees;
          }
          Serial.print("Final Longitude: ");
          Serial.println(new_lon,6);

}
}
}

void displaytime(){
    Serial.print("\nTime: ");
    if (GPS.hour < 10) { Serial.print('0'); }
    Serial.print(GPS.hour, DEC); Serial.print(':');
    if (GPS.minute < 10) { Serial.print('0'); }
    Serial.print(GPS.minute, DEC); Serial.print(':');
    if (GPS.seconds < 10) { Serial.print('0'); }
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    if (GPS.milliseconds < 10) {
      Serial.print("00");
    } else if (GPS.milliseconds > 9 && GPS.milliseconds < 100) {
      Serial.print("0");
    }
    Serial.println(GPS.milliseconds);
}

This is my NeoGPS Library code in which I am using NeoSWSerial:

#include <NMEAGPS.h>
#include <NeoSWSerial.h>// import the serial library

NeoSWSerial gpsPort(11, 10); // RX is 11 (to GPS tx), TX is 10 (to GPS rx)
NMEAGPS gps; // the parser
gps_fix fix; // the struct with all the parsed values

void setup() {

  gpsPort.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS Start");
}

void loop() {

  if (gps.available( gpsPort)) {
      fix = gps.read();
      Serial.println("Latitude:");
      Serial.println( fix.latitude(), 6);
      Serial.println("Longitude:");
      Serial.println( fix.longitude(), 6);

    }
 }

It seems like using the distance feature in NeoGPS would be a good solution for this problem and it should allow you to create a buffer around the original location to filter some of the noise from the GPS readings.
Here's a page with an overview of using Distance in NeoGPS
https://github.com/SlashDevin/NeoGPS/blob/master/examples/NMEAdistance/NMEAdistance.ino


Does SoftwareSerial and the servo library produce interrupt conflicts? I'm planning a project that will involve multiple serial ports and the Arduino servo library. I have heard that this may cause interrupt conflicts. Are there any simple solutions to this

I have heard that this may cause interrupt conflicts.

Indeed. The Arduino can only run one interrupt routine at a time, and:

Servos use rapidly firing interrupts
SoftwareSerial both turns off interrupts while sending (for relatively long periods)
SoftwareSerial uses an interrupt for receiving that runs for an extended period

So really you can't use both together.

Options?

Use hardware PWM to drive the servos (There is a library for this somewhere)
Use an external servo PWM driving board (Adafruit do one IIRC)
Don't use SoftwareSerial.  IIRC AltSoftSerial is better, though no software serial implementation will ever be particularly good.

The underlying problem is that the low-end Arduinos only have on serial port. If you need to use more than one serial port then you really need to be looking at using a different Arduino - one with multiple serial ports.


NodeJS (Galileo-IO) + Arduino sensor library I've done some basic apps with NodeJS firmata where I can connect to my Arduino Uno and do the basics like reading a pin or doing a servo write. I'd like to go further and play with some different sensors from vendors like Adafruit.

Many such sensors appear to come with their own Arduino libraries. Using NodeJS firmata to communicate with my Uno, could I somehow use the sensor libraries? Maybe by including their header files in the Standard Firmata sketch before uploading or...? But then I don't know how I'd get at their methods from my NodeJS app.

Even better, I'd love a little direction on how to go about using an Arduino sensor library in a sketch, and use Galileo-IO to interact with the sensor that way, if possible.

Including the header files for the libraries in the standard Firmata
sketch is only the first step. You will have to also modify the sketch in
order to actually use the libraries. You will have to figure out a way
of interacting with the libraries through the Firmata protocol and
implement this in your modified version of the sketch. You will then
have to modify the JavaScript side to enable these new interactions.
That's where you will write the missing methods


External access to Yun - request not recognised as HTML I am trying to access my Yun externally.

My router recognises traffic on Port XXXXX and forwards it to my Arduino Yun.

I have the below code working internally and now trying to adapt this to work for external (adapted from http://arduino.cc/en/Tutorial/TemperatureWebPanel).

To access the Arduino Yun over the network I type:

http://XXX.XXX.XXX.XXX:XXXXX/arduino/on

When using this script locally, i.e. myArduinoName.local/arduino/on, the onboard light turns on (and off if URL changed accordingly).

Adapting this working code, I have changed to "noListenOnLocalhost" and put in my port number (XXXXX).

The code is reached (see below for the response).

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

// Listen on default port 5555, the webserver on the Yun
// will forward there all the HTTP requests for us.
YunServer server(XXXXX);
String startString;
long hits = 0;

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

  // Bridge startup
  pinMode(13,OUTPUT);
  digitalWrite(13, LOW);
  digitalWrite(13, HIGH);

  Bridge.begin();
  Console.begin();

  // Listen for incoming connection only from localhost
  // (no one from the external network could connect)
  //server.listenOnLocalhost();
  server.noListenOnLocalhost();
  server.begin();

}

void loop() {
  // Get clients coming from server
  YunClient client = server.accept();

  client.println("hello");

  // There is a new client?
  if (client) {
    // read the command
    String command = client.readString();

    command.trim();        //kill whitespace

    client.println(command); // why does this return a full GET request instead of "on"?

    if (command == "on") {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);
    }

    if (command == "off") {
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
    }

    // Close connection and free resources.
    client.stop();
    hits++;
  }

  delay(50); // Poll every 50ms
}

The response I get is (I have replaced my IP and port with X's):

  hello

  GET /arduino/off HTTP/1.1 Host: XXX.XXX.XXX.XXX:XXXXX
  Connection: keep-alive Pragma: no-cache Cache-Control: no-cache
  Accept:
  text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
  User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36
  (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
  Accept-Encoding: gzip, deflate, sdch Accept-Language:
  en-GB,en-US;q=0.8,en;q=0.6

I expected

  hello

  on

So it would seem that because I'm using a different port (other than 80 or 5555) the response is no longer being interpreted as an HTTP request.

I have also tried to edit the uhttpd file via SSH to provide a specific address and port for both my external IP address and my fixed internal IP address.

Then tried to restart the device and also a uhttpd restart i.e.:

/etc/init.d/uhttpd restart

I have attempted to access the URL using my mobile phone (i.e. not on the same network).

Any ideas why my request is not being treated as HTTP?

It works!

The changes to the uhttpd must have done the trick to listen for http traffic on a given IP/port (other than 0.0.0.0:80).

Instead of supplying a port number for the server in the code, I would surmise that the change to the config takes care of it so this, so the port number in code is no longer needed:

YunServer server(XXXXX);

should be changed back to

YunServer server;


esp32 Stack canary watchpoint triggered I am writing a program for esp32 on Arduino IDE. On some point of execution of code for File reading I am facing this exception,
Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered (loopTask)

However on reading few forums I found an answer of increasing the depth of the stack for your FreeRTOS task.
My question is there any other way to handle this exception other than increasing stack size and avoid the program from crashing ?

The best way to handle this exception is to identify what's using so much space on the stack and rewrite your code to avoid it.
The three most common ways you'd use too much stack space are:

large local variables - for instance, declaring a large array as a local variable inside a function, like:

#define VERY_LARGE_STRING_LENGTH 8000

void loop() {
  char my_very_large_string[VERY_LARGE_STRING_LENGTH];

  for(i = 0; i < VERY_LARGE_STRING_LENGTH; i++)
    my_very_large_string[i] = ' ';
}

Local variables are stored on the stack, so a large array of them will use up a lot of stack space.

recursive functions - each time a function recurses it uses stack space. If it recurses deeply enough then it will trample the stack guard and cause this exception. For instance:

int count(i) {
  i--;

  if(i > 0) {
    Serial.println(count(i));
  }

  return i;
}

void loop() {
  count(8000);
}

Each time a function recurses, its return address and its arguments and local variables are all stored on the stack. If it recurses too many times it will use more storage than is allocated to the stack.

mistakes in your code like wild pointers and buffer overruns

void loop() {
  char my_bad_string[10];
  char *wild_pointer;

  // buffer overrun
  for(i = 0; i < 8000; i++)
    my_bad_string[i] = ' ';

  // who knows where this will end up pointing
  wild_pointer += rand();
  wild_pointer = ' ';
}

when you overrun an array on the stack you'll probably overwrite other variables and corrupt their values. Do it enough and you'll hit the stack guard. Remember that C strings (char arrays and pointers) need n+1 characters to store a string of length n because they're terminated with an extra null '\0' character.
If you're using recursive functions, look at ways to limit the recursion or use tail recursion which the compiler may be able to optimize to avoid using excessive stack space.
If you're using large variables, think about why and rewrite your code to be able to use smaller variables. For instance, if you're reading a large file, try to process it a line at a time rather than reading the entire file into memory. If you're downloading large JSON from a web server, try using a streaming JSON parser rather than downloading the entire thing and then processing it.
A mistake in your code will be the hardest to figure out, given that it's a mistake. Be careful about pointers and memory allocation. Although memory is allocated from the heap and not the stack, if it's overwritten or reused after it's been freed using it as a pointer can still cause stack corruption. Also be careful to not return pointers to local variables inside functions:
int *do_not_do_this() {
  int this_will_not_work_the_way_you_hope = 0;

  return &this_will_not_work_the_way_you_hope;
}

can also lead to stack corruption as the space occupied by the variable will no longer be reserved for it and may be used by something else.


Why are Arduino timer registers not 0? I'm trying to use the timer registers to do some timing on my Arduino Mega 2560.

The output of the following code confuses me:

void setup ()
{
    // Set up serial connection
    Serial.begin(9600);
    while (!Serial) {}

    // Print control registers of timer 1
    Serial.println(TCCR1A); // Outputs 1
    Serial.println(TCCR1B); // Outputs 3
}

void loop () {}

Why is TCCR1A equal to 1 and TCCR1B equal to 3? The documentation of the chip says the initial values of the registers are zero. I could of course set them to zero, but I want to understand why it works like this. The values are the same for the other 16-bit timers (3, 4 and 5).

The Arduino core does things at startup. One of those things is to configure the timers ready for PWM operation.

Here's the relevant bits from init() in wiring.c:

    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
#endif

#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
#endif


Arduino Adafruit playground: Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory I've tried installing the Arduino Adafruit playground but came across the same error.

sketch\src\Libraries\Adafruit_Circuit_Playground\utility\Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory

 #include <Adafruit_CPlay_LIS3DH.h>

                                   ^

compilation terminated.

exit status 1

I don't really know what else I can try. I've tried reinstalling the library and
different versions of the Arduino IDE but is doesn't seem to work.

IDE version: 1.8.7

Playground version: 1.8.1

Sorry completely forgot about this post. Apparently I had a folder in my project with the playground library that wasn't updated. When I removed this folder everything worked fine.


Running out of GPIO & looking for suggestions I'm working on a project using a NodeMCU and am quickly running out of GPIO pins. I'm trying to decide which way to go to complete it.

Right now, I have the MCU connected to a MAX31856 PT100 thermocouple (SPI), a PWM output, a transistor (acting as a switch), a single button and a single LED. I'm needing to add at least 2 more of the MAX31856, a display (either I2C or SPI) and a rotary encoder/button.

I've looked into GPIO expanders, but I'm doubtful that the available libraries for the additional hardware will work through the expanders. I have a Mega that will work without a doubt, but then I will have issues with WiFi & MQTT. I looked at the Mega's with onboard WiFi, but I got so confused in reading how to program it, setting the DIP switches, etc that it doesn't seem like a valid choice.

Can anyone offer guidance?

Two main solutions comes to my mind:

GPIO expander (as you mentioned). It is really easy to use them as digital inputs or outputs. So you can connect button, LED, transistor and maybe even display (you did not specified type of the display, so I assume standard LCD 1602 or 2004 display). You can also connect SPI-CS signals to the expander, but this depends on used libraries...
Auxiliary Arduino e.g. Nano. Arduino can be used for measurement of the temperature and other stuff and NodeMCU for communication. In this case you have to implement some kind of communication between these two boards (SPI, I2C or UART).


Fade LED strip using proximity and map() function I'm using a sonar sensor to detect proximity, and need to control the brightness of an LED strip in direct relationship to the distance detected. For example, as someone moves toward the sonar, the strip needs to dim.

I'm using map() to do it now crudely but it's way too abrupt and I'm not sure how best to achieve the effect I'm looking for. Ideally, as the person moves toward the light, it very smoothly fades out in relationship to the person's movement/pace.

Initial thoughts / questions:

-- Can I use a more refined number type to set the LED brightness other than int?
-- Do I need to do something more complex where I detect the delta in the person's movement and use the loop to fade the LED from one value to another? Seems complicated...

Any help / ideas on this would be much appreciated! Existing code is below if it helps.
Claudia

//variables needed to store values
long pulse, inches, cm;

//LED VARIABLES
int frontPin = 6;    // front strip connected to PWN pin 5
long interval = 8000; // interval at which to do something (milliseconds)
int val;

void setup() {
  //This opens up a serial connection to shoot the results back to the PC console
  pinMode(frontPin, OUTPUT);
  pinMode(pwPin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //Used to read in the pulse that is being sent by the MaxSonar device.
  //Pulse Width representation with a scale factor of 147 uS per Inch.

  pulse = pulseIn(pwPin, HIGH);
  //147uS per inch
  inches = pulse/147;
  //change inches to centimetres
  cm = inches * 2.54;

  if (inches < 36){
    detect();
  }
}

void detect(){
  Serial.print(inches);
  Serial.print("in, ");
  Serial.println();

  val = inches;
  val = map(val, 6, 36, 0, 255);

  analogWrite(frontPin, val);
  Serial.print("mapped value is ");
  Serial.print(val);

  delay(500);

}

The biggest problem is that by forcing the code to use integral inches you've restricted it to 31 discrete values. And since the brightness response of a PWMed LED is non-linear you effectively have very large steps in brightness when the LED is dim.

pulseIn() has much more flexibility with regards to its range so use the raw value directly instead of converting it to "pretty" values.

val = map(pulse, ..., ..., 0, 255);


Syntax for stopping loop until the condition has made false I am taking reading from temperature sensor and from that data. I have to control 3 LEDs. Lets consider LED1, LED2, LED3.

If temperature range between 0-20
   I have to HIGH LED2.
   else if temperature range between 20-30
I have to HIGH LED1; HIGH LED3; LOW LED1;

my sketch is something like this:-

while(1)
{
if(temp>=0&&temp<=20)
{
digitalWrite(2,HIGH);
}
else if (temp>=20&&temp<=30)
{
digitalWrite(1,HIGH);
digitalWrite(3,HIGH);
digitalWrite(1,LOW);
}
}

The problem which I am facing is LED1 is continuously ON (which should be OFF), when temperature is between 20-30 because of continuously running loop so, how can I stop loop, once the statement under second condition has executed till the second condition has made false.

Your code doesn't make sense. You have a while (1) statement, which will run forever. Inside the body of that statement, you never change the value of temp.

An Arduino sketch's loop() function runs continuously. You should not have a while (1) loop inside your loop function. You should have a loop function something like this:

void loop() {
  temp = //read a temp value somehow
  if(temp>=0&&temp<=20)
  {
    digitalWrite(2,HIGH);
  }
  else if (temp>=20&&temp<=30)
  {
    digitalWrite(1,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(1,LOW);
  }
}

With that loop function you would fetch a new value of temp on each pass through the loop, then decide what LEDs to light.


Can I apply a Kalman filter to DHT11 data? I want to apply a Kalman Filter to the humidity data which I retrieve of the DHT11.

How can I do that?

Learn about the kalman filter and what it does. It requires a certain understanding of what it is, what it is good for and why you would eventually use it. It seems to me, that at the moment this isn't your strongest topic.

Thereafter, figure out which !multiple! sensor values you have, since only with a "model" and an "observation" a filter of this kind makes sense in the first place.

To specifically adress your question: you can apply any filter to any data. The hidden question, if it makes sense in this case is not trivial to answer, since you didn't exactly provide the vast information. My guess is, you only have this one sensor, and it would be (at this state of knowledge) a reasonable idea to use a bandpass filter of sorts instead.


Fast PWM with Arduino, the inputs outputs don't work Hello to the community!
I am using ATTINY85 and I am programming it through the AVRISP using an Arduino UNO.
This is the code I am using :
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
    PORTB = 0;        //Reset values on port B

    // After setting up the timer counter,
    // set the direction of the ports to output
    DDRB |= (1<<PB1) | (1<<PB0) | (1<<PB3); // PB0, PB1 and PB3

    // PLLCSR - PLL control and status register:
    // PLL is a clock multiplier
    //      - multiplies system 8 MHz by 8 to 64 MHz
    // PLL is enabled when:PLLE bit is enabled,
    // CKSEL fuse is programmed to 0001.  This clock is
    //   switched off in sleep modes!
    PLLCSR |= (1<<PLLE);    // PLL enable

    // Wait until the PLOCK bit is enabled
    // before allowing the PCK to be enabled
    //WaitForPLOCK();
    //unsigned int i = 0;

    while ((PLLCSR & (1<<PLOCK)) == 0x00)
    {
        // Do nothing until plock bit is set
    }

    // Enable asynchronous mode, sets PWM clock source
    PLLCSR |= (1<<PCKE);

    TCCR1 = (1<<CTC1)    | // Enable PWM
            (1<<PWM1A)   | // Set source to pck
            (0<<(CS13))  |
            (0<<(CS12))  |
            (1<<(CS11))  |
            (1<<(CS10))  | // Clear the pin when match with ocr1x
            (1<<COM1A1);
    GTCCR = (1<<PWM1B) | (1<<COM1B1);

    // Set PWM TOP value - counter will count and reset
    //  after reaching this value
    //           OCR1C
    // 100 kHz   159
    // 80 kHz    199
    OCR1C = 199;

    // Enable Timer1 OVF interrupt
    TIMSK = (1<<OCIE1A) | (1<<TOIE1);

    sei();

    OCR1A = 190;  //chaning th FR
}

void loop() {
    PORTB |= (1 << PB3);
    delay(500);
    PORTB &= ~(1 << PB3);
    delay(500);
}

the problem is that when I use the PWM my rest of the outputs do not work . Any idea why is this happening?
I am using the ATTINY CORE library from Spence Konde.

This line:
TIMSK = (1<<OCIE1A) | (1<<TOIE1);

enables a couple of interrupts generated by Timer 1. Whenever you
enable an interrupt source, you should make sure that the matching ISR
has been defined. Otherwise, the interrupt request is routed to
__bad_interrupt(), which by default jumps to the reset vector, thus
resetting your program.


How to automate an electric kettle? I have this tea kettle, which requires pressing two buttons one after the other ("on" and "prog") to start.

I'd like to automate that action (tying it to Tasker on my phone), and am wondering what's my simplest/cheapest option. My communication options are either WiFi or Z-Wave/ZigBee.

I'm assuming Arduino Uno Wifi is an option, but that seems like a huge overkill given how simple what I want to do is. Are there any other simpler/cheaper tools that I could use to do this?

You could use lots of options to control it from Mbed boards to the Uno with a wifi shield, to a raspberry pi to .... the list goes on.  But if it were me I would use the something like the ESP8266 which cost less than $10 usd and can be programmed with the arduino IDE (I'm assuming that is useful given the community this was posted in).  There are also lots of tutorials available online for this kind of thing.

To trigger the button you have two options: a non-destructive one and a destructive one.  For the non destructive one, use something like a solenoid in a custom mount or a servo and small lever arm to push the button.  The benefit to this is that if you change your mind you just have to move the device and you still have a perfect unharmed kettle.  Plus, you can still use it if your device breaks or malfunctions.

For the destructive option, open up the kettle to get at the buttons or button pads and solder a wire to each side.  If you're lucky you can do this so that it can still be put back together and the original button still work.  One option is to use a relay to connect them.  You can use a small solid state relay or a larger coil relay; both would be under a couple of dollars and not large enough to be too obtrusive.  Using a relay is nice since you don't have to worry about which voltages are being used on which side of the button and it isolates the microcontroller from the kettle better.  (Actually some relays are polarized so if it doesn't work, switch the wires and try again).  Another option is to use an  optoisolator like this one.  It is polarized so if it doesn't work switch the wires.  Another option is to use a mosfet.  I believe it will work if you get an N channel mosfet with a Vgs (gate to source voltage) less than 3.3V.  Hook up the Source pin to the more negative of the two button leads and the Drain to the other.  Hook up the gate to a pin on the micorcontroller.  Also, you should put a resister between the gate and the source pins.


SMlib State Machine Library not working as expected I have the following setup and sketch.

The problem is that when I click the button it works sometimes, but other times it executes On Off straight after On as if it's executing twice.

This is after pressing the button only 7 times:

Off
On
Off
On
Off
On
Off
On
Off

I thought that was the whole point of a state machine? That it continues to execute the next state (not multiple times at random).

Very very confused with this one.

//http://www.arduino.cc/playground/uploads/Code/FSM.zip
#include <FiniteStateMachine.h>
//http://www.arduino.cc/playground/uploads/Code/Button.zip
#include <Button.h>
//http://www.arduino.cc/playground/uploads/Code/LED.zip
#include <LED.h>

const byte NUMBER_OF_STATES = 2; //how many states are we cycling through?

//initialize states
State On = State(ledOn);
State Off = State(ledOff);

FSM ledStateMachine = FSM(On);     //initialize state machine, start in state: On

Button button = Button(2, INPUT_PULLUP); //initialize the button (wire between pin 12 and ground)
LED led = LED(13);                 //initialize the LED
byte buttonPresses = 0;            //counter variable, hols number of button presses

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

//poor example, but then again; it's just an example
void loop(){
  if (button.uniquePress()){
    //increment buttonPresses and constrain it to [ 0, 1 ]
    buttonPresses = ++buttonPresses % NUMBER_OF_STATES;
    switch (buttonPresses){
      case 0: ledStateMachine.transitionTo(On); Serial.println("On"); break;
      case 1: ledStateMachine.transitionTo(Off); Serial.println("Off"); break;
    }
  }
  ledStateMachine.update();
}

//utility functions
void ledOn(){ led.on(); }
void ledOff(){ led.off(); }
//end utility functions

Maybe you need some sort of debouncing? There's a tutorial on the Arduino site that I think will sort your problem out.


Issue with simple timer based on millis() Sorry to bother but I am at my wits end. I'm experimenting with timers, and starting very simple. The following code is supposed to print the content of a variable each time an interval of time has passed, then update that variable. But for some reason I'm getting no output on the serial monitor.
I have used the serial monitor before on other projects without issue, so I'm not sure what the problem could be.
Is there any error in my code?
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;

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

void loop() {
  if (currentMillis - previousMillis >= interval) {
    Serial.println(previousMillis);
    previousMillis = currentMillis;
  }
  else {
    ;
  }
}

//  previousMillis += interval;

Since currentMillis is just a simple variable, it will not automatically update. In fact the initialization with millis() in global scope is unnecessary. Just initialize the value with 0. At the time, where the global variables are created, the time is 0ms anyways.
You need to update the currentMillis variable everytime, before using it. So just insert
currentMillis = millis();

right at the start of the loop() function.


Should long wires be kept separated from each other, to reduce interference? Let's say someone has four CAT5 cables that are running along the ceiling for the length of a room (30 feet), of which most of the twisted pairs are connected to Arduino input/output pins on one end. Would it be okay to keep these wires bundled together when running along the ceiling? Or is it safer to keep them separated by a few inches? Is interference usually a problem only in very specific situations, or should it be considered for all long wire runs?

How about if there is a telephone cable (hooked up to a landline telephone) running along the same length? Is there any chance of interference if this is too close to the Arduino cables?

How about if there are 120v mains lines running the same length? Should these be kept at a distance from the Arduino cables?

On the other end of the cables that are hooked up to the Arduino, some of the following are connected: temperature sensors, light sensors, servo motors, LCDs, relays, and push-buttons.

A benefit of using CAT-5 is that the pairs are twisted.  You would want to look at how you are using the pairs so that you're not introducing cross talk inadvertently, but the twisted pairs tend to resist RFI which is why its used.  Telephone wire, however, can be a completely different story.  You may find some that is twisted pair, but most if it is simply flat cable.  Worse, much of it is very cheap flat cable with what amounts to a piece of thread with a very thin foil wrapped around it.  This is very high loss and very vulnerable to RFI.


Custom function like yield As far as I understand, yield() is used when you have long code (e.g. loop) so the background processing required by the esp8266 is not suspended for long time.

I have application where some sound should be running all the time and in the same time the program has to do other things which may includes long loops (that I call yield() inside them). Those long loops cause the sound to be discontinues.

What is the best idiomatic way of imitating the yield() function in my program so I do some thing like this:

for(int i=0;i<10000;++i){
    yield();
    customeYield();
    someFunction(i);
}

Where customeYield() contains the necessary instruction for playing the sound. It is exactly like this (I am using ESP8266Audio):

if (mp3_->isRunning()) {
    if (!mp3_->loop()) {
        mp3_->stop();
        return true;
    }
    return false;
}
return true;

Of course, I can just call it like I did (making it global or something). However, I was wondering if there is a standard way for such a task.

Without any hint, what you are actually doing in your long loops, it is difficult to say, what way would be the best for your case. I don't believe, there is a standard way of doing this, but there are basically only two ways of multitasking on a microcontroller:

Interrupt driven: You can set a timer interrupt, that occurs regularly to call the AudioGenerator::loop() function (which fills the buffer with the next data).
Non-blocking code: If you are using non-blocking code, you can first do one thing and then do another in sequence, so fast, that both codes are executed often enough. Thats exactly what the library you use is designed for (according to the README file).

If you are using more than one of these long loops in your loop() function, you may consider doing things with a finite state machine (FSM), so that you don't have to always add the AudioGenerator::loop() function to your long loops, but only once for the normal loop() function.


Shift Register on ATMEGA328p I want to learn more about the shiftout function used with Arduinos and used the implementation with my ATMEGA328p.

The Setup

This is the original shiftout function used in Arduino Programming, except that I replaced 1 with HIGH.

#define F_CPU 1000000UL
#define BAUD 9600UL
#define LSBFIRST 0
#define MSBFIRST 1
#define HIGH 0x1
#define LOW  0x0
#define INPUT 0x0
#define OUTPUT 0x1

#include <avr/io.h>
#include <util/delay.h>
#include <USART.h>
#include <pinDefines.h>

#define DATA PD7
#define LATCH PB2
#define CLOCK PB0

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;
    for (i = 0; i < 8; ++i) {
        if (bitOrder == LSBFIRST) {
            PORTD |= (!!(val & (HIGH << i)) << DATA);
            } else {
            PORTD |= (!!(val & (HIGH << (7 - i))) << DATA);
        }
        PORTB |= (HIGH << clockPin);
        PORTB &= ~(HIGH << clockPin);
        }
}

Main

int main(void)
{
    initUSART();
    DDRD |= (HIGH << DATA);
    DDRB |= (HIGH << LATCH) && (HIGH << CLOCK);

    PORTB |= (HIGH << LATCH);
    shiftOut(DATA, CLOCK, LSBFIRST, 1);
    printBinaryByte(PIND);
    PORTB ^= (HIGH << LATCH);

    /* Replace with your application code */
    while (1)
    {

    }

    return (0);
}

I created an example to understand more about the function, but the outcome does not add up to what I expected to see.

Szenario

PORTD |= (!!(val & (HIGH << 0)) << DATA);

This is what I expect for val = 1

(HIGH << 0) = 00000001
val & (HIGH << 0) = 00000001 & 00000001
!!(val & (HIGH << 0)) = 1
PORTD |= (1 << DATA)

As PORTD is the data pin on the shift register, it should get 00000001.
When I print the binary number within PORTD I get: 10000111 and my LED Array connected to the 74HC595 displays: 10101111

I am really lost.... I checked the connections to the LEDs and they are all good. Can you explain to me why I receive this awkward result?

This is what I expect for val = 1
PORTD |= (1 << DATA)
As PORTD is the data pin on the shift register, it should get 00000001.

your deduction is correct and the code is correct -> remember this is the case for LSBFIRST. so "val = 0x01" should be sent out as "0b1000 0000", which is precisely what the code is doing.

!(val & (HIGH << 0))

the "!!" operator is often used to turn a logic value into either '1' or '0'.
the code for shiftout() can be greatly improved.


inttypes vs Arduino defined integral types In my Arduino projects I use both Arduino types and types defined in the "inttypes.h" file, which #includes stdint.h. So far I've always written code only for the ATmega328P microcontroller (either in the UNO board or "standalone").

To be clear, in this question I'm referring to the following types:

"Arduino": char, int, long; byte, word, unsigned long
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

What is the actual difference between e.g. int and int16_t?
Is implicit conversion between corresponding types always possible, or should I avoid it even if the compiler doesn't complain? (quite often in my programs I pass an int16_t as int argument to a function and it always works, but is it good practice to do it, in general?

"Arduino": char, int, long; byte, word, unsigned long
  inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

A better classification would be:

C and C++: char, int, long, unsigned long
"Arduino": byte, word
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

I generally avoid the Arduino-specific types, as they are quite
non-standard, and do not usually exist outside the Arduino world. As for
the other types, just like Michel Keijzers suggests, I use the C types
when I do not care much about the exact size. int is guaranteed to be
at least 16 bits, but is likely to be 32 bits on a 32-bit architecture.
It is a good default type, as it is supposed to be efficiently handled
on any architecture. These types allow you to write portable code that
automatically selects the "right" integer width for whatever
architecture it is been compiled for.

If you care about the exact size, which can often be the case in a
memory-constrained environment, use the types from inttypes.h. And do
not worry about implicit conversions: as long as both types are wide
enough to hold the numbers you need to store, a type conversion, whether
implicit or explicit, always preserves the value.


How to write modular code for arduino? I would like to create a program with separated modules, is this this possible using Arduino IDE?

While you can create your own libraries for the Arduino, a simple way to make reusable code is to create a header (.h) file that contains the code you would like to make reusable.

Specifically, in the Arduino IDE create a new tab with some name foo.h, and in your main tab, add #include "foo.h" at the top of your code. What this does is essentially copy paste the code from foo.h into your code during the build process. While simple in execution, it really helps organize more complex code, and in your case, helps with reusing code.

You can alternativly use "Normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h)."

And one extra note to help you - the header files do not have access to some of the typical Arduino commands and functionality, such as delay() or Serial unless you add #include "Arduino.h". However, for IDE versions less than 1.0, use #include "WProgram.h". This will give you access to those functions.


Arduino: Digitally Muti-Switch - What is the proper term for hardware? I have recently purchased a RoboMower. Like most of the automated mowers these use electric-fence wiring to mark the borders of the property and keep a small charge on those wires so that the mower can tell where the borders are. The  RoboMower I purchased is rated for 3/4 of an acre and I have 2.25 acres to mow.

As a result I was thinking of breaking my yard into multiple 3/4 or less acre zones and using an Arduino to shift which zone is active/has current in it so that the mower would follow those boundaries. The base station would be in a place where all zones overlapped slightly. Based on what day of the week it was, the Arduino would activate the proper zone, and the mower would go out and mow in that zone because it was active. I'd clearly have to schedule this so that the switch did not happen when the RoboMower was actively mowing or it would cause all sorts of issues.

In any case, my question is: What is the hardware called that I would need in order to activate one zone or the other? Is that called a digital switch or something else? Is there such a thing of one switch that would be able to switch multiple zones, or would I basically need a bunch of switches to individually control each zone?

Each zone is a loop of wire and therefore there would not be any shared wires between the zones.

The technical term of what you're looking for is demultiplexer. Note that the demux itself will not be enough to activate the zone, it will simply allow you to choose between different zones based on its input. It is still up to you to provide any further electronics required to enable the appropriate zone.


Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt? I am trying to set up a custom board under the Arduino IDE, but I can not figure out why I am getting the warning...

Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

My "vendor/maintainer" is move38 and my platform is avr, so the path to the boards.txt is...

Arduino\hardware\Move38\avr\boards.txt

Here is my boards.txt that defines the blink board...

blink.name=Blinks Tile
blink.upload.tool=avrdude
blink.upload.protocol=avrisp
blink.upload.maximum_size=15872
blink.upload.maximum_data_size=1024

blink.build.core=blinks
blink.build.board=AVR_Blink

blink.build.mcu=atmega168pb

blink.c.extra_flags=-Wextra -flto
blink.c.elf.extra_flags=-w -flto
blink.cpp.extra_flags=-Wextra -flto
blink.ltoarcmd=avr-gcc-ar

# set F_CPU to 1Mhz for all boards on this platform
build.f_cpu=1000000L

...which would seem to define build.board as AVR_BLINKS.

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

...but nonetheless the warning persists.

I am using Arduino IDE version 1.8.3 on Windows.

What am I missing here? Is there something special about the value, format, or position of the build.board key that I am missing here?

Thanks!

More notes

Adding the following lines to a working boards.txt file...

build.name=testname
build.f_cpu=4000000L
build.core=blinks
build.board=AVR_BOARD

Will create a menu entry for a new phantom board called testname, but this is not a real board with usable keys. If you compile while that board is selected, you get the warning...

Using board 'build' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Using core 'arduino' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

...despite the fact that the key build.board is explicitly defined.

It appears that you can no longer set a global property in the boards.txt file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

  The other properties will override the corresponding global properties
  of the IDE when the user selects the board.

Further, if any global key is set directly, then both the board specific keys  and the global keys are ignored.

So in my above boards.txt, setting the the global key build.f_cpu at the end of the file seems to cover the blink.build.board key and prevent it from being copied to build.board when the board is selected. Even if you set the global key build.board directly, this setting is ignored.


Receive sms on android phone without GSM module I have done a simple project which measures CO gas in air.Now I want that sensor will measure the level of CO gas and sms will be received on android phone when the area is under danger zone.How to receive sms on android phone without GSM module?

There are exactly two ways of sending an SMS. Both of which require more than "just" an Arduino.

Directly using GSM - for which you NEED a GSM shield
Indirectly using an Internet Gateway - for which you NEED some form of internet connection.

Since you have an aversion to 1, 2 is your only option. So you require some extra hardware (unless you have an Arduino with built in WiFi or Ethernet) to connect your Arduino to the internet. Then you have to pay an SMS gateway provider to allow you to send SMS messages through them, and implement their API in the Arduino.

Also you need an internet connection available wherever the Arduino happens to be.

All in all a lot of work and you're really no better off than using a GSM shield.


Getting the highest value from analog reading? I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.

I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.

This is the code I have until now.

int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider
void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.println(fsrReading);     // the raw analog reading

  delay(100);
}

You don't want to delay ever. Instead you want to change your thinking to "X miliseconds have passed, time to print and reset":

int maxval = 0;
uint32_t lastSample = 0;

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

void loop() {
    if (millis() - lastSample > 100) { // Every 100ms:
        lastSample = millis();
        Serial.println(maxVal);
        maxVal = 0;
    }
    int reading = analogRead(0);
    if (reading > maxVal) {
        maxVal = reading;
    }
}

Every 100ms it will print the maximum analog value read during the past 100ms.

You can replace the 100ms with any other value you choose, or even with a check to see if a button has been pressed, in which case you get the maximum reading since the last time the button was pressed:

// global
bool lastButtonValue = HIGH;

// in loop()
if (digitalRead(3) != lastButtonValue) {
    lastButtonValue = digitalRead(3);
    if (lastButtonValue == LOW) {
        // ... do the print and reset
    }
}


How to determine which pins_arduino.h file is used? For some applications I need access to the registers that control the output/input and high/low state of pins.  For example pin 10 on a adalogger is PORTB with a mask of _BV(6).  This information can be found in pins_arduino.h.  For some boards many variants get installed.  I turned on verbose compiling and looked through the output there as well as looking through boards.txt and platform.txt.  In that output I see an include to a directory with a pins_arduino.h file but there is nothing in that file but a definition for BUILTIN_LED.

When I run a function like digitalWrite(13,HIGH); how does it know which registers to use for pin 13?  Since my board has this pin, and digitalWrite(13, HIGH); makes an LED light up ... it's working.

In the boards.txt file for the core in question you have a line for each board:

xxxx.build.variant=yyyy

where yyyy is the name of the folder in variants for the board.

For instance, the Uno, has:

uno.build.variant=standard

which relates to:

variants/standard

with the pins_arduino.h file in it for that board.


My Arduino isn't showing up on my computer. What should I do? You have your spangly new Arduino board, you've installed the software, and you plug it in. Nothing happens. Diagnosing problems may be a little tricky for the beginner, so what hoops should you go through to try and work out where the problem is and why you can't get your board working?

Note: this is an FAQ. Do not use it to ask about your specific problem. Comments will be deleted. Either ask a new question detailing all the steps you have taken, or, better, discuss your problem in chat.

Linux

Getting Arduino and Arduino-like boards working properly under Linux can be a troublesome task if you are not familiar with how Linux works.

So I am going to introduce you to some of the basic tools you will need to work out why your board isn’t working as you’d like it to work.

The majority of problems a new user is faced with boil down to one simple thing: permissions. A normal user doesn’t, by default, have permission to talk to much in the way of hardware. That include serial ports and USB serial emulation ports (FTDI, etc). Fortunately granting permission to your user to access the serial ports is a simple matter, and one that you should always do by default to make life much simpler for you. This is done through a Linux permission facility called groups. A group is a name given to a collection of users, files, devices etc., that go together. Permissions can be granted on files to the group that it belongs to, and users that are in that group can access those files. On Linux most devices are just files.

The serial ports are all in the default group dialout, but your normal user isn’t. So you need to add your user to that group. Only root has the permission to do that, so use sudo to execute the commands as root. If you don’t have access to root through sudo or some other means then you will have to seek the assistance of an administrator who does have permission.

First add your user (you’re called fred, right?) to the dialout group:

$ sudo usermod -a -G dialout fred

The “-a” is of vital importance. That says “Add the user to these groups”. Without it you have “Set the user’s groups to be this list”. If you omit the “-a” by accident you will remove your user from any other groups before setting them to be in the dialout group. That means you will never be able to run sudo again. So be sure not to miss that one out, eh?

Now that has only changed the configuration files (/etc/groups in this case) and the change hasn’t actually had any effect yet. The groups are only set when you log in to the computer, so you will either need to log out and back in again or (a more definite solution, especially if you have auto-login turned on) reboot the computer.

Now you should be in the dialout group:

(before)

$ id
uid=1000(fred) gid=1000(fred) groups=1000(fred),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

(after)

$ id
uid=1000(fred) gid=1000(fred) groups=1000(fred),4(adm),20(dialout),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

Now try it, see if that has got you working.

Next step, if that doesn’t fix your problems, is to see if the computer knows about the Arduino. First look to see if there is a device file for the Arduino and if it has the right permissions:

$ ls -l /dev/ttyACM* /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory
crw-rw---- 1 root dialout 166, 0 Aug 24 11:05 /dev/ttyACM0

Don’t worry about the “cannot access…” message unless you get two of them. There are two sets of device names that the Arduino could be under depending on which type it is. Genuine UNO and similar boards (the ones with the ATMega16U2 chip as the USB interface) are /dev/ttyACM*. Clones using the CH340G, and FT232 based boards appear as /dev/ttyUSB*. We just asked for both there, so it complained when it couldn’t find any entries for one of the types. Which is fair enough. If you get:

$ ls -l /dev/ttyACM* /dev/ttyUSB*
ls: cannot access '/dev/ttyACM*': No such file or directory
ls: cannot access '/dev/ttyUSB*': No such file or directory

however, then worry. That can’t find anything at all. The computer doesn’t know the Arduino exists.

One thing to check is the permissions on the files that have been listed above. You see the word “dialout” in the list? That’s the group that the device belongs to, and it should match the group you added yourself to earlier. There are times when it may say “tty” instead. This is because some other program has grabbed the device and is using it to allow remote access to the computer through that serial port. For that you need to make sure that there are no agetty processes using that port. How you do that is very much down to your version of Linux. Modern Debian based systems (such as Debian Jessie and Ubuntu) use systemd to manage it. You can examine what is running on your system using

$ systemctl status

That returns a tree of all the services that your system is running. Look through that list to see if there are any “serial-getty” services running. If there are you should remove them:

$ sudo systemctl stop serial-getty@ttyACM0
$ sudo systemctl disable serial-getty@ttyACM0

While you’re there look through the list for another troublesome member: ModemManager. This is a program used to dial out to the internet through old-fashioned modems (you know, the kind that go beep beep beep squark squeek squark ) or USB DSL modems (that no one uses any more, we’re all wireless now. Remember the old green “frog” modem from way back when…?). That has a habit of grabbing a serial port as soon as it appears and trying to configure a modem attached to it. While that’s happening nothing else can access the serial port. It’s especially a problem with boards like the Arduino Leonardno or chipKIT Lenny which create a new serial port when they enter programming mode. So unless you really need the functionality that ModemManager provides you should just remove it:

$ sudo apt-get remove modemmanager
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED
modemmanager
0 to upgrade, 0 to newly install, 1 to remove and 138 not to upgrade.
After this operation, 2,826 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 180827 files and directories currently installed.)
Removing modemmanager (1.4.12-1ubuntu1) ...
Created symlink from /run/systemd/system/ModemManager.service to /dev/null.
Removed symlink /run/systemd/system/ModemManager.service.
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for hicolor-icon-theme (0.15-0ubuntu1) ...
Processing triggers for dbus (1.10.6-1ubuntu3) ...

Another useful tool is lsusb. This lists the USB devices that are connected to your computer. You should find your Arduino listed there. This is especially useful for boards that don’t present a serial port for programming, but we’ll cover those in more depth a little later on.

$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Nothing much on this computer. Well, actually I am using a virtual machine for this, as you can see by the VirtualBox USB Tablet entry. But let’s connect my Arduino UNO:

$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 004: ID 2341:0001 Arduino SA Uno (CDC ACM)
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

So we know that the operating system has identified it. You can find out lots more information about it if you so desire, with:

$ lsusb -v -d 2341:0001

That gives you all the device descriptors for the device. Tells you all you could ever want to know about the information the board sends to the computer when it is connected.

Another useful tool is dmesg. This is the system message log viewer and can be used to find out exactly what is going on with your computer.  It has a useful “keep running” mode specified by the flag -w. I like to run dmesg and then press return a few times to create a breakpoint in the listing, then plug in the board I am diagnosing to see just what the messages are that pertain to that board:

$ dmesg -w
[ 0.000000] Initializing cgroup subsys cpuset
[ 0.000000] Initializing cgroup subsys cpu
[ 0.000000] Initializing cgroup subsys cpuacct
[ 0.000000] Linux version 4.4.0-24-generic (buildd@lgw01-12) (gcc version 5.3
... lots of stuff spools past ...
[ 19.425870] NFS: Registering the id_resolver key type
[ 19.425883] Key type id_resolver registered
[ 19.425885] Key type id_legacy registered
<press return a few times>

<connect Arduino>
[ 131.232511] usb 2-2: new full-speed USB device number 3 using ohci-pci
[ 131.519307] usb 2-2: New USB device found, idVendor=2341, idProduct=0001
[ 131.519312] usb 2-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 131.519315] usb 2-2: Product: Arduino Uno
[ 131.519317] usb 2-2: Manufacturer: Arduino (www.arduino.cc)
[ 131.519319] usb 2-2: SerialNumber: 64934333235351B002E0
[ 131.605485] cdc_acm 2-2:1.0: ttyACM0: USB ACM device
[ 131.613792] usbcore: registered new interface driver cdc_acm
[ 131.613796] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

Press CTRL+C to terminate the listing.

If nothing appears when you connect the Arduino then there is something fatally wrong. My money is either on a faulty cable (some cheap cables on eBay only have power wires and no data wires) or the Arduino itself is completely dead.

More likely though you get error messages. I can’t replicate them right now (I don’t have a faulty Arduino) but they usually pertain to things like “device not accepting address” and “Error -71”. This is usually caused by bad USB communication. It may, again, be a faulty cable, or it may be that the USB interface chip is not working right. Maybe the crystal has drifted and it’s not running at precisely the right frequency. Maybe it’s a cheap CH340 chip that has failed. Maybe the firmware on the ATMega16U2 has become corrupted.

If all that checks out fine so far and you still can’t upload a sketch there may be something even more fundamentally wrong with your Ardunio board. Maybe it’s time to look to see if there is actually any communication happening. I find the program minicom invaluable, although you could use the ghastly Serial Monitor in the Arduino IDE.

First you need to disable the main chip on your Arduino. You can do this simply by connecting the RESET pin to GND with a piece of wire. Or you can hold the RESET button down, but that means you’re then typing one-handed. That stops the main chip from interfering in any way with the serial communications while you’re testing it. It can also prevent any damage to the chip while testing.

The second step is to connect the TX and RX pins together (pins 0 and 1 usually) with another piece of wire. You are now in what is known as a loopback mode. Any serial data you send to the board should be sent straight back to where it came from. So now fire up minicom and try it out (you will need to install it first of course with sudo apt-get install minicom).

$ minicom -D /dev/ttyACM0 -b 115200

Of course replace the /dev/ttyACM0 with the real device name for your board. The -b 115200 is the baud rate, though that is pretty much irrelevant since we’re not actively communicating with an external device.

Now you should be able to type some gibberish and get some gibberish back. If you do then communication is working fine, and the problem most likely lies within the target MCU – maybe the bootloader has become corrupted and needs re-flashing, or the chip has died.

CTRL+A, X gets you back out of minicom again.

If you didn’t get your gibberish back, or you got back different gibberish than you sent, then there is definitely something up with the serial communications. The main culprit is, again, the USB interface chip.

All this, of course, has been focusing on the traditional Arduino style interface with a USB serial port of some form. Not all boards give you that though. Some, such as the Launchpad boards, use a hardware programmer on the board, and that doesn’t always give a serial port – certainly the programming isn’t done through the serial port. To gain access to those (again by default you don’t have permission to access the low-level devices) you have to get deeper into the operating system.

For these you need to make modifications to the configuration of a system called udev. This is a management system for the devices on your computer and is used to control what happens to them when they are plugged in. One of the things you can do is set the permissions on that device so people can actually access it.

The system is configured by a set of rules in “rules files”. These are stored in /etc/udev/rules.d and there should already be a few in there for other purposes. You will need to, as root, create a new file to put your rules in.

$ sudo nano /etc/udev/rules.d/50-boards.rules

The most important thing to know is the VID and PID (Vendor ID and Product ID) of your board. You can get that from lsusb as above (it’s the vvvv:pppp bit – v = VID, p = PID). You can then feed that into a simple rule, such as:

ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="0033", MODE="0660", GROUP="plugdev"

There we are matching a vendor (04d8 = Microchip) and product (0033 = PICkit2) and assigning it to the group plugdev (make sure you are in that group – default users should be already) and allowing the group members read and write access to it (MODE="0660"). Save that file and restart udev for the changes to take effect (or reboot your computer if you like):

$ sudo /etc/init.d/udev restart

Now plug the device in and you should have permission to access it.


Is the LGT8F328P legal? Since some months, everyone can buy a board with this IC.

It is compatible with the ATMega328 and has some features like 12bit ADC (instead of 10 bit), DAC, unique ID and also 32MHz.

But I can't find it in the "normal" shops. Also on the LCSC it is not available. Only in this shop:
https://www.electrodragon.com/product/5pcs-logicgreen-lgt8f328p/
For 0.68$ compared to the 2$ for the atmega326P-AU of the other electronic parts shops (it is cheaper than the cheapest attiny with ADC!)

So the question. Is this chip just a clone for private use or can it be used as official alternative to the more expensive and original ATMega328?

Legal or not, I DO NOT reccomend this clone. It is similar and compatible to some extend but it lacks features like an EEPROM. With fuses you can only reserve some FLASH to emulate an EEPROM. Thus have less space for your code.
Also the manual is only available in chinese. There are english translations but those are hard to read as the layout got screwed up.
It has some new features that sound great but I would not see them as replacement for the ATmega328P from Atmel/Microchip.

I bought an Arduino clone with LGT8F328P by accident. I find it barely usable as there are itches here and there which I don't want to deal with.


How to upload a sketch to Arduino if it goes to deep sleep mode quickly I have created sketch where Arduino goes to powerdown mode in about 1s after boot. Now I can not upload other sketch, because programmer does not get proper response. I tried to hold reset and release it at various stages during compile/upload, but it does not help. I suspect the programmer needs to communicate with Arduino for several seconds. Any advice how to erase the sketch without programmer, or how to ban the sleep mode? It is Pro Mini 168. Thanks

Hold the reset button while you start the upload. Wait until you upload first tries to connect to the Arduino, then release the reset.

If you can't get that to work, the next option is to load another Arduino with the ArduinoISP example sketch, connect the two as described in the comments, and use the 2nd Arduino to program yours.

Update:

  Would another Arduino overcome this problem?

Ok, then it's time for plan B. Using a programmer (real, or simulated by another Arduino) doesn't depend on the 'failing' Arduino's bootloadloader but uses a direct (SPI) interface to program it. This article has more information.


What precision can I expect by syncronising DS3231 with PC serial? The point here is to syncronise a DS3231 module (on an Arduino) via serial port with NTP time by computer.

The problem here is that I'd like to know how much time is taken by the serial and I2C transmission, because if the PC sends the time at a time t1 and transmit it to the Arduino, the Arduino decodes it and sends it to the DS3231, the time t1 is received at a time t2 greater than t1.

PC (t1) => Serial(t1+x) => Arduino(t1+x+y) => I2C(t1+x+y+z) => DS3231(t2=t1+x+y+z)

t1 -> NTP time recorded by PC
x  -> Time taken by serial transmission
y  -> Time taken by arduino buffering/processing
z  -> Time taken by I2C transmission at 100kHz
t2 -> Time when message is received by DS3231

Is it negligible for a precision at millisecond?

I found a table on Wikipedia that displays time per bit per baudrate. I am planning to use a baudrate of 57600.

I tested offset using a simple echo program available here at 300 baud:

String buff="";

void setup() {
  // put your setup code here, to run once:
Serial.begin(300);
}

void loop() {
  if(Serial.available())
  {
    while(Serial.available())
    {
      buff += char(Serial.read());
    }
    Serial.print(buff);
    buff = "";
  }
}

Transmission time will certainly not be negligible. To estimate it, you could use the roundtrip delay calculation, which is (roughly) how the NTP protocol is implemented in the first place.

at PC time T1, PC sends current time T1 to Arduino via UART
Arduino sets the time T1 in DS3231 via I2C
Arduino reads the time T2 from DS3231 via I2C
Arduino sends the time T2 to PC via UART. This happens at time T3 from PC's point of view.

Now the PC can estimate the half-roundtrip delay R as (T3-T2)/2. See the following chart which denotes current time form POW of PC and RTC

        |--UART--|--I2C--|--------|--I2C--|--UART--|
PC      T1              T1+R     T2+R           T3=T2+2R
DS3231  -                T1       T2              T2+R

Next, at time T4, the PC sends the value (T4+R) via UART. This will result in  DS3231 to be set to (T4+R), which happens exactly R time after T4, so that both clocks are now set to the same value.

Estimation of R can be repeated several times. In this case you can calculate the standard deviation which tells you how much "jitter" your clocks have.


Arduino Pong game Circuit Board Troubleshoot I am following a tutorial online to make a pong game. I have managed to make quiet a lot work apart from my paddles in the game keep on shaking. The buttons do work fine, up and down on both ends.

Tutorial Link

I am sure, there is something with the power being supplied and not reaching to all points in the breadboard.

I am attaching a picture of my circuit board. Any advice?

Thank you,
W

The + and - along the bottom of the picture aren't connected to anything.
It also looks like this board has a separate left and right side.

So just make sure everything is connected along the sides.


SIM800 gsm Module returns 0 on AT+COPS? I am using SIM800 Module with Arduino Micro. It reponds well to basic AT commands. But i am unable to send SMS from this module as:

AT+CMGF=1 ERROR

Now while further debugging i saw AT+COPS? Returns 0, means not connected to any operator. That may be causing the CMGF failure. But my AT+COPS=? returns multiple operator. I have an Airtel working sim. Intialyy it was showing AIRTEL too in AT+COPS=? but not now.. anything to do with signal??

AT+COPS?

+COPS: 0

OK AT+COPS=?

+COPS: (2,"405800","405800","405800"),(1," IDEA CELLULAR Ltd","IDEA","40404"),(1,"40505","40505","40505"),,(0-4),(0-2)

What is going wrong here. any inputs?

It can take a while for a modem to register on the network - sometimes several minutes.

Turning on CREG URCs can help you monitor what is happening:

AT+CREG=1

You should now start getting +CREG notifications as the network status changes.

Before using AT+COPS? you should really select a reporting mode so you know what you are looking at. I prefer numeric, since it's easier to parse:

AT+COPS=0,2

That will switch to automatic registration and reporting as numbers.

AT+COPS?
+COPS: 0
OK

That is not registered.

AT+COPS?
+COPS: 0,2,"40404"
OK

That is registered on a network with ID 40404.

The +CREG reports tell you what is going on:

+CREG: 1

That tells you that you have just connected to your home network.

If you are roaming, you would see:

+CREG: 5

Of course, if your home network is not available (say you have an AT&T SIM and only Verizon is visible at the moment), and your SIM doesn't have roaming enabled, then registration will never work.  You'd expect to see +CREG reports of:

+CREG: 2
+CREG: 3
+CREG: 0

That is "trying to register" (2), "registration denied" (3) and "doing nothing much now" (0).

The best document for learning about these commands is the 3GPP Command Set which is the standard that all modern GPRS modems should adhere to.


W5100 module hookup help - Not a shield I recently purchased a W5100 based ethernet shield for my arduino Uno, and looks like this. I had been following the guide here, and connected the pins accordingly - 5V to 5V, GND to GND, MOSI to 11, MOSO to 12, SCK to 13, and SS to ten.

I booted up a default sketch (webServer, under Ethernet), and plugged in and ethernet cable. - PWR, LINK, SPD,and FDX all lit up, with Rx blinking for first 10 or so seconds. I then go to the IP specified on the arduino sketch, and nada. Also, my router doesn't show the shield under the attached devices.

Therefore, I figure it's a problem with my connections. Can anyone help me? Googling has only brought my lots of info about shields, and little info on these modules.

First, if you cannot connect to arduino by ethernet, use Serial Monitor and add some Serial.println to your code to log what is going - what part of program Arduino is executing.

W5100 module has no automatic reset module as opposed to Ethernet shield.
So try to connect W5100 RST pin to for example D8 and reset module in setup.

Here you are example from my (working) project:

const int W5100_RESET_PIN = 8;

void setup() {
  Serial.begin(SERIAL_SPEED);
  Serial.println();
  Serial.println(F("node starting..."));
  pinMode(W5100_RESET_PIN, OUTPUT);
  digitalWrite(W5100_RESET_PIN, LOW);
  delay(100);
  digitalWrite(W5100_RESET_PIN, HIGH);
  // give the Ethernet shield a second to initialize:
  delay(3000);
#ifdef USE_DHCP
  Serial.println(F("DHCP..."));
  while (Ethernet.begin(mac) == 0) {
    Serial.println(F("DHCP failed."));
    delay(10000);
  }
#else
  Serial.print(F("static IP..."));
  Ethernet.begin(mac, IPAddress(MY_IP));
#endif
  Serial.print(F("local IP:"));
  Serial.println(Ethernet.localIP());
  Serial.println(F("node started."));
}

Also after setup if your arduino lost ethernet connection and cannot get it again, you can try to reset w5100 and initialize Ethernet again.


ADXL355 accelerometer code I am doing a project which monitors vibrations using an ADXL355 sensor and an Arduino. I have used the MPU-9250 sensor before.
I am not able to find a library or tutorials for calibrating, filtering, and reading accurate data from the sensor. Can anyone who has worked previously with the sensor help me? I am mechanical engineer new to the field of electronics.
If library files are not available, how can I use the datasheet to write the entire code myself? Is there any tutorial available for this?
Sorry if the post seems confusing..

I had a similar learning path  as yours and I also tried to use ADXL345 and ADXL355. The latter was a pain for the issues described in many posts like this.
I couldn't find any good tutorial on this topic and had to learn all by myself.
I also use a different approach because I program ESP32-wrover devices with MicroPython. Nevertheless the logic is the same for translating DataSheets -> code.

You have to decide which serial interface to use

I2C if you are constrained to limited wires
SPI for high frequency measures

in both cases you write/read to/from registers of the device which are identified by an address, indicated in the datasheet (look for the registers map section). In each address you read/write a byte, that is 8 bits (0 or 1), that are packed into an hexadecimal format (e.g. you can set power mode to 'measure' writing 0x01 in register with address 0x2d)

with both you normally have a library that implement 3 main methods:

init() for initializing the interface with the parameters you find in the datasheet:

SPI: polarity, phase, max_clock_frequency, first bit MSB or LSB
I2C: max_clock_frequency

read(register_address, nbytes) -> bytearray
write(register_address, bytearray)

before reading accelerations you must set range (e.g. ±2g), output data rate (e.g. 1000Hz), power mode (e.g. measure mode)

then you read acceleration data from corresponding registers. Consider that you can read multiple registers in one transaction reading multiple bytes starting from an address (e.g. you can read x,y,z measure in one transaction by starting from the first byte of x data and then reading 9 bytes = 3 axes * 3 bytes)

Then you have to convert from bytes to g units: in this accelerometer the value of one axis consist of 20 bits that are split in 3 bytes. You have to join the 3 bytes, shift away the trailing 4 bits, then apply two's components (that is for allowing negative numbers, look at this guide), then multiply by the scale factor indicated in the datasheet.


How to handle multiple input pins at once? I am relatively new to Arduino platform and not know much. I am working on a Bicycle speedometer with turn and stop indicators.

I am planning on connecting an inductor magnet to calculate the rotation of my front wheel while providing the following services from the same arduino board:

Input horn and turn indicator switches.
Output to turn indicators.
Stop light when one of the brakes is
applied.

While I am sure of how to connect all the sensors, except the magnet, I am not sure how to handle the various inputs and the outputs at once.

I must be able to horn and stuff while the indicator blinks at a regular interval all the while the monitor keeps displaying my speed and distance covered.

Any reference or help would be greatly appreciated.
Thanks in advance.

Bharath. S.

How fast do we need to read the magnetic switch to not miss any pulses? I'll make some working assumptions:

Using 700c wheel and 28mm tire [assumed; adjust as necessary]
Rolling radius 2.1m [from here; there are other ways to arrive at this]
Max speed 22 m/sec (50mph), [working assumption; adjust as you see fit]
Magnet and switch interact for at most 3% of a rotation, [WAGuess]

The wheel will have to turn at ~10RPS at max speed giving a pulse period of 100ms. The pulse width will be at most 3% of that, or 3ms.

Your service loop would have to execute in somewhat less than 3ms, every time, in order to not miss any wheel pulses and that's if I haven't been too optimistic about the pulse width. I'd personally assume a 1ms maximum loop time, then test it on the road by sampling & logging wheel-pulse level with an Arduino at at least 10x that rate or 10+KHz.

Or I'd go with an interrupt-driven wheel pulse period timer not width) to ease the constraints on the main loop.

The main loop need only poll your turn, brake, and horn switches and a timer for blinking the turn signals. Even if the timing is a little erratic for some reason, no harm is done, and nothing is likely to be apparent to the rider or other road users.


Simple Arduino Serial Arithmetic I'm developing a program to calculate static margin of an aircraft through the calculations of mass,moment and arm. Essentially dealing with large numbers.

I'm having difficulty in setting up my code in the way so that the arithmetic is applied correctly to larger numbers. What I have so far works but only when the input is 0-9. The arithmetic fails to calculate digits beyond.

I understand that I'm breaking the digits into separate variables as to convert them from ASCII format to their intended value. The problem is in putting those digits back together.

I know this is probably very simple but I'm picking up arduino again after a long break and I'm very rusty.

Here's my code thus far:

long batterymoment,num1,num2,answer;
int batterymass = 720;
int batteryposition;
boolean mySwitch = false;

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
}

void loop() {
  while (Serial.available()){
   batteryposition = Serial.read();

   if(batteryposition>47 && batteryposition<58){
     if(!mySwitch){
       num1=(num1*10)+(batteryposition-48);
     }else{
       num2=(num2*10)+(batteryposition-48);
     }
   }

   answer=num1+num2;
   batterymoment=answer*batterymass;
   Serial.print("Battery moment is: ");
   Serial.println(batterymoment);
   num1=0;
   num1=0;
   mySwitch=false;
  }
}

Thanks.

Do you mean to repeat num1=0; in loop()?

It is only reading one character per loop() because loop() happens much faster than Serial.available() and Serial.read().

Do the reporting and clearing when you receive some sort of separator/non-digit character.