HX711 Soft WDT Reset I am using the following code to check if the value is 0 e.g there is no weights placed and if so, it will ignore this value and do nothing with it. The code runs correctly but keeps outputting the following:

  Soft WDT reset

        stack>>>

  ctx: cont sp: 3ffffd70 end: 3fffffc0 offset: 01b0 3fffff20:  00000050
  00000000 31310010 36323439   3fffff30:  00000000 00000000 00000010
  00000001   3fffff40:  3ffee408 00000000 00000000 40202927   3fffff50:
  4022dff2 a0000000 bf2cc404 3ffe84dc   3fffff60:  3ffee408 bf2cc404
  3ffee408 40202962   3fffff70:  3ffeeb9c 40202c00 3ffee408 40202996
  3fffff80:  3ffee448 bf2cc404 3ffee408 40202664   3fffff90:  3fffdad0
  fffe2d7e 3ffee448 3ffee4b0   3fffffa0:  3fffdad0 00000000 3ffee480
  40203848   3fffffb0:  feefeffe feefeffe 3ffe8514 40100a41
  <<

If I remove if(reading < 0.01){ the code runs fine. What could be causing this?

#include "HX711.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define DOUT  D3
#define CLK  D2
const char* ssid = "Curtis";
const char* password = "password";

HX711 scale(DOUT, CLK);
float calibration_factor = -118470; //-7050 worked for my 440lb max scale setup
void joinwifi(){
    WiFi.begin(ssid, password);
  Serial.println();
  Serial.print("Connecting");
   while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("success!");
  Serial.print("IP Address is: ");
  Serial.println(WiFi.localIP());
}
void setup() {
  Serial.begin(9600);
  joinwifi();
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}
void loop() {
  while (WiFi.status() == WL_CONNECTED)
  {
    scale.set_scale(calibration_factor); //Adjust to this calibration factor
    float reading = scale.get_units(1);
    if(reading < 0.01){
      Serial.print("no need");
       Serial.println();
    }
    else{
      Serial.print("Reading: ");
      Serial.print(reading);
      Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();
      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }
  }
  while (WiFi.status() != WL_CONNECTED)
  {
    joinwifi();
  }

}

Because your code is all running in a while inside your loop (which is redundant - loop() loops, hence its name), and you have no delays or yield() calls, you are not giving the watchdog the required kick that it needs to stay alive.

Either remove your whiles and turn them into ifs instead, or add yeild() calls inside your while loops.


Re-enable Arduino after short I happened to short-circuit my Arduino by mistake. It was powered by USB on my Windows 7. The OS was so smart to pop-up warning about USB power surge and shut it down immediately. Arduino survived.

I fixed the circuit and connected it back. Arduino was powered again, but it was not recognized as COM port anymore. There was no unknown device in Device manager. I tried different USB connector on the same computer and it was found and it worked. But the other USB was out.

I restarted the computer and connected the Arduino back to the broken connector. The drivers were automatically reinstalled (I don't know why) and it worked again.

Is it possible to re-enable Arduino on the same USB connector without restart? I'd like to understand what happened on the computer side.

Most likely, your motherboard detected a over-current situation, and disabled power to that port. Since it has to way to know if the cause of the over-current has been fixed, it will continue to disable the port (since the only way to know would be to turn the power back on, and doing that to many times might cause permanent damage).

I wouldn't expect there to be a way to force your MoBo to reset the port, as this is an unlikely event. You should be glad the MoBo prevented any damage.

Using a different port sounds like an okay solution.


Wire.h missing - Failing to upload I2C 16x2 LCD sketch I am total newbie in Arduino and for the last 3 days I am trying to figure this out.

I would like to use an I2C display for a project. I have installed the LiquidCrystal_I2C, but when I try to upload it I get this wire.h missing message.

Could anyone please help me to understand and fix this?

That library is special. It expects to be placed in the same location as the Wire library.  You need to find the location of the Wire library and place this library alongside it.  So you have:

.../Wire/Wire.cpp
.../Wire/Wire.h
.../LiquidCrystal_I2C/LiquidCrystal_I2C.cpp
.../LiquidCrystal_I2C/LiquidCrystal_I2C.h

etc


Arduino Nano Every I2C PORTMUX Arduino Nano Every schematic informs us that we can use ATMega4809's pins PF03 and PF02 to communicate via I2C.
ATMega4809 manual says in page 19 that in order to use those pins as I2C we need to use PORTMUX.
I'm not really an expert and I don't understand how to do that.
Any help would be approciated.

In the Nano Every schematic, PF2 and PF3 are connected over to PA2 and PA3 respectively.  That is, Arduino pin A5 and ATMega4809 pins PF03 and PA03 are connected together by PCB traces such that there's no distinction between them, PF03 doesn't have its own header pin anywhere distinct from PA03.  They're both A5.  Likewise for Arduino pin A4 and ATMega4809 pins PF02 and PA02.
The Nano Every was designed to be compatible with the original Nano boards that used the ATMega328P.  On these boards the A5, analogRead-capable pin, is also the I2C/Wire clock signal.  Likewise,
A4, analogRead-capable pin, is also the I2C/Wire data signal.
On the ATMega4809 the I2C/Wire Master/Slave signals on PORTA routed to the A5 and A4 pins are not also analogRead-capable.  That is, they are not connected to the analog-to-digital converter in the chip as they were in the Atmega328P on the old Arduino Nano boards.
To mirror the workings of the original Nano, where A4 and A5 were both analogRead pins and I2C/Wire Master/Slave pins, they connected A4 and A5 to pairs of ATMega4809 pins.  One of these pins on PORTF is connected to make the Arduino pin analogRead-capable and the other pins on PORTA are connected to make the Arduino pin Wire/I2C Master/Slave capable.  In other words, they used two AVR pins to synthesize a single Arduino pin capable of both functions that were available on that pin on the older Nano boards.
When it comes to using PORTMUX to switch choice of I2C pins, practically speaking, you won't be able to if you're looking to get alternate pins for TWI Master.  PORTMUX lets you switch the I2C Master/Slave or just Master peripheral onto pins PC2 and PC3 instead of PA2 and PA3.  But, in the Nano Every schematic, you can see these are not connected to anything.  So if you wanted to do that, it would mean something like soldering wiring-wrap wire directly to the MCU pin, which would be difficult.  And PC2 and PC3 are the only two other ATMega4809 pins that PORTMUX will route the hardware I2C Master/Slave peripheral to.    So, practically speaking, if you want I2C any pins other than A4 and A5 on a Nano Every, it means using a software (bit-banged) implementation of I2C.
You asked (in comments) about the TWI support indicated on PF2 and PF3 in the ATMega4809 datasheet.  I think I'd either been looking at an older datasheet or maybe disregarded those pins because of how they're hardwired over to PORTA on the Nano Every.  The ATMega4809 has a "Dual TWI" mode apparently, where you can have just master mode on the pins that are normally both, and just slave mode on an alternate set of pins.  In two configurations of PORTMUX under Dual TWI, the PF2 and PF3 are where the slave-only capability of the peripheral are broken out.  With PORTC's TWI pins unconnected and PORTA's TWI pins hardwired to PORTF's TWI pins, it's unclear to me what advantage you could get out changing PORTMUX on an Arduino Nano Every.


Any suggestions? (On running two programs within one Arduino maybe) Super duper noob here! Please help me out thanks!. So what I am doing right now for a project is to create a device that can read the EMG (muscle tension) in the body, and when it reads a specific number, an audio clip will be triggered to play. I already hooked up the Arduino board to this device that reads EMG successfully. Now my question is, to add the audio component to this device, what should I do? Can another program actually run on the same Arduino device? Is there an add on that I need to buy? (Perhaps some sort of Bluetooth device to connect to a Bluetooth speaker for the audio? )

Small excursion:

You are right to observe that the Arduino with its 1 core can only execute one instruction at any given time. However, there are ways with which we can achieve that the Arduino "does things in the background". We can e.g. use interrupts from hardware timers, which will interrupt the main CPU core to quickly execute a interrupt service routine, and then continue where it let off originally.

This is also how an RTOS (real-time operating system) works. You can only execute one thing at a time, but if you set up a timer interrupt every 20 milliseconds in which you switch between the executed functions, you get a "emulated" multi-task system. These are the basics of any operating system.

References:

https://www.sparkfun.com/tutorials/326
https://www.youtube.com/watch?v=QtyOiTw0oQc
https://arduino-info.wikispaces.com/Timers-Arduino
https://www.freertos.org/implementation/a00002.html

You will also notice that your Arduino Uno can't play music directly -- for that, you would need a digital to analog converter to produce the needed analog audio voltages, together with a audio amplifier for headphones or loudspeakers.

https://www.youtube.com/watch?v=Y2OPnrgb0pY

Fortunately there are many Arduino shields that do the job. Some of them are:

Seedstudio Music shield (documentation, library)
Adafruit Music Maker shield, with either headphone or loudspeaker output

Here, the work of playing music (from a file on an inserted SD card, for example), is offloaded to an external synthesizer chip. We do however need to supply the chip with the to-be-played music data in the background.

When you look e.g. at the library reference for the Adafruit Music shield, you'll see that it offers a function that will use interrupts to play a file from the SD card in the background.

Using the library in this interrupt mode will of course use an interrupt source (either timer or pin), which may conflict with your EMG code if it also uses that timers. In that case you will have to move either the EMG code or the music code to a different available timer.

In short:

Learn more about what interrupts and timers are
find a suitable shield (e.g. the adafruit shield above) and understand its library capabilites and limitations


Why am I always getting 48 with serial communication? So I want to send some data from Matlab to Arduino. To verify that I am getting the correct data I am sending the data back to Matlab (since I get errors if I open the serial monitor, if there's an easier way to print debug messages let me know).

The problem is that I always get 48 back.

My matlab code:

arduino = serial('COM3','BaudRate',115200);
fopen(arduino);
fprintf(arduino,'%f',1);
fclose(arduino);

fopen(arduino);
disp(fscanf(arduino, '%f'))
fclose(arduino);

and my arduino code:

In the setup:

Serial.begin(115200);

In the loop:

delay(100);
myFunction();

In myFunction:

while(!Serial.available()>0)){}
int data = Serial.read();
Serial.println(data,DEC);

It seems like the 48 is an ascii code for something but it doesn't ever change when I change the 1 is the 3rd line of the matlab code to anything else.

Why am I always getting 48 with serial communication?

Your Arduino sketch (snippet) is reading a byte and writing the value, not the character. The value 48 in ASCII is the character '0'.

The below loop() function will echo all the characters received.

void loop()
{
  while (Serial.available()) {
     char c = Serial.read();
     Serial.println(c);
  }
}

This could be a good starting point when debugging what is actually written from MATLAB.


I have downloaded the library but not sure what went wrong C:\Users\Dray98\AppData\Local\Temp\arduino_modified_sketch_819854\sketch_jun09a.ino:2:29: fatal error: Adafruit_Sensor.h: No such file or directory

 #include <Adafruit_Sensor.h>

                             ^

compilation terminated.

Multiple libraries were found for "DHT.h"
 Used: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
 Not used: C:\Users\Dray98\Documents\Arduino\libraries\DHT-sensor-library-master
Using library DHT_sensor_library at version 1.3.0 in folder: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
exit status 1
Error compiling for board Arduino/Genuino Uno.

Your problem is, that you haven't installed the Adafruit_Sensor.h, which is a dependency of Adafruits DHT library. The README on Github for the DHT library also states this:

  You must have the following Arduino libraries installed to use this
  class:

Adafruit Unified Sensor Library

You can find the Adafruit_Sensor.h here at Github. Install it in your libraries folder. You can refer to the answer from per1234 for instructions on installing libraries.

--

The second part in your error output is not really an error. As others stated before, the IDE only tells you, which version of the DHT library it uses. If you want to have multiple version in your libraries folder, you will have to make sure, that you always use the correct one. If they are identical, you can delete one of them, if you want to. The outcome would not be any different, except for that the IDE doesn't have to tell you, which library it uses.


Send serial data to local server I am new to arduino coding.
I am reading data from serial port and storing it in char array.
I want to send that data to the local server but it is not getting converted to string

Code :

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server;
char* ssid = "Office RTPL";
char* password = "********";
char data[64];
char data1[64];
String str;
void setup()

{
  // put your setup code here, to run once:
  WiFi.begin(ssid,password);
  Serial.begin(115200);
  while(WiFi.status()!= WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
  server.on("/",[](){server.send(200,"text/plain","Data Test");});
  server.on("/toggle",serialData);
  server.begin();
}
void loop()
{
  // put your main code here, to run repeatedly:
  server.handleClient();
 ;
}
void serialData()
{
  if(Serial.available() > 0)
      {

        server.send(200,"text/plain","Data");
         for(int n=0; n<64; n++)
         {
           data[n] = (Serial.read());

         }
         String str (data);
         server.send(200,"text/plain",str);

  else
        {
        String no_data = "No Serial Data";
        server.send(200,"text/plain",no_data);
        delay(5000);
        }

}

Please help

As I mention in my answer about serial communication:

  Before reading, always make sure data is available. For example, this is wrong:

if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

  The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

In your code:

if(Serial.available() > 0)
    {
    server.send(200,"text/plain","Data");
     for(int n=0; n<64; n++)
     {
       data[n] = (Serial.read());

So you know that one byte is available, but you are reading 64. No, that won't work.


Implement two processes at the same time I am a beginner in arduino and due to the lockdown I have been learning it by implementing it on tinkercad. I have made a simulation where I have attached :

Servo Motor

Ultrasonic Sensor

Led Bulb

LCD display

to an arduino uno 3
My AIM :  When something falls under 30cm of the ultrasonic sensor, the servo motor starts from zero position and goes upto 180 degrees in a span of 20seconds and then goes back to its initial position. At the same time and led switches on for 20s and switches off when the motor returns back to its position.
I was able to successfully implement this. But then I added an lcd to show the time i.e time is initialized at 0seconds and then goes to 20 seconds and when the motor resets. Time also resets.
I was able to make a timer on another simulation and I tried to run it in this one by placing the code correctly but I am not able to figure out how?
The present code I have written keeps blinking the led at an interval of one second and the servo moves very very slowly.
Any sort of help will be amazing.
This is my simulation, I have made it public, you may copy and simulate it if you have a tinkercad account. Even without an account you can see how it looks.
Here is the code:
(Please ask if you want me to add comments some areas)
//library code for lcd
#include <LiquidCrystal.h>
//setting up pins
const int rs = 9, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

unsigned long readTime=20;

//servo motor
#include <Servo.h>
Servo servo_9;
int pos = 0;
//servo motor end

//ultrasonic sensor pin
const int pingPin = 12;

//lcd
signed short seconds;
char timeline[16];

void setup()
{

  servo_9.attach(13); //servo pin
  Serial.begin(9600);

  pinMode(11,OUTPUT);// led

  //lcd initialize
  lcd.begin(16, 2);
  lcd.print("Time : ");

}

void loop()
{

  long duration, cm;
  //Ultrasonic start
  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  cm = microsecondsToCentimeters(duration);

  // Print the distance
  Serial.print("Distance: ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  // ultrasonic end

  // the servo motor should activate when object is
  //less than 30cm close to the sensor

 if(cm < 30) {

  // sweep the servo from 0 to 180 degrees in steps
  // of 1 degrees
  for (pos = 0; pos <= 180; pos += 1) {

    // tell servo to go to position in variable 'pos'
    servo_9.write(pos);

     //LCD TIMER START
    lcd.setCursor(0, 1);
    sprintf(timeline,"%0.2d secs", seconds);
    lcd.print(timeline);
    delay(1000);
    seconds++;

    //led buld switch on
    digitalWrite(11,HIGH);

    // wait 20ms for servo to reach the position
    delay(200);

    //switch of the bulb
    digitalWrite(11,LOW);

  }

  //moving servo back to zero
  for (pos = 180; pos >= 0; pos -= 1) {
      // tell servo to go to position in variable 'pos'
      servo_9.write(pos);
      // wait 20 ms for servo to reach the position
      delay(20); // Wait for 15 millisecond(s)
            }

    } //if end

  delay(100);

}//loop end

//FUNCTIONS

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

Think of an Arduino as a circus clown spinning plates. It has to spend very little time on any one plate, and then it can keep a lot of plates spinning, moving quickly from one to the next.
That's how "multi-tasking" works on a realtime device like an Arduino. You write a loop function that buzzes through a bunch of sub-tasks, spending a few microseconds on each one, and then repeats the process. Each plate (sub-task) gets a little bit of time on each pass, but only a little.
The delay() function is the death of that. If you're in a delay(), everything comes to a screeching halt. Your program stops checking for button presses, stops switching output pins to control your motors, etc. It's like the clown taking a coffee break. The plates start crashing to the ground.
You might get away with single-digit delays for things like timing changes in output state (and delayMicroseconds() is rarely a problem since those delays are so short), but a delay(1000) means everything comes to a screeching halt for a full second.
You need to refactor your code to get rid of calls to delay() with delay values of more than a few milliseconds. Do a search on "Arduino blink without delay" to figure out how.
Note that on a single core device with preemptive multi-tasking, the circus clown analogy still holds, but now the OS serves as the clown's manager. The OS schedules the clown's time, and tells it when to switch between plates. If the clown gets distracted by a particularly shiny plate and tries to spend too long on that plate, the OS forces the clown to switch plates. The OS also saves the clown's current state each time it switches away from a task, and restores that state when it returns to that task.
On A multi-core device with preemptive multi-tasking, the manager (OS) has a team of clowns (cores). Each clown (core) gets assigned to different plates (tasks), and all the clowns work at the same time (The cores run concurrently.) The OS has to make sure the clowns (cores) don't bump elbows (have conflicting access to the same memory or other resources.)


Why does opening the Tools menu take so long? Every time I open the Tools menu, the IDE freezes for a few seconds. Why is that? It happens on both of my computers, and nothing I do makes a difference in how long it takes. I've tried restarting the IDE, unplugging my Uno, and many other things, but nothing helps.

I'm on windows, running IDE version 1.0.2.

It's an RXTX issue. RXTX is the native serial library used to make the IDE talk to the boards.

On some Windows installation, with some Bluetooth things (both dongles or integrated), when enumerating serial devices, these dongles scan the air for remote serial devices. Hence, the IDE stays stuck, waiting for RXTX serial device enumeration to end. This issue has been acknowledged a lot of times, see for example #1375, #532, #200 and #143

As far as I understand, this issue does not affect linux or mac because of the different way the scan occurs. On linux it's a plain filtered file listing of /dev. Similarly it's on mac. On windows, it uses native API calls.

Some fixes are available in the 1.5 series but I suggest switching to the latest 1.5.6 release as RXTX was replaced by JSSC, a more modern and simpler library.


Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain? I use ESP8266 and ESP32 with arduino toolchain rather than pure arduino hardware.
Arduino IDE is standard and proven but what are the other IDE and advantage/disadvantage ?

Not an exhaustive list. Most advantages will be subjective.

UECIDE - Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
PlatformIO (Available as plugin for Atom editor, MS Visual Studio and Eclipse IDE) - Automatic library updating, one ini file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
Arduino IDE for Visual Studio - For those who like VS?
Arduino Makefiles - More like old-school command-line coding, Linux-style development. Not an IDE.
Eclipse - Another quite popular IDE outside Arduino world.
Atmel/Microchip Studio 7 - Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.


Interfacing ADS8319 with Arduino UNO I am using Arduino UNO and trying to interface 2 16-bit ADS8319 ADCs with it via the SPI interface.

I have interfaced the 2 ADCs with the micro-controller using the "4 Wire CS Mode Without Busy Indicator" (data sheet page number 15).

I am using the following code to get the values from the ADCs.

#include <SPI.h>
#define CONVPIN 7
#define SELPIN 8
#define SELPIN2 4
#define MISOPIN 12
#define SCLKPIN 13

int adcvalue;
byte byte1; byte byte2;
const float aRefVoltage = 5;
float volts = 0;

void setup() {

  // put your setup code here, to run once:
  pinMode(SELPIN, OUTPUT); // ADC's selection pin
  pinMode(SELPIN2, OUTPUT); // 2nd ADC's selection pin
  pinMode(CONVPIN, OUTPUT); // ADC's conversion pin
  pinMode(SCLKPIN, OUTPUT); // ADC's clock pin
  pinMode(MISOPIN, INPUT);  // ADC's data out
  SPI.begin();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(CONVPIN, LOW);
  digitalWrite(SELPIN, HIGH);
  digitalWrite(SELPIN2, HIGH);
  digitalWrite(CONVPIN, HIGH);
  digitalWrite(SELPIN, LOW);

  delay(1000);

  byte1 = SPI.transfer(0x00); //transfer (read) 8 bits from the adc chip D15-8
  byte2 = SPI.transfer(0x00);  //transfer (read) the second 8 bits. D7-0

  adcvalue = (byte1 <<8) | (byte2 & 0xff);  // combine the 2 bytes to make our 16 bit word
  Serial.print("Voltage Value: ");
  Serial.println(adcvalue,BIN);
  volts = (adcvalue*aRefVoltage/65535);
  Serial.print(" Sensor Volts: ");
  Serial.println(volts,5);
  delay(1000);
}

However i am not getting the right values. The ADC that ive selected by "digitalWrite(SELPIN, LOW);" should output 1V, whereas the values keep on changing in between 0 and 2.2 V .I am not sure if my code is correct or not. Can you please verify the code so that i should know whether the problem is in my hardware, or the code.

Below is the screenshot for my schematic :

Your helpful suggestions and comments would be appreciated !
Thankyou.

After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.


How many I2C lines does the Arduino Due have? According to the Arduino pin Mapping

20  PB12    SDA 3   6
21  PB13    SCL 3   6
70  PA17    SDA1    3   6
71  PA18    SCL2    15  9

The first one seems pretty obvious, the second one though is confusing. They have different labels. I also do not see other SDA or SCL in the table. So is this a typo?

According to the Wire library documentation https://forum.arduino.cc/index.php?topic=132130.0:

  The Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to
  the AREF pin and the additional one is on pins 20 and 21.

And the table:

Arduino Due: 20 (SDA), 21 (SCL), SDA1, SCL1

So it seems in your table SCL2 should be SCL1.


Sending wireless data over with xbee s1 I am following this tutorial to learn about Arduino wireless communication. I have 2 Arduino unos with Xbee S1s sitting on Xbee Pro shields.

I've programmed the Xbee S1s by screening into the /dev/tty/* and configuring them with: +++, ATID1234, ATMY1000 (ATMY1001), ATDL1001 (ATDL1000) and ATWR. I've double checked the values to ensure they are correct.

So i've created a super simple Sender and Receiver package:

Sender.ino

int counter = 0;

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

void loop() {
  Serial.println(counter++);
  delay(1000);
}

Receiver.ino:

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

void loop() {
  Serial.println("Looping");
  while (Serial.available() == 0);    // wait
  int counter = Serial.parseInt();
  Serial.println(counter);
  Serial.flush();
  delay(500);
}

So first of all, when I upload my program to my arduino, I make sure that the S1s are not attached to the Pro shields which is attached to the unos.

When both of my unos are powered, I see a red light blinking but no indication of "busy blinking" which is supposed to happen when two XBee S1s are connected to the same channel. I am currently seeing a consistent blinking at about 1 second frequency.

Can someone tell me why I am only able to see "Looping" in my Serial monitor on my receiver?

blah reported:

  So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned.

Can someone vote this up please to remove it from the unanswered queue?


How do I pause a loop just once? I´m trying to make a pause in a loop, but just for the first time it loops. The next loops i would like the program to NOT do the pause. Just once time, each time a button is pressed. Does anybody knows how to do it?
Thanks!
This is the code i want to pause just once:
void loop() {
  if(digitalRead(switch_pin) == LOW){
    digitalWrite(led_green_pin,LOW);
    digitalWrite(led_red_pin,HIGH);
    lastMotionState    = currentMotionState;
    currentMotionState = digitalRead(MOTION_SENSOR_PIN); //
      if (currentMotionState == LOW && lastMotionState == HIGH) {
      servo.write(90);
      }
      else
      if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
      servo.write(0);
      }
  }

The following code will pause (Give some delay) when it runs for the first time and also when you press the button.

void loop() {
  static int status = true;
  if(status){
    //Pause
    delay(15);
    status=false;
    return;
  }

  if(digitalRead(switch_pin) == LOW){
    digitalWrite(led_green_pin,LOW);
    digitalWrite(led_red_pin,HIGH);
    lastMotionState    = currentMotionState;
    currentMotionState = digitalRead(MOTION_SENSOR_PIN); //
      if (currentMotionState == LOW && lastMotionState == HIGH) {
        servo.write(90);
      }
      else if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
        servo.write(0);
      }
  }
  else{
    status = true;
  }
}

Give delay according to your need.


Connect Arduino via TX RX Pins to Computer's USB Port I want to avoid using the big USB B connector to program my Arduino Mega. Since there are those RX TX Pins I thought, it would be possible, to connect my USB - Wires from my PC directly to those RX TX Pins. D+ -> TX and D- RX. This Post on Arduino Stackexchange says, those wires are just connected, while this post says the exact opposite.

I'm confused. Is it possible or would I damage my board when connecting USB wireq to RX / TX pins on my Arduino?

The first answer that you cite that you say says it is possible is in fact not talking about  what you are referring to  - it is discussing the use of the RX & TX pins directly when they are not being used for USB connection.

The second answer you cite is technically incorrect but "correct enough" in the context.

The answer to your question  is "It can be done but it requires a different boot loader, its slower, its technically inferior, it's less standard, it requires a degree of understanding (on someone's part) to get it going, and it can be done

It IS possible to access USB directly from digital I/O pins. As TX & RX are also standard digital I/O pins they could be used for this purpose BUT you need dedicated bootloader code to do this and it has inferior performance if a USB to serial converter is available. The eg ADAFruit Arduino Trinket uses this system.

Here is how the (or a)  ADAFRUIT Trinket Bootloader works. (The Trinket is not mentioned here but I'm told that this is what it uses. If not, it works in functionally the same manner).

This is in turn based on the USBaspLoader

A (very) simple "more or less Arduino compatible" development board which can use this system is Metaboard. It's circuit diagram is shown below. As can be seen - it uses an ATMega168 and the USB connection is made to two standard digital I/O pins.

"Metaboard" using ATMega168

note USB connection to pins PD2 & PD4 - NOT via RXD on PD0 and TXD on PD1 via a serial to USB converter, as is more usual.

AND another version:  AVRUSBBOOT

And again

BootloadHID   They say  -

BootloadHID is a USB boot loader for AVR microcontrollers. The uploader tool requires no kernel level driver on Windows and can therefore be run without installing any DLLs.

BootloadHID is a USB boot loader for AVR microcontrollers. It can be used on all AVRs with at least 2 kB of boot loader section, e.g. the popular ATMega8. The firmware is flashed into the upper 2 kB of the flash memory and takes control immediately after reset. If a certain hardware condition is met (this condition can be configured, e.g. a jumper), the boot loader waits for data on the USB interface and loads it into the remaining part of the flash memory. If the condition is not met, control is passed to the loaded firmware.

This boot loader is similar to Thomas Fischl’s avrusbboot, except that it is built on top of the HID device class. This implementation is more user friendly on Windows, since no kernel level drivers need to be installed.


C Serial Communication Code is unreliable This going to be a difficult to debug problem but I hope some ppl here have C knowledge and idea what's going on. Given an arduino nano which is controlled by a C program from WRT54G.

Here is the relevant part of the arduino code:

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

 int integerValue=0;

                              // Max value is 65535
char incomingByte;

void loop() {
  if (Serial.available() > 0) {   // something came across serial
    integerValue = 0;         // throw away previous integerValue
    while(1) {            // force into a loop until 'n' is received
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
      if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
      integerValue *= 10;  // shift left 1 decimal place
      // convert ASCII to integer, add, and shift left 1 decimal place
      integerValue = ((incomingByte - 48) + integerValue);

    }
   Serial.print("Command: ");
   Serial.println(integerValue);

  }
}

Pretty straight forward (it converts serial received ascii chars to numeric format), arduino receives a simple integer and it runs a function. For example 1-> turn on relay1. This work's reliably for sure because I can just do:

echo "1" > /dev/tts/1

from the terminal.

Now here is the relevant part of the C code:

    int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
    {
        char b[1];  // read expects an array, so we give it a 1-byte array
        int i=0;
        do {
            int n = read(fd, b, 1);  // read a char at a time
            if( n==-1) return -1;    // couldn't read
            if( n==0 ) {
                usleep( 1 * 1000 );  // wait 1 msec try again
                timeout--;
                continue;
            }
    #ifdef SERIALPORTDEBUG
            printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
    #endif
            buf[i] = b[0];
            i++;
        } while( b[0] != until && i < buf_max && timeout>0 );

        buf[i] = 0;  // null terminate the string
        return 0;
    }

    /* Only use integer commands */
    int serialport_write(int fd, int comm_no)
    {
        char command[6];

        sprintf(command,"%d\n",comm_no);
        printf("Sending Command:%s",command);

        int len = strlen(command);
        int n = write(fd, command, len);
        if( n!=len )
            return -1;
        return 0;
    }

void *ardu_handler(void *fdfd)
{
  int fd = *(int*)fdfd;
  char buf[256];
  char getback[10];

  while (1)
   {
     memset(buf, 0, sizeof(buf));
     serialport_read_until(fd, buf, '\n', 256, 5);
     fprintf(stderr, "Received: %s\n", buf);
   }
}

Then a C thread will be started with the ardu_handler which in this case doesn't do anything else just print's back the response from the ardu.

What's happening is when I send a command I start getting back infinite amount of commands (up until I close the C app and start it again) and to make it worse it is even inconsistent.

For example:

Command: 62143
Command: 7891
Command: 3216
Command: 11287
...
runs forever.

What I asking myself is whether these responses coming out from the arduino or they are just coming out from the bogous C program...
It's not possible to connect to see what's coming out on the serial port unfortunately until this program holds the port open.

Although I run the C code on mips this was doing the same thing back on x86 PC with an arduino uno (sometimes it is stable but then it falls into this unstable state and floods the serial port). It was unreliable and I would like to make it reliable.

I recommend you change the type of incomingByte to int, like was advised in the comments. Also, your null-termination is occurring past the end of buf; change the condition in the while statement to i < buf_max - 1, so that one byte is left for the null. Also use parentheses to separate those conditions, in the unlikely event there's some issue of precedence.


Converting a message received in char buffer to integer I am receiving a message from my mobile to my microcontroller via GSM. The message is in a char buffer, but I want to convert it to an integer as I want to perform some mathematical operations on it. I tried many functions such as atoi, toint but it's not working. Please let me know if there is any way in which I could do this conversion.

atoi() is the simplest way:

int val = atoi(buf);

If that doesn't work then your buffer doesn't start with the number you are after. If that is the case you will have to work out where in the buffer the number is and convert just that portion. How you do that depends on what the format of the data is in your buffer.


STM32 and SDFat - Can't create file in directory in SD I'm using the SdFat.h library on a STM32 and I can successfully create a file in the root directory using SD.open("test.txt", FILE_WRITE); but my code fails to create SD.open("DATA/data_test.txt", FILE_WRITE); in a directory.
Here's the piece of code that successfully creates a file in the root:

String final_book_name = upload_book_name + ".txt";
if (SD.exists(final_book_name.c_str())) {
  SD.remove(final_book_name.c_str());
}
tft.println(final_book_name); // This successfully prints "test.txt"
book_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name.c_str())) {
  tft.print("Created file");
} else {
  tft.print("Failed to create/replace\nfile!");
}

and here's the piece of the code that fails to create a file in a directory:

if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
}
String final_book_name = upload_book_name + ".txt";
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;
if (SD.exists(book_data_path.c_str())) {
  SD.remove(book_data_path.c_str());
}
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(book_data_path, FILE_WRITE);
if (SD.exists(book_data_path.c_str())) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name.c_str())) {
    SD.remove(final_book_name.c_str());
  }
}

I found the issue. I'm not creating the directory folder properly. When I checked the SD card from another device, the DATA folder was invalid, and creating it manually works. I'll look for a solution and post an update.

UPDATE: https://forum.arduino.cc/index.php?topic=421131.0 I'll try this tomorrow but it'll probably fix the issue.


What is the typical form for a finished Arduino project? I just started with Arduino. I am an experienced software developer so the programming side was already mostly known to me, and I am surprised at just how easy Arduino have made the hardware side of things, and how easy to use the various libraries are.
So for my first non tutorial project, I want to make air quality sensor web servers to be placed in several rooms throughout my house. I will then have a program running on my PC which collects readings from each sensor and stores then somewhere, to be analyzed later.

All I have right now is an Arduino UNO R3 starter kit, and I am having a WiFi shield delivered today. I feel confident that I can have a working version using the kit that I have shortly after the shield gets delivered.

But my question is: what is the best (some combination of easiest and cheapest) way to crank out half a dozen of these?

Presumably, most experienced makers don't include a breadboard in their finished products? I suppose I should buy a soldering iron.

Should I buy half a dozen UNO R3s and half a dozen WiFi shields (along with air quality sensors)? Or is there a cheaper option that is intended for semi-productionizing an Arduino project?

PS: I feel like the tags I have included barely intersect with the purpose of this question, so if you know of any more appropriate ones, feel free to suggest/edit.

I'm in the same boat as you (SW engineer by trade who likes to tinker with electronics, and is a "maker" at heart.)

I think the answer to your question is "it depends." For a one-off, a breadboard might be fine.

For half-a-dozen, you might want to get project cases and perf-boards, and solder up your design. (For the Mega, there is a very nice prototyping "shield" that brings all the pins from the Mega up on headers and has quite a bit of working room for soldering up circuits.) If you want to make more than a handful, though, you'd probably want to create a custom PC board. You can either create a design in a CAD program and send it off to be small-batch manufactured, or you can buy the equipment to do it yourself. If you make hundreds of units, you should think about ditching the Arduinos and designing a completely custom board using the AVR-family microcontroller and only the components you need.

(I'm still at the breadboard/hand soldered perf-board stage myself, and haven't created any custom PC boards yet, just read about it.)


Controlling multiple servos as one I want to attach multiple servos to Arduino but all them must receive same command. If it possible to connect all servos to one command pin (I don't want to use "for" in code to minimize processor time for operation)?

IMHO it is possible to connect more than one server PWM control inputs to a Arduino output pin.

The Servo input is something like a comparator with an very high resistance. So the servos should not influence each other in any way, nor will the output pin be overloaded.

Because of the input capacities of the servos, there might be a limit of the count of the servos.

And if you supply the servos with power from the arduino then, there is of cause a limit.

EDIT:

It is always a good idea to use buffers in a servo control circuit, to keep a sharp square wave signal. Parasitic capacities can reshape the signal even to a sinus signal.

That might confuse the servo control unit which works well only with a square wave (i.e a PWM-Signal).

simulate this circuit – Schematic created using CircuitLab


How to pass a static const (progmem) array to a function I'm implementing a voice synthesizer chip. To build a phrase, I create a list of phonemes like this:

static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

And to play them I do this:

 for (size_t i=0; i<sizeof(heybuddy); i++){
    say(pgm_read_byte(heybuddy+i));
 }

So what I'd like to do is create a function where I can just pass the array to a function that can take care of the loop and do some other maintenance stuff.

//what I've tried:
void sayPhrase(const uint8_t *phrase){
  int open = 0;
  for (size_t i=0; i<sizeof(*phrase); i++){

      if(pgm_read_byte(*phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(*phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(*phrase+i));
    }
}

But when it comes to passing a static const I'm lost I've tried passing it as a reference with * but nothing I do seems to work - I just don't know the proper way to do this in C.

What I have compiles, but it seems to only get one phoneme and repeat it over and over. The rest are lost.

The problem is, when you call sizeof(*phrase), what is returned is 1, the size of the uint8_t array element, the result of your pointer de-reference. On the other hand, if you call sizeof(phrase) inside the function, you get the size of the pointer itself and not the size of the array, as you might expect. When you pass the array to the function via a pointer, the function has no idea if you passed the start of an array to it or merely a pointer to some uint8_t variable, so it can't know what the size is; context has been lost.

Instead, you should call sizeof(phrase) in the same scope where the array was declared and initialized and pass the result to the function, which can then use this value in the for loop.

static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

size_t SIZE = sizeof(heybuddy);  // this is ok since each element = 1 byte

sayPhrase(phrase, SIZE);

The function definition should be:

void sayPhrase(const uint8_t *phrase, size_t size){
  int open = 0;
  for (size_t i=0; i < size; i++){

      if(pgm_read_byte(phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(phrase+i));
    }
}


Defining array in switch case I’m completely new to arduino, so be polite. I’m trying to program my esp32 to drive neopixels as seven segment display. So I take a digit and pass it to switch case and in switch case I mention which led number should be lit.
`

function showDigits(digit){

switch(digit){

 case 1:
   int a[]={1,3,4,.....};
  break;

 case 2:
    int a[]={1,3,4,6,8,...};
   break;
  .
  .
  .
default:
   int a[]={1,2,3,4,5,6,7,8,9,....};
  }
}

Now this is throwing multiple errors including redeclare of array a in same scope. Is there any better way to code this?

If you want to declare multiple variables with the same name inside different case statements, you can enclose the code inside each of them inside curly braces:

case 1:{
    Code...
break;}
case 2:
...

The curly braces will set the limits for the variables scope to just this case.


using seek() in Arduino to go to the end of a variable-sized file Anyone know how to use the seek() function of Arduino SD Library to position pointer at the end of a file?

If programming in Windows do something like:

void fileInsert(char *file, void *data, size_t len) {

    FILE *filePtr;

    if ((filePtr = fopen(file, "rb+")) == NULL) {
        printf("Arquivo %s não pode ser aberto.", file);
        exit(EPERM);

    } else {

        fseek(filePtr, 0L, SEEK_END);
        fwrite(data, len, 1, filePtr);
        fclose(filePtr);
    }
}

But the Arduino does not have the SEEK_END

You can only seek to an absolute position from the start of the file.  Fortunately there is the size() method that can tell you where the end is, though.

file.seek(file.size());


millis() vs creating a "long" variable I think my issue is not fully understanding how the millis() function works;

I am wondering the difference between simply creating a variable such as

long fake_millis  ++ ;

vs using millis()?

millis() returns the ACTUAL time milliseconds since the start of the program. Wheter you put a delay, you do multiple tasks, millis() will still return the right time.

The other method that you mentionned will not work if, for example, you add a delay in the program. Then, for more complex tasks that might take more time, your "custom" counter will be very unacurate.

I short, just use millis(). It is easy to use and works great.

P.S. Use an unsigned long instead of a long.


How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`? How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.

  avrdude: usbdev_open(): did not find any USB device "usb"

I've already added myself to the dialout group,

  sudo usermod -aG dialout $USER

And, I did that after I confirmed the dialout group owns the device (in my case /dev/ttyACM0:

$ ls /dev/ttyACM0 -l
crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]


Cleaning up code? Removing repetition? I am using Adafruit motor shield, I am running multiple DC motors for different amounts of time, but to start at the same time - I have researched that to do this I have to monitor the elapsed time of each motor in the loop instead of using the delay to avoid blocking if I want them to run at the same time.

Eventually, There will be around 10 DC motors running off this, however it seems very sloppy to me to have 10 repeat entries of very similar code.

Is there a way to create a class or something for the following code so I am not repeating it all as although it works it seems like the way I am currently doing it is bad practice(?) and could be done more eloquently! Forgive me if this is a strange question as I am new to arduino.

In this example there are only 2 motors, however when it gets to around 10, there will be a lot of code just for this bit!

Any suggestions are welcome.

Thanks in advance.

Example code:

#include <Wire.h>
#include <Adafruit_MotorShield.h>

boolean runMotor1 = false;
boolean Motor1Running = false;
unsigned long Motor1StartMillis;
unsigned long Motor1RunTime = 5000;

boolean runMotor2 = false;
boolean Motor2Running = false;
unsigned long Motor2StartMillis;
unsigned long Motor2RunTime = 10000;

//etc etc etc up to 10 Motors

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *MotorMotor1 = AFMS.getMotor(1);
Adafruit_DCMotor *MotorMotor2 = AFMS.getMotor(2);

void setup()
{
  Serial.begin(9600);
  AFMS.begin();
  runMotor1 = true;  // set condition to true for testing
  runMotor2 = true;
}
void loop()
{
/// Motor1 START
  if (runMotor1 == true) {
     Serial.println("Run Motor 1!");
     runMotor1 = false;
    MotorMotor1->setSpeed(255);
    MotorMotor1->run(FORWARD);
    Motor1StartMillis = millis();
    Motor1Running = true;
  }

  if( Motor1Running && (millis()-Motor1StartMillis > Motor1RunTime) )
  {
    Serial.println("Motor1 Time Elapsed!");
    MotorMotor1->setSpeed(0);
    MotorMotor1->run(RELEASE);
    runMotor1 = false;
    Motor1Running = false;
  }

  /// Motor 2
    if (runMotor2 == true) {
     Serial.println("Run Motor 2!");
     runMotor2 = false;
    MotorMotor2->setSpeed(255);
    MotorMotor2->run(FORWARD);
    Motor2StartMillis = millis();
    Motor2Running = true;
  }

  if( Motor2Running && (millis()-Motor2StartMillis > Motor2RunTime) )
  {
    Serial.println("Motor2 Time Elapsed!");
    MotorMotor2->setSpeed(0);
    MotorMotor2->run(RELEASE);
    runMotor2 = false;
    Motor2Running = false;
  }

}

Thanks for reading, and thank you for any input you may have.
Steve

You are perfectly right, a class would help simplify your code. Here is
a tentative class that should work for what you are doing:

class Motor
{
public:
    Motor(const char *_name, Adafruit_DCMotor *_motor,
          unsigned long _runTime)
    : name(_name), startNow(false), running(false),
      runTime(_runTime), motor(_motor) { }
    void start() { startNow = true; }
    void update();
private:
    const char *name;
    boolean startNow;
    boolean running;
    unsigned long startTime;
    unsigned long runTime;
    Adafruit_DCMotor *motor;
};

Most of this is almost copy-paste from your actual code, except for your
runMotorX variables that I renamed startNow, which seemed more
appropriate.

Beware that the name of the motor is copied as a pointer. Thus you
should better call the constructor with a literal string (like
"the name") as a first parameter. Otherwise it would be more
appropriate to allocate memory and copy the characters themselves, but I
like to avoid dynamic memory allocation on an Arduino if I can.

Now, all the code that you have in loop() for each motor would be the
Motor's update() method:

void Motor::update()
{
    if (startNow) {
        Serial.print("Run ");
        Serial.print(name);
        Serial.println('!');
        startNow = false;
        motor->setSpeed(255);
        motor->run(FORWARD);
        startTime = millis();
        running = true;
    }

    if (running && (millis()-startTime > runTime))
    {
        Serial.print(name);
        Serial.println(" Time Elapsed!");
        motor->setSpeed(0);
        motor->run(RELEASE);
        running = false;
    }
}

With this class, your code would now look like:

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor m1("Motor 1", AFMS.getMotor(1),  5000);
Motor m2("Motor 2", AFMS.getMotor(2), 10000);
//etc etc etc up to 10 Motors

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    m1.start();
    m2.start();
}

void loop()
{
    m1.update();
    m2.update();
}

Of course, when you get to 10 motors, this would still be annoying
repetition. You can simplify further by putting the motors in an array
and looping through it:

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor motors[] = {
    Motor("Motor 1", AFMS.getMotor(1),  5000),
    Motor("Motor 2", AFMS.getMotor(2), 10000)
    //etc etc etc up to 10 Motors
};
#define NUM_MOTORS (sizeof motors / sizeof motors[0])

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].start();
}

void loop()
{
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].update();
}


How to Communicate between arduinos wirelessly? I am doing a project where I need to send some numbers between arduinos. But it has to be wirelessly because they will be moving. How to Communicate between arduinos wirelessly? I need to send data between them. Wifi would be preferred.

Thank You.

You can use XBees. They are powerful and do provide wifi connections (the recent versions).

And you rely on well-designed devices which guarantee packet retransmission and they achieve up to 1km in an open field.

XBee still works with serial communications making them an excellent tool for your embedded project.

Just plug your Arduinos and write code to send/receive data. This library is a good start point for API mode.

If you don't mind using all the benefits from ZigBee protocol, just use AT mode where all you push in one side is sent to another via serial communication.


IDE avoiding math operation I have no idea why this has been happening:

byte potenciometro = 0;int redpin=9;

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

void loop() {
int valor=analogRead(potenciometro);  delay(50);
Serial.println();
Serial.print(valor, DEC);

analogWrite(redpin,valor);   }

This code above has been working just fine. However, i understand the LEDs will work properly with intensities that range from 1 to 255, so i replaced this line

Serial.print(valor, DEC);

for this
    Serial.print((valor/700)*255, DEC);

and all that the IDE has been returning since then is 0 as console output.

i tried also just

Serial.print(valor/700, DEC);

and i get nothing but 0s

anyone?

my arduino is the UNO version.

In the C family of programming languages, the division operator (/),
when used with integer arguments, provides an integer division. You
get the integer quotient, and you can use % to get the remainder.

If you want a floating point division, then at least one of the
arguments should be a floating point number. E.g.:

Serial.print(valor / 700.0 * 255);

(the DEC argument is redundant). The final result is then truncated to
an integer before being passed to Serial.print().

A better option, which is outlined in dhimaspw's answer, is to do the
multiplication before the division. This way you avoid costly floating
point operations. If you do that, however, you should be careful about
overflows: valor*255 can be as big as 1023 × 255
= 260865, which is larger than the maximum value an int can store
(215−1 = 32767). You should then write

Serial.print(valor * 255L / 700);

where the L suffix forces the operation to be carried using long
integers.

The simplest solution, however, is to use the Arduino function map(),
which does essentially the same as above:

Serial.print(map(valor, 0, 700, 0, 255));


Unable to store data in variable from Serial.read() I have a relay and bluetooth module connected to Arduino Uno. I send data such as digit 1 to the bluetooth module and I view it in the Serial Monitor. If I send 1 from serial monitor I get 4910 printed.

I would like to turn on the relay and have it stay on until I send a different digit. However, in my code below it doesnt work, the relay doesnt stay on.

Only, if I put the digital.write under while(Serial.available()) it works.

const int ledPin =  11;
int relayOn;

void setup() {

  //initialize serial port for logs
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);

}

void loop() {

  while (Serial.available()) {

      Serial.println("Data: ");

      Serial.println(Serial.read());

      if(Serial.read())
      {
        relayOn = Serial.parseInt();
      }

      while (relayOn > 1)
      {
        digitalWrite(ledPin, HIGH);

      }

    }

}

You could try something like (not tested):

void loop() {
 if(Serial.available()){
   input = Serial.parseInt();
   Serial.print("Data: ");
   Serial.println(input);
   if(input == 1){
      digitalWrite(RELAY, HIGH);
      digitalWrite(LED, HIGH);
   }
   else if(input == 2{
      digitalWrite(RELAY, LOW);
      digitalWrite(LED, LOW);
   }
 }
}

don't forget to declare input variable, use 1 to turn on, 2 off :)


Which Arduino-compatible microcontroller for 2 continuous analog audio recording and 2 digital pin snapshots every second? Apologies if the title is not very well worded. I'm new to electronics and trying to learn more about embedded systems too. I have a small project that requires recording an analog audio input at 8-bit at 40kHz and saving it every second in a SD card.

Although I know that I can do that with an ATmega328P chipset, I'm not sure if the processing power of ATmega328P will be good enough for further extension of the project.

Ideally I would like to be able to record two sound sources at the same time at around 40kHz -- 16 or 24-bit would be perfect, and capture two sensory data also every second.

This device should be able to run on a reasonably sized battery for at least two hours, but ideally up to eight hours.

I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project and the current draw of a Cortext-M3 series might be too much for this project too.

My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements -- in terms of processing power, or do I have to upgrade to something like the AT91SAM3X8E?

My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements

No. Not in the slightest.

Your primary requirement of sampling audio at, basically, CD quality (or better) requires the use of a proper CODEC chip - and to drive that you require a microcontroller that has I2S. None of the 8-bit AVR chips have that.

On top of that you will need a LOT of memory. Far far more than an 8 bit Arduino has.  Two channels of 16 bit audio at 44100Hz (CD quality) requires 176400 bytes per second.

You will need double that.

To both continuously record and save the data you will require DMA to do the recording.  The DMA reads the incoming data from I2S and stores it in one buffer. When that buffer is full you generate an interrupt and switch to a second buffer. You can then save the first buffer to SD - assuming that it can be done in under a second.  Note that SD cards, when controlled by SPI as they generally are on microcontrollers, are generally quite slow.

So with all that in mind:

  I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project

Overkill? No. Not suitable since it is not up to the task. Yes, it has I2S. Yes, it has DMA. But it doesn't have anywhere near enough memory.  You need for the audio alone 350 kilobytes (the SAM3X8E has up to 100 kilobytes) - not to mention memory required by the SD card's buffers.

So you're looking for a microcontroller that has full I2S support, DMA, and around half a megabyte of memory.  And those aren't small and cheap like the Arduino's 8-bit AVRs.


what is aref(analog reference) what is the analog reference, I know that it can be used as a voltage reference, but not exactly what  it is all about please someone help.

It is the reference voltage against which all other analog voltages (analog inputs) are measured against.

By default it is the same as the chip supply voltage (5V on most Arduino boards), so the analog inputs can measure between 0 and 5V.

If you connect the AREF pin to a lower voltage, say to the 3.3V pin (for convenience) and set the analog reference to EXTERNAL, you can then measure between 0 and 3.3V.

This is good if you are measuring a smaller voltage and want to get as much resolution in the analog reading. If you leave it at 5V and are measuring only up to, say, 3.3V, you're wasting all the analog reading values between 3.3V and 5V that could go to getting you more sensitivity.


Access serial monitor on linux cli? Using arduino-cli? I have an arduino uno connected via USB to a raspberry pi, the raspi is accessible via ssh only.
Just started a bit with arduino-cli ; I upload a sketch which reads my analog pins. How can I access the serial monitor to get the data??

Programs such as screen, minicom or (my favorite)
picocom are useful if you want bidirectional communication
between the Arduino and the host computer. If you only want to read
what the Arduino sends, that can be done with cat:
stty -F /dev/ttyACM0 raw 115200
cat /dev/ttyACM0


Programing in Assembly for the Digispark I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

The Arduino IDE build support assembly files (.S). Nerd Ralph has written a  blog on the subject. There you will find all the details and how to write both inline and pure assembly files. He is really god at digging out all the details and sharing his findings.


Measuring resistance conceptually and in code? How would I measure resistance over a certain length? In this case the resistance is variable.

What I have in my head is that you would output a certain amount of current from one pin, and measure how much comes back from the other.

I'm not sure if this would work, or how to implement it in code.

I've seen this forum post, but it's not making much sense to me.

How can I measure resistance?

you cant control current output to a pin BUT you know a pin output 5V (if using a 5V a arduino, 3.3v in other case).

Then what you need is a know resistence resitor, so you can set up a voltage divider and then read the resulting voltage with an analogRead. That give you a 10bit precision value that you can easily translate to a voltage, and then use the formula on the linked page to find R1 or R2 (depends on how you wired up your know resistor)


Error: "invalid use of non-static member function" while calling a function from my own class-method I'm having a bad time trying to call a correctly-working expression (ultra[currentSensor].ping_timer(echoCheck)) from an own class method (myclass::run) instead of from void loop().

I'm getting the following compiler error:
"invalid use of non-static member function".

If I call ultra[currentSensor].ping_timer(echoCheck) directly from void loop() it gives me no error, so I may be missing something.

Here's the (shortened) piece of code which is generating the error:

#include <NewPing.h>

#define ULTRA_NUM      3
#define MAX_DISTANCE 200

class myclass {
  public:

    void run();
    void echoCheck();

    unsigned int distance[ULTRA_NUM];
    uint8_t currentSensor = 0;
};

NewPing ultra[ULTRA_NUM] = {
  NewPing(4, 5, MAX_DISTANCE),
  NewPing(6, 7, MAX_DISTANCE),
  NewPing(8, 9, MAX_DISTANCE)
};

void myclass::run() {
// ....
      ultra[currentSensor].ping_timer(echoCheck);  // Compiler error
  }

void myclass::echoCheck() {
  if (ultra[currentSensor].check_timer())
    distance[currentSensor] = ultra[currentSensor].ping_result
}

ping_timer() is defined as it follows:

void NewPing::ping_timer(void (*userFunc)(void), unsigned int max_cm_distance) {
    if (max_cm_distance > 0) set_max_distance(max_cm_distance);

    if (!ping_trigger()) return;
    timer_us(ECHO_TIMER_FREQ, userFunc);
}

I hope any of you can help me!

Thanks in advance,

Eduardo

Edit:
What I am trying to do is to adapt this example (from NewPing Arduino Library) so that the sonar ping (sonar[currentSensor].ping_timer(echoCheck)) is done from a class method, and not from void loop().

The problem is that echo_check isn't void echo_check() but void echo_check(myclass *this) because it's a member function of a class.

You can make the whole thing static (along with run()) by:

class myclass {
    public:
        static void run();
        static void echo_check();
};

static void myclass::run() {
    ....
}

void myclass::echo_check() {
    ....
}

And then you call:

myclass::run();

instead of instantiating an object.


Infinite Loop on Pin Input (Teensy 3.1)? I have an infinite loop issue that keeps persisting in this code on my Teensy 3.1. This program is intended to take an input on Pin 0 and press the Enter key on the computer it is hooked into.

It is connected to a wire with no current but once a switch is flipped it should send a 5v Digital Signal blip to the Teensy and trigger it to run. It does function but it keeps getting caught in an infinite loop for some reason. Any help would be greatly appreciated!

// Global Variable
int signal_receiving_pin = 0;

void setup() {
  // Outputting for error checking
  Serial.begin(38400);

  // Readying the pin for input
  pinMode(signal_receiving_pin, INPUT);
}

void loop()
{
// If statement to check whether an input has been received
if (digitalRead(signal_receiving_pin) == HIGH)
{
  // If the signal has been detected..
  Serial.println("The signal has been received \n");
  Serial.println("Now sending the ENTER signal \n");

  // .. The ENTER key is sent to the computer
  //Keyboard.press(KEY_ENTER);
  //Keyboard.release(KEY_ENTER);

  // Waiting 1 minute before allowing more input
  //delay(60000); // Pause
}
else
{
  // If the signal is not detected..
  // it will let you know it isn't there
  Serial.println("Input not detected \n");
}
}

Try using the internal Pullup/Pulldown resistor to control the input when the pin is not connected to anything.  If you do not have a pullup/pulldown, then the input capacitance on the input pin circuitry can sample and hold the 5V unreliably.

...
void setup() {
  // Outputting for error checking
  Serial.begin(38400);

  // Readying the pin for input
  pinMode(signal_receiving_pin, INPUT_PULLDOWN);
}
...

You may want to uncomment the delay() or add some state logic trigger only one activation per each cycle of signal_receiving_pin


Semantics of local PROGMEM I want to create a class to better use strings in flash. At its core is the following

template<size_t N>
struct progstr
{
    constexpr progstr(const char (&str)[N])
        : progstr(str, make_index_sequence<N> {}) {}

    template<size_t... Is>
    constexpr progstr(const char (&str)[N], index_sequence<Is...>)
        : _str{str[Is]...} {}

    constexpr operator const char*() const {
        return _str;
    }

    const char _str[N] PROGMEM;
};

Where make_index_sequence and index_sequence are the same as those from <utility>.

The problem arises when I try to emulate PSTR

template<size_t N>
constexpr const char* pstr(const char (&str)[N])
{
    return progstr<N>{str};  // huh?
}

It even compiles. However

The returned pointer is "dangling", but it is pointing into flash memory. Will this work?
A constexpr function may be called with an array with runtime values, and that cannot possibly create the string in flash can it?

I tested with 100 chars string

const char*

Sketch uses 1566 bytes
Global variables use 288 bytes

with F macro

Sketch uses 1594 bytes
Global variables use 188 bytes

progstr <101> ps(...

Sketch uses 1618 bytes
Global variables use 288 bytes

const char* ps = pstr("...

Sketch uses 1502 bytes
Global variables use 188 bytes

the pstr version string has errors at the end, when printed.

sorry, the pstr function works only if previous sketch version put the string into flash memory. it is not in hex file.


Modular Coding - What types of code portions to convert into library files? Rationale and methods? I'm working on documentation and combining 2 pieces of code for testing parts of a larger project.

I'm supposed to comment and make the code very clear to people who will use it later and make sure it's modular. I'm supposed to make header files, to reference function chunks in the main code from just the #include(s).

I understand in C++, that the convention is that for each header files(?), .h, there is a .cpp, where the .h is the header file that declares all the content, and that the .cpp is where you define the .h, ie. implementation.

My supervisor told me to put more parts of the code into library files, because additional components will be added in the future -

  but confused because all the length comes from using already existing
  library files, just a specific pattern of calling pre-defined
  functions.

If I put the files into a .h, how do I reference all the calls?
Make a void setup () {}?

The compiled code is 348 lines right now. All it has are some #include(s), code to calibrate and read from 2 different sensors using I2C and SPI protocols, with 1 shared master an Adafruit Bluefruit nRF52832, and comments with links to datasheets.

The bulkiness is in the set-ups and the different ways to  represent data (have 24 lines just to print out data from 1 sensor).

Should the entire code be just calling built in functions from a library file? So people who read the code don't see the details so much?

It's very subjective what should and shouldn't be put in a library.

I use the simple rules:

If it's an atomic piece of code like a hardware driver, it's a library.
If it's something that could be used in multiple sketches, it's a library.

Maybe things like configuration options could be put in a header file (not a library - a header file in the sketch folder).

You could maybe split portions of your sketch into C++ files or INO files within the sketch (not a library - files in the sketch folder, and using INO files is easier since you don't need header files, the IDE does it all for you) to group things logically together and make it easier to manage (all the LCD code in one file, all the temperature sensor code in another file, that kind of thing).


Accessing two MPU-9250 DMP I want to use both IMU at the same time using the Sparkfun Library on a SAMD21 mini breakout board. Can anyone help?

The begin function is :

inv_error_t MPU9250_DMP::begin(void) {
  inv_error_t result;
  struct int_param_s int_param;
  Wire.begin();
  result = mpu_init(&int_param);
  if (result)
    return result;
  mpu_set_bypass(1); // Place all slaves (including compass) on primary bus
  setSensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS);
  _gSense = getGyroSens();
  _aSense = getAccelSens();
  return result;
}

Sorry, but I'm not 100% sure of what you are trying to do, I don't understand 'both imu the' in your question.  I think you are trying to use two identical boards at the same time.  (If not tell me so I can edit my answer)

You will need to modify the library so the begin function takes a parameter.
That parameter for MPU9250_DMP::begin then identifies the address of the device, this will need passing to Wire.begin() I think (you'll need to check the Wire.begin() function, I can't).

That should let you create two different instances of the class.

MPU9250_DMP apple;
MPU9250_DMP banana;
apple.begin(0x68);
banana.begin(0x69);


Problems stacking Arduino Shields I'm trying to stack the Adafruit Data Logger Shield https://learn.adafruit.com/adafruit-data-logger-shield/overview onto a CuteDigi Sim900 GPRS Shield so that I can upload data (collected eventually by a GPS breakout) to a server at certain intervals.

The problem is that I can't seem to get the two shields to play nicely together. I'm a beginner with the Arduino and electronics in general, so hopefully this is just a noob issue.

When I power on the GPRS Shield, the data logger stops outputting the Date/Time to the serial monitor. And when I turn the GPRS Shield off, the serial monitor continues again and shows the Date/Time from the data logger.

They don't share any pins that I'm aware of, and I've tried connecting a 7.4V li-po for external power with no success.

Any help is greatly appreciated!

Make sure you are using a software serial port for the GPRS shield.

If you aren't using the software serial port, then you are probably running into an issue with trying to read data over the only UART (serial) port while two devices are tryiing to use it.

It looks like there are two jumpers next to D0/D1 on the GPRS shield, I can't tell but I think if you remove those, the shield will use software serial over D7/D8.  If you do this, you'll have to code your program to use a software serial.  This wiki page on the GPRS shield if you need help with that.


Reading a string from Firebase and storing it as a CString I have a mobile app (done using MIT App Inventor) storing some values to a Firebase database. App inventor stores all the values as strings (i.e. with quotes, and strings have quotes enclosed within quotes eg. "\"hello\"").
I'm using this library to fetch data from Firebase to ESP8266. I'm using String var to store the value retrieved and then change it to a CString (trying to store it directly doesn't work) as below:
This doesn't work:
Firebase.get(firebaseData, "/SCHEDULE DETAILS/SCHEDULE1/FREQ FR");
Serial.print("node -- schedule1 /FREQ FR -- type: ");
Serial.println(firebaseData.dataType());
char * cstr1 = new char [33];
cstr1 = firebaseData.stringData();
Serial.print(" -- data: ");
Serial.println(cstr1);

This works:
Firebase.get(firebaseData, "/SCHEDULE DETAILS/SCHEDULE1/WEIGHT");
Serial.print("node -- schedule1/WEIGHT -- type: ");
Serial.println(firebaseData.dataType() ) ;
String dummy = firebaseData.stringData();
Serial.print(" -- data: ");
Serial.print(dummy);
char * cstr = new char [dummy.length()+1];
strcpy (cstr, dummy.c_str());
Serial.print(" -- data int type: ");
Serial.println(atoi(cstr)) ;

I have some more nodes to get data from and I've read that lots of Strings are a bad practice. While trying to find out more, I saw the source code and stringData function itself returns a CString:

I feel like I'm doing one step more than what is required! Any suggestions on how to go about this would be very useful!
Try1 Based on the answer from @Majenko, I tried this before adding to the library:
const char* get_cstring() {
  String str = "will it work" ;
  return str.c_str();
}

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

void loop() {
  const char *new_c = get_cstring();
  int len = strlen(new_c);

  for (int i = 0; i < len; i++) {
    Serial.println(new_c[i]);
    delay(1000);
  }
  Serial.println("----------");
}

But how do I access the contents, because it just prints garbage values; strlen(new_c) gives 2 (I'm guessing that's the amount of storage needed in bytes!?)
Thanks!

In returning a String object the Firebase first generates that String object and copies the C string data into it.
If you want to get at the raw C string data you will have to look at adding a new "getter" to the library to return the pointer to that C string data:
I'd write it for you, but since you posted a screenshot of the Firebase function, and the change from that code to the new code is very minor (just change the function name and the return type), I can't copy-and-paste it. And I'm not going to peer at that little image and type it all in again.
Incidentally, internally the Firebase library actually uses std::string, which is a better implementation of the same thing that String does. String was created because the Arduino compiler has no STL, and hence no std::string. Either way they both use dynamic allocation.


Arduino + simple DC motors? (4WD kit) I am trying to connect 4 small DC motors to Arduino, like those in the following image:

The specification for each of them is:

  Suggested Voltage: 3V DC;
  No Load Speed: 65 ± 10rpm;
  No Load Current: 125mA (170mA MAX).

But I have no useful knowledge in electronics to do so...

I would be really thankful if anyone could explain me why it is so difficult to connect DC motors to Arduino (I've heard about problems with the magnetic field, but I don't really understand why); and possible point me to an easy (and cheap) solution. I am, of course, willing to study (not expecting a complete solution).

I'm aware there are some shields for doing this kind of connection, but they are really expensive, and I've seen some people using only transistors or components like SN754410.

Thank you in advance! :-)

First you make 4 parallel H-Bridges, http://en.wikipedia.org/wiki/H_bridge then you attach it to an external powersource ( or attach directly to the battery to prevent burning your arduino )

Attach every up to a pin, making it high makes the motor running, you need 8 pins for this, eg pin 1 makes motor 1 go forward, pin 2 makes motor 1 go back and so.

This is by far the most practical solution, but it is the easiest, and can be done with 8 PNP and 8 NPN transistors.

If you don't know how transistors work i suggest https://www.youtube.com/watch?v=-td7YT-Pums collins lab, it is both educational and entertaining.


Use object of LiquidCrystal class within another class I am quite new to C++ and hope that I don't bore you too much with my question.

I want to use an object of LiquidCrystal Class in another class called "Display_ManagerClass". I followed the instructions of the 2nd alternative in the following link:

Use object of other class within class

Unfortunately, I receive a linker error.

.ino-file:

#include "Licht_Manager.h"
#include "Display_Manager.h"
#include "Zeit_Manager.h"

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);

void setup()
{

    Licht_Manager.init();
    Display_Manager.init(&lcd);
}

void loop()
{
    Display_Manager.showText("Hello", "World");
    while (1)
    {
        Licht_Manager.blink(1);
    }
}

Display_Manager.h:

#ifndef _DISPLAY_MANAGER_h
#define _DISPLAY_MANAGER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <LiquidCrystal/src/LiquidCrystal.h>

class Display_ManagerClass
{
    protected:

    public:
        //void init();
        void init(LiquidCrystal* _p_lcd);
        void showText(String DisplayText1, String DisplayText2);
    private:
        LiquidCrystal* p_lcd;

};

extern Display_ManagerClass Display_Manager;

#endif

Display_Manager.cpp:

#include "Display_Manager.h"

void Display_ManagerClass::init(LiquidCrystal* _p_lcd)
{
    p_lcd = _p_lcd;
    p_lcd->clear();
}

void Display_ManagerClass::showText(String DisplayText1, String DisplayText2)
{
    p_lcd->clear();
    p_lcd->setCursor(0,0);
    p_lcd->print(DisplayText1);
    p_lcd->setCursor(0,1);
    p_lcd->print(DisplayText2);
}

Display_ManagerClass Display_Manager;

I receive the following errors:

Display_Manager.cpp.o:In function `Display_ManagerClass::init(LiquidCrystal*)
Display_Manager.cpp:clear()
Display_Manager.cpp.o:In function `Display_ManagerClass::showText(String, String)
Display_Manager.cpp:clear()
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

I made sure that the correct directory of the library is set up in the project properties. The library also works in the normal way, but in combination with the class it doesn't.

I work with Atmel Studio 7 in combination with VisualMicro, Arduino IDE 1.6 and Arduino Uno.

Thank you in advance.

You must also include LiquidCrystal.h in your sketch. That way the IDE will know to include it in the list of files to compile and link with your sketch.


How to load scal factor external to the code? We know that, we need calibration factors (scale factors) to read current sensor data (ACS758) to arduino. I am also using voltage reader using voltage divider circuit for my project. I need to build 5 such boards and need to change calibration factor in main program everytime due to tolerance of componenets. Currently for one of my board reference_factor is 0.81 and this will change due to resistor tolerance for other boards.

Because of this issue I need to maintain 5 different codes for 5 different boards. These sensor values controls on and off of certain relays. (Not shown in the code).

can I load this referrence_factor externally through text file or as any other medium so that I need not change the code everytime.? I am using arduino Nano.

int reference_Factor = 0.81;

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

void loop() {
  // read the raw data coming in on analog pin 0:
  int lightLevel = analogRead(A0);
  // Convert the raw data value (0 - 1023) to voltage (0.0V - 5.0V):
  float voltage = lightLevel * reference_factor;
  // write the voltage value to the serial monitor:
  Serial.println(voltage);
}

As written in the comments you coulduse eepron, but in your scenario it has one big disadvantage: Everything has to be written at compile time (aka when you programm the Nano, you have also to fill the eeprom with the relevant values), so e.g. if you have a temperature depending factor you want to change while on the field...
I would go for a SD-card reader:

Cheap to get (2$)
Easy to handle in code (read from a file is a standard function)
using a PC compatible file systen FAT enables reading/writing onto the SD card on a PC/other device without recompiling your code.
If you switch sensors for whatever reason, just write a new scale.txt file to the SD-card, insert and reboot the nano to get the new values
you could still use eeprom as a fallback scenario

As a tip (also mentioned in the comments by Delta_G) int for something like 0.01 is not what you want - define as float and watch out for the "conversion trap" when using with other variables not defined as float.


CH340 max serial speed With an Arduino-like board using a CH340 USB Serial chip, I'd like to send text lines as fast as possible to a Raspberry Pi through USB using the Serial.println() function. The problem is that when I set the serial speed to values above 230 400 with the Serial.begin(speed) function, the Arduino console crashes and the C program on the Rapsberry Pi displays garbage in its console, even though I set the same serial speed.

Short examples :

Serial.begin(230400);
Serial.println("Test !"); // Works fine.

Serial.begin(250000);     // Or any speed above 250 000.
Serial.println("Test !"); // Doesn't work at all.

This answered question states that 2 Mbauds is possible, so I'm a bit lost.

The Arduino IDE console offers various speed from 300 to 2 000 000 bauds, so why don't speeds above 230 400 work ?

CHG340 supports common baud rates: 50, 75, 100, 110, 134.5, 150, 300, 600, 900, 1200, 1800, 2400, 3600, 4800, 9600, 14400, 19200, 28800, 33600, 38400, 56000, 57600, 76800, 115200, 128000, 153600, 230400, 460800, 921600, 1500000, 2000000 baud.

250 000 baud isn't supported by that IC.

The Baud steps is either 200% or 150% of the previous value (There is exceptions).

Tested and working Baud rates.

I used putty as serial monitor since the built in monitor didn't have all baud rates preprogrammed.

SpeedTest.ino

// Serial port Baudrates:
// const int Speed = 115200;
// const int Speed = 128000;
// const int Speed = 153600;
// const int Speed = 230400;
// const int Speed = 460800;
// const int Speed = 921600;
// const int Speed = 1500000;
const int Speed = 2000000;

void setup() {
  // Initialize serial:
  Serial.begin(Speed);

  // Initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  Serial.print("Speed :  ");
  Serial.println(Speed);
}


Neopixels with I/O expander Because I have no pins available on my Wemos D1 mini, I want to drive my Neopixel ring from a MCP23008 I/O expander.

I'm trying to run the 'simple' example from the Adafruit_neopixel library. How do I declare the Neopixel pin number when using say pin 0 on the MCP23008 - or is this impossible?

I don't think that will be an option. The NeoPixel parts need very tight control of the timing in order to work, if the pin timing is wrong by 100 us the wrong data will get latched in.

Can you move some other functions / pins onto the IO expander and then drive the neopixels directly from the processor?


Using Arduino as ISP and SoftwareSerial at the same time I'm trying to use my Arduino Uno as an ISP to program an ATTiny85 and at the same time check my board by using the SoftwareSerial library to output the values I'm getting from my sensor.

Is this actually possible? Or does it require 2 different setups? Because I found a lot of tutorials and threads about one or the other, but never both. Which I find odd because once you send your program to the chip you might want to test it as well (or debug it).

Many thanks for your help and input! :)

I'm not really sure, but in the Arduino ISP example there is an if that looks if the ISP is in program-mode. You could try adding in the else statement of that if the Software Serial part.


writing very long function I'm writing an Arduino program, and I need to write a function to input some numbers trough a computer connected to it trough the serial interface.

This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.

What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:

class GetNumbers {
    public:
        //using the constructor as what I called "main" function
        GetNumbers(int arg1, char arg2) {
            performFirstAction();
            performSecondAction();
            ...
        }
    private:
        performFirstAction() {...};
        performSecondAction() {...};
        ...

        bool aSharedVariable;
        int anotherVariable;
        ...
};

And where I actually need to input those numbers from the computer:

GetNumbers uselessName (x,y);

Making the "main" function a normal class method (and not the constructor) seems to be even worse:

GetNumbers myClass;
myClass.getNumbers(x,y);
...
//somewhere else in the same scope
myClass.getNumbers(r,s);

Maybe it's my background of old C programmer but... I would just write
plain functions, no classes, like in C. And I would keep all this stuff
in a single file, to provide some form of encapsulation:

my_parser.h:

some_type get_numbers(int arg1, char arg2);

my_parser.cpp:

static int performFirstAction(float arg1, int arg2, char arg3)
{...}

static bool performSecondAction(long arg1, void *arg2, int arg3)
{...}

some_type get_numbers(int arg1, char arg2)
{...}

Note that there is only one function declared in the .h: this is the
“interface” to your module. Note also that all the other functions are
defined as static. This tells the compiler to keep them hidden from
the linking phase, so they do not pollute the global namespace. And
finally, note that there is no global shared variable: everything is
passed as arguments to the functions.

The rationale for the last point is that this helps the compiler
optimize things. A static function that is called only once is almost
guaranteed to be inlined by the compiler. Which means there is no
overhead in passing the arguments. On the other hand, if you use global
variables and the compiler doesn't manage to optimize them away, you
will incur the cost of RAM access.


Convert a char array to Flash string I would like to pass a formatted string to a method that accepts a __FlashStringHelper. Here is the method signature:
void myMethod(const __FlashStringHelper *str);

I have been using snprintf to format my string:
char cmd[30];
snprintf(cmd, 30, "There are %d seconds in a minute", 60);
myMethod(F(&cmd[0]));

Clearly the above doesn't work but how can I format a Flash String?
EDIT: I need to include an integer variable in my flash string. In the example above, '60' is a variable.
uint8_t nSeconds = 60;
char cmd[30];
snprintf(cmd, 30, "There are %d seconds in a minute", nSeconds);
myMethod(F(&cmd[0]));

Direct answer
F() takes immutable string literals, that are known at compile time, and places them into flash ("PROGMEM") instead of RAM.  snprintf() creates strings at runtime and places them into a mutable array.  The two things are fundamentally incompatible.
Limited compile-time concatenation
A very limited form of what you're trying to do could probably done like this:
#define MY_STRINGIZE(x) #x

myMethod(F("There are " MY_STRINGIZE(60) " seconds in a minute"));

This expands to:
myMethod(F("There are " "60" " seconds in a minute"));

Adjacent string literals are concatenated together, which makes this:
myMethod(F("There are 60 seconds in a minute"));

All that said, you could just write 60 in there directly.  And there's none of snprintf's formatting capabilities possible here.
There is not a compile-time version of snprintf available in Arduino.  And I don't think the features of the C++ (or C) language are there to support the creation of one either.  Odds are there is a better way of achieving what you really want to do.
Working around this altogether
Often it's not necessary to concatenate strings at all, particularly if you're just to turn around and write them to a Stream, or more generally Print subclass, e.g. Serial, LCD, SDFile, SoftwareSerial, etc.  Concatenating things for you is a large part of what these do.  It is not necessarily to do it yourself in advance.
If you have a string literal and constant (or variable) and want to keep as much of it out of RAM as possible, using two separate .print()/.println() helps you do this:
printCapableThing.print(F("AT+CIPSTAT="));
printCapableThing.println(index);

F() places "AT+CIPSTAT=" into flash.
If index is a constant it will also wind not being resident in RAM.

Side note
I realize you're asking about, getting as much into flash as possible, but I also can't help but point out this same basic technique applies to this otherwise awful idea, for somewhat different reasons:
Serial.println(String(F("Key ")) + keyname + " : " + value);

This creates a horrific mess of allocations and deallocations and unnecessary copying, where if you just let the Stream/Print object do its job by calling print()/println() multiple times.  The result code is more reliable, smaller, and where not I/O-bound, faster when you do.


Selecting a MOSFET Shield Im building an electrical system for my EBike.  My bike has 2 power sources, one is the 48 volt battery, the other is a 12 power converter coming off the battery pack.  I need an arduino shield that has 4 switching channels.  2 that can take in the 48 volt and switch it on and off, and two that can take in the 12 volt and switch it on and off.  Something that can take the 12 volt to power the arduino uno would be nice but I can find a chip to do that if necessary.

Since these are lights, normally off would be more more efficient but with the power consumption we are talking about, i can probably run the battery all day to the point of dry and the fets eat all of 50 feet worth of power staying closed.

Does anyone know of anything like that?  I found several shields out there like this but all of them seem to be setup to take 1 voltage input and switch it between the 4 or 6 fets on the board, not different voltages per fet and since I'm a programmer, not an EE so I have trouble reading the schematics.

Because my grounds have to be tied, its easier to switch the positive on and off than the negative.

You can make your own. Buy a protoshield and 4 fets (and a few resistors).

You can also use the shield you linked to, by not using the + terminals on the board. Just connect the + of the lights directly to the battery and only the - of the light to the shield.

The Uno can be powered by up-to 20V, so you can connect it directly to the battery.


ESP32 - `Brownout detector was triggered ` upon Wifi begin I'm Using an ESP32 - NodeMCU. One of the MCU's is acting weird upon boot, while at start I thought it was something to do with its sleep cycle. But, it seems that even on a minimal code as shown below, I get this message at the Serial output: Brownout detector was triggered
void setup()
{
  Serial.begin(9600);
  Serial.println("\nBegin");
  Serial.println(bootCounter);

  WiFi.begin("Xiaomi", "guy");

  while (WiFi.status() != WL_CONNECTED && millis())
  {
    delay(200);
    Serial.print(".");
  }
}

Edit 1: attaching MCU picture.
Can someone please explain ?
Edit 2: A workaround
stop alerting

Those boards have an inherent weakness in that they don't provide enough decoupling capacitance for the module.
Not all modules are quite the same, and some have more internal decoupling than others (not by design, just due to component tolerances).
I have found that unless you provide adequate decoupling of your own some modules work just fine and some don't. Some brown-out and some fail to flash.
For all my designs now I always provide both a 100nF and an 10uF capacitor right at the power pins of the module. However those boards don't provide anything like that.
You need to modify the board to add a capacitor (about 10uF) directly across the power and ground pins (pins 1[ground]-2
[3.3v]) of the ESP32 module. I like to use an 0805 MLCC capacitor as they fit nicely across the pins and are discrete, but they can be tricky for a novice to solder. So an electrolytic through-hole capacitor can be a simpler proposition (make sure you get the polarity right).