How to power two stacked motor shields with one 3S Lipo battery (11.1V)? I have these 2 motor shields:
Adafruit Motor Shield V2 and
Seed Motor Shield V2.

They are stacked on top of an Arduino UNO.

My question is, how can I power 2 of those motor shields with one 3S Lipo battery(Turnigy 3S 2200mAh 20C), given that I have 6 identical 4.6-6V DC gearmotors?

Thanks!

You can avoid using a linear voltage regulator. Try using this voltage regulator.

You will get 5 Volts 2 Amp output which should be easy to connect to motor shield's input power ports.


It is possible an Arduino generate 3d graphics on tft or vga It is possible to an Arduino render 3d graphics like very low polygonal 3d models or generating lighting efects non realtime shadows or realtime shadows and reflections. Rendering like first 3d video game consoles.
Someone can ask why you don't use an Rasberry Pi. Beacuse Linux can be more complex. Also Rasberry Pi is a computer runs Linux .Linux is hard and some people can say you can install Windows but it doesn't give freedom as Arduino on Arduino you have more control on system.It doesn't run operating system but Rasberry pi runs and you needed write programs for it. You can't do much  anything ( at least i know) than Linux or Windows will allow.

My goal was running very basic 3d graphics on a Vga.
Theres no rule it can be like old dos games.Fake 3d effect like distorting sprites to look like 3d and rotate them move change coordinates change camera position like a 3d but it's actually generating fake depth.
Must camera position controllable . Like a video game.

Sprites,effects are completely pre rendered. Only realtime rendered thing was distorting sprites by camera position. Changing room (Square area will reset view that will make after another room it would show another room).

Is there a library can done that?

Your solution can be for another Arduinos.

Your solution can be Arduino dependent. Like only works for due,mega etc.

Theres a vga library for Due supports 256 colors your solution can use this library problary called DueVGA

On AVR based Arduinos: No, definitely not. It is possible to create a VGA signal, but only with very limited resolution and few colors (like 4 or so) and also a framerate, that will not be enough. Also they all have too few memory.

It might be possible on the Due (don't have much experience with it), but it is still a bad choice for a platform (also partly because the Due is in general such a bad designed board with no good documentation).

  Is there a library can done that?

I don't think, that you will find any library doing all what you want. You might find libraries, that help you draw on the display, but you will do all the hard stuff (creating and loading sprites, distorting them, animating them) yourself. This is, because Arduino is a bad choice for such a project.

Also: In the title you mentioned TFT. I guess you meant one of the TFT display modules, that you can connect to Arduinos. Forget about that. They are connected over rather slow serial data interfaces (not meaning the Arduino Serial here, but serial interfaces like I2C or SPI). You won't get a sufficient frame rate with them.

I would oppose your arguments against the Raspberry Pi. Sure, it has an OS, but that also means, that it can make use of a variety of languages and frameworks. You are not bound to plain C/C++. You can use the language or framework, that best suites your needs. That can be a bit complex at first to find the right one. But thats, because your project is complex. What you are describing is a very complex task, when you cannot rely on others, that have already implemented the hard stuff (which would be the case for the Arduino).

Also a Raspberry Pi has plenty of RAM and plenty of storage space. It runs at high speed and is actually capable of outputting video with a good framerate.

Without wanting to offend you: I think, as you are asking this question here, you are not qualified enough yet to do such a project on an Arduino. There are insanely capable people out there (wouldn't count myself to them), who do incredible things with Arduinos by milking the very last drop of resources out of them. But they are doing it for the grind, not for having a functioning product at the end. I guess you want this to work good at the end, without needing you to work on it for many years. Then you are result-focused and should choose the correct platform for this. A computer (like the Pi) will be easier.

  Rasberry Pi had lot of things but some of them are unnecessary.

Yes, but is that really a problem? Is the unused potential really a no-go for the project? You could say the same thing about an Arduino. It has a lot of peripherals build in (depending on type Timers, Comparators, ADCs, DACs, several communication interfaces, power management peripherals, ...). Almost no project uses all of them. But that's simply the difference between general purpose chips/boards (like all Arduinos or Raspberry Pis) and custom made chips for a single purpose. If (!) a fitting chip for your project exists, that really only has what you need, it will most likely be very expensive. Chips for a single very narrow purpose have a very narrow target group, thus are more expensive (simple economy here). Companies have formally nearly everytime designed their own chips for gaming consoles (which is way beyond your current scope), like PS1 or N64. Current gaming consoles rely often on modified standard hardware, also because it is cheaper. The really old gaming consoles used the generic electronical chips, which means, that you didn't have one single programmable chip. Instead lots of the logic was build into the electronic design.

So you will always have some excessive features, that are not used. Why would you want to remove them from the project, just for the fuzzy goal of not wasting features. It will make your project only more complex and expensive. You will gain nearly nothing from minimizing the resources. This is a hobby project, not for selling it.

  In rasberry pi you just writing a computer program.You don't have much control like arduino

That depends on what type of control you mean. On a computer you are writing code on a higher level of abstraction. That also makes it easier to do complex things, since you can rely on the low level programming of others. What control do you want to have over the system, that you don't have on a computer like the Pi? Do you think, you can program better display drivers or graphic renderers, than all the other people? Then you can still do that on the Pi. A Pi also gives you control over the GPIO pins, which let's you do many hardware things, that you can also do on an Arduino.

Also Linux is open source. If you think, you need more low level interaction with the hardware (cannot think of a reason for needing it), then you can build your own OS, which gives you the needed freedom. Sure, that is very complex. But when you are able to use the low level programming, then you are also able to change the OS.

You seem to already have chosen the Arduino for your project. I, like others, have advised you to use a Pi instead to make it a lot easier and better. It is up to you, if you want to believe us or not. All in all I'm still not convinced, that you are able to pull that off on the Arduino platform, while still getting good results. You are simply not at that point of knowledge yet. You write confidently about the problems with an OS, while you don't seem to have a concept about the exact structure of these problems and how they impact you. We will not prevent you from doing it the hard way. Please for free to choose your own way.


restart counter of elapsed millis willingly with read When I trigger high it will count for as long as I ask it while I am high then shut off. I am able to start counting again whenever I want by triggering low and going back to high and it starts from the beginning as long as the time in low is not within the time I asked it to be high. The problem is I go low mid count then quickly back to high the count picks up where millis left off without starting from the beginning. Is there a way to make this better.

unsigned long induceTime = 0;
unsigned long elapseTime;
long setTime = 10000;
int openClose;
int openClosePin = 2;
int writeToPin = 3;
void setup() {
Serial.begin(9600);
}

void loop() {
  int openClose = digitalRead(openClosePin);
  elapseTime = millis();
  if (openClose == HIGH && elapseTime < induceTime + setTime){
    digitalWrite(writeToPin, HIGH);
    Serial.println(' ');
    Serial.println(elapseTime);
    Serial.println(' ');
    Serial.println(induceTime);
    Serial.println(' ');
}
  if (openClose == LOW && elapseTime > induceTime + setTime){
    induceTime = elapseTime;
    Serial.println(elapseTime);
    Serial.println(induceTime);
}

delay(500);
}

Thanks for the help, this code is closer to what I was looking for. This is for a water level pump, when the trigger is high it turns on, when the water rises the trigger goes low and stays on during the timer as a failsafe and then turns off with when the elapsed time is greater than the set time and also not in my code it turns off with a additional trigger. Here is my working code.

unsigned long induceTime = 0;
unsigned long elapseTime;
long setTime = 10000;
int openClose;
int openClosePin = 2;
int writeToPin = 3;
void setup() {
Serial.begin(9600);
}

void loop() {
  int openClose = digitalRead(openClosePin);
  elapseTime = millis();
  if (openClose == HIGH){                //reset count
    induceTime = millis();
    digitalWrite(writeToPin, HIGH);
    Serial.println(induceTime);
}
  if (openClose == LOW){
    elapseTime = millis() - induceTime;  //induceTime is set when leave high
    if (elapseTime < setTime){
      digitalWrite(writeToPin, HIGH);
      Serial.println(elapseTime);
      Serial.println("within setTime high");
}
    if (elapseTime > setTime){
      digitalWrite(writeToPin, LOW);
      Serial.println(elapseTime);
      Serial.println("within setTime for low");
}
    Serial.println(' ');
    Serial.println(elapseTime);
    Serial.println(' ');
    Serial.println(induceTime);
    Serial.println(' ');
}
delay(1000);                              //so that I can see serial monitor
}


Receiving hex data from terminal I am trying to transmit serial data from terminal to Arduino and I want to reconfirm that its the same data. But I am not able to get the right answer. I want data to be HEX. I want to check only the third last and last bytes since they will be changing every time.

I tried to write it in 2 different ways but none worked.

First try:

byte thisByte[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
void setup()
{
  // start serial port at 9600 bps:
  Serial.begin(9600);
}

void loop()
{
  while (Serial.available())
  {
    delay(250);
    // get the new byte:
    byte thisByte = Serial.read();
    // add it to the inputString:
    //inputString += char(intChar);

    if(thisByte == 0x03 || thisByte == 0x03)
    {
      Serial.print(thisByte, 'Hello');
      //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(50);             // wait for a second
      Serial.print(thisByte, 'Nothing');
      //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    }
    Serial.print(thisByte,HEX);
    Serial.print(" | ");
  }
}

Second try:

const byte message[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
boolean found = false;

byte byte1 = 0xAA;
byte byte2 = 0xBB;
byte byte3 = 0x06;
byte byte4 = 0x00;
byte byte5 = 0x00;
byte byte6 = 0x00;
byte byte7 = 0x01;
byte byte8 = 0x01;
byte byte9 = 0x03;
byte byte10 = 0x03;

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

void loop() {
  // put your main code here, to run repeatedly:
  // put your main code here, to run repeatedly:
  //int hexIn = Serial.read();
  //Serial.write(message,2);
  //Serial.write(message,sizeof(message));
  //delay(500000);
  while(Serial.available())
  {
    delay(10);  //small delay to allow input buffer to fill
    byte c = Serial.read();
    byte message = c;

    //Serial.print(c,HEX);
    //Serial.print(" | ");

    //if (c =!byte 0xAA && c =!byte 1 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA);

    if (c == message);
    //Serial.print("I received: ");
    Serial.println(c);

    // byte c = Serial.read();  //gets one byte from serial buffer
    // readmessage += c;
  } //makes the string readString
  //Serial.print(messsage);
  //readString=""; //clears variable for new input
}

First, you have to understand what “hex” means. Basically, you are
representing binary data as text, where each byte is represented as
two characters. For example, the number 42 is represented as either “2A”
or “2a”. In C and C++, you can write this number as 0x2a, but I assume
your serial stream sends the raw hex data, without the “0x” prefix.
Thus, on the serial stream you may receive the character “2” (character
code 0x32 = 50 in decimal) followed, some time later, by “a” (charcode
0x61 = 97).

What you need is a conversion routine that takes these characters and
reconstructs the binary data out of them. Here is one such routine I
use. You have to provide it with an input string in and an output
array out large enough to store the resulting binary data. The
function will return the number of bytes filled in *size:

/*
 * Convert an hex string to binary. Spaces are allowed between bytes.
 * The output array is supposed to be large enough.
 * On return, *size is the size of the byte array.
 */
static void hex2bin(uint8_t *out, const char *in, size_t *size)
{
    size_t sz = 0;
    while (*in) {
        while (*in == ' ') in++;  // skip spaces
        if (!*in) break;
        uint8_t c = *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
        in++;
        c <<= 4;
        if (!*in) break;
        c |= *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
        in++;
        *out++ = c;
        sz++;
    }
    *size = sz;
}

As a mere convenience, the function above accepts spaces within the
string, but only between bytes. Notice however that it does not attempt
to do any error checking. You may want to improve it in this respect.

Next, you have to devise a way to frame your messages on the serial
line. Serial does not provide any framing per se: it only transmits byte
one by one. When dealing with text, a common scheme is to send a
carriage return (\r) to indicate the end of a message. With this
convention, you sketch has to buffer the bytes it receives until it
sees a carriage return. Then it can process the whole message as a
whole. This approach is nicely explained in the blog post Reading
Serial on the
Arduino,
by Majenko, a regular contributor to this site.

Here is an example that reads an hex string, converts it to binary, and
then sends it back as hex again:

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

void loop()
{
    static char buffer[1024];
    static size_t length = 0;

    if (Serial.available()) {
        char c = Serial.read();

        // On carriage return, process the received data.
        if (c == '\r') {
            Serial.println();  // echo

            // Properly terminate the string.
            buffer[length] = '\0';

            // Convert the hex data to a byte array.
            size_t byte_count = length/2;
            uint8_t data[byte_count];
            hex2bin(data, buffer, &byte_count);

            // Echo back the byte array in hex.
            for (size_t i = 0; i < byte_count; i++) {
                Serial.print(data[i], HEX);
                Serial.print(" ");
            }
            Serial.println();

            // Reset the buffer for next line.
            length = 0;
        }

        // Otherwise buffer the incoming byte.
        else if (length < sizeof buffer - 1) {
            Serial.write(c);  // echo
            buffer[length++] = c;
        }
    }
}

Notice the lines with the comment “echo”: they are meant to help you see
in the terminal what you are typing. You can remove them if you do not
what the Arduino to echo your typing. I tested it by sending

AA bb06 000000 0101 03 03

and it replied

AA BB 6 0 0 0 1 1 3 3


Can MP3 be sent to SPI of Adafruit Music Maker Arduino shield instead of from its SD card? Can uncompressed MP3 audio data be sent from Arduino board, by SPI, to Adafruit Music Maker shield instead of from the SD card on the Music Maker?

Instead of using SD card on Music Maker board, I want to send the compressed MP3 data from a Particle Photon board on the Particle shield shield, by SPI, to the VS1053B codec chip on Music Maker board, and then to amplifier for speakers.

Particle Shield Shield is attached to Particle Photon board, which has STM32F205RGY6 120Mhz ARM Cortex M3.

Particle Photon board uses its WiFi to receive uncompressed MP3.

As far as I can see the SD card on the shield isn't read by the VS1053 directly, but by the arduino, which sends it to the VS1053.

So as far as I can see, you should be able to do what you want.


Why does a variable size struct not compile in the Arduino IDE? This sketch does not compile in the Arduino IDE

void setup() {
  // put your setup code here, to run once:

}

struct test {
  int i;
  char variable[];
};

typedef struct test test;

test t = {
  0, "hi"
};

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

}

Arduino throws

sketch_may09a:16: error: initializer-string for array of chars is too long [-fpermissive]

 };

 ^

exit status 1
initializer-string for array of chars is too long [-fpermissive]

However compiling with g++ works just fine. How can I fix it? Or is there a principle reason why flexible array members are not supported?

Flexible array member is a C feature. It does not exist in C++. On top of that, the way you use it to declare and initialize a static struct of flexible size is non-standard even for C.

However, GNU-C language supports it as an extension. Also, newer versions of GCC (6 and higher) allow this in GNU-C++ code as an extension as well. But GCC 5.4.0 used by Arduino IDE doesn't support this non-standard feature in C++ code.

If you flip through different GCC versions on Godbolt (https://godbolt.org/z/Iul7hD) you'll see that support for this feature has always been present in C code, but for C++ code it first appeared in GCC 6.

This is why you were able to compile it with your standalone g++ compiler (which is apparently a much later version), but were unable to compile it in Arduino IDE.

It means that if you really want this non-standard code to compile in the current version of Arduino IDE, you have to place it into a .c file. Or just specify the array size explicitly.


How do I change pin assignments for the LUFA AVRISPMkII? I just managed to get Dean Camera's LUFA AVRISP clone working on my Arduino Pro Micro, when to my dismay I found that to use PDI for my XMega, I need to have PD5 exposed for the clock source! The Pro Micro has PD5 connected to an LED, so I am not easily able to use it.

If worst comes to worst, I can desolder the LED and wire a jumper, but that would be a pain in the butt. So I am wondering if any of you know if I can change the clock pin assignment from PD5 to PD6 or some other accesible pin. Thank you in advance for your help!

--[[ EDITS ]]--
Sorry for my lack of clarity, I am using the Pro Micro as the programmer, and the AVRISP clone supports PDI to the XMEGA. The 32u4 is actually directly supported by the programmer firmware. Here is what I am doing:

--[[ EDITS II ]]--
There is a schematic.. umm.. draw-o? I don't know but anyway the cathodes of D1 and D3 are NOT connected. That wire is an error.

simulate this circuit – Schematic created using CircuitLab

--Cantos

I found the answer searching through the Doxygen files. I had to go to AppConfig.h under Config in the project root directory, and edit AUX_LINE_MASK to change the pin. Thanks to everyone who helped!


Help with multi function momentary buttons I'm using the PunchThrough Bean and trying to build a two button project that has multiple functions. The idea is the user can press button 1 or button 2 for either short or long presses, or they can press both buttons simultaneously for a short or long press. This would give the user up to 6 different functions. Below is my code. I can get button 1 or button 2 press to work, but can't get pressing both to work. Also, I can't figure out how to have a function depending on how long a button sequence was pushed. Any help would be greatly appreciated.

const int btn0 = 2;
const int btn1 = 3;

void setup() {
  Bean.enableWakeOnConnect(true);
  Bean.enablePairingPin(true);
  BeanHid.enable();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);
}

void loop() {
  bool connected = Bean.getConnectionState();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);

  if (connected) {
    int btn0State = digitalRead(btn0);
    int btn1State = digitalRead(btn1);

    if ((btn0State == LOW) && (btn1State == HIGH)) {
      Bean.setLed(255, 0, 0);
      Serial.print("up");
      BeanHid.sendKey(KEY_UP_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == HIGH)) {
      Bean.setLed(0, 255, 0);
      Serial.print("down");
      BeanHid.sendKey(KEY_DOWN_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == LOW)) {
      Bean.setLed(0, 0, 255);
      Serial.print("right");
      BeanHid.sendKey(KEY_RIGHT_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

  }
}

Don't act immediately when a button gets pressed, instead when a button is pushed all you do is set the timestamp on that button and set a flag.

Then when it is released or the time elapsed is large enough do the appropriate thing.

void loop(){
    int btn1State = digitalRead(btn1);
    static bool button1 = false;
    static unsigned long time1 = 0;

    if (btn0State == LOW && !button1) {
        button1 = true;
        time1 = millis();
    }

    if (btn0State == LOW && button1) {
        if(millis() - time1  > SHORT){
            //do long action
            time1 = millis(); //reset timer
        }
    }

    if (btn0State == HIGH && button1) {
        button1 = false;
        //do short action
    }

}


My button stays on high if I press it once, what did I do wrong? If I press my button once, I get characters on all of the 32 character places and I get an infinite tone with my piezo. Can someone help me with this?

#include <LiquidCrystal.h>

const int buttonPin = A0;
int buttonState = 0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte run1c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B01110,
  B11100,
  B01110,
  B10010,
};

byte run2c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B11100,
  B01110,
  B11100,
  B10010,
};

byte jumpc[8] = {
  B01100,
  B01100,
  B00000,
  B11110,
  B01101,
  B11111,
  B10000,
  B00000,
};

byte jumpLowerc[8] = {
  B01110,
  B11100,
  B01110,
  B10000,
  B00000,
  B00000,
  B00000,
  B00000,
};

byte groundc[8] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
};

byte rightGroundc[8] = {
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
};

byte leftGroundc[8] = {
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
};

void setup() {
  lcd.createChar(0, run1c);
  lcd.createChar(1, run2c);
  lcd.createChar(2, jumpc);
  lcd.createChar(3, jumpLowerc);
  lcd.createChar(4, groundc);
  lcd.createChar(5, rightGroundc);
  lcd.createChar(6, leftGroundc);
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    tone(8, 400);
    lcd.setCursor(1,0);
    lcd.write(byte(2));
    digitalWrite(buttonState, LOW);
  } else {
    lcd.setCursor(1,1);
    lcd.write(byte(0));
  }
}

From what I can tell from your drawing, you have both sides of your button tied to 5V.  The green wire on one side and the blue wire through the resistor on the other.  So yes, the button will always read HIGH.

Instead, remove the resistor, tie one side of the button to the pin and the other side to ground.  Use INPUT_PULLUP in your pinMode cal instead of just INPUT.  Now a pressed button will read LOW and not pressed will read HIGH, so you'll have to reverse your logic in your code.  But the wiring will be much nicer.


Establishing an MQTT connection using Arduino Mega and ESP8266 As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me.
I have tried using PubSubClient library, but the problem is that to create an instance (PubSubClient client(?????)), I have to set a client. What should I put in there? Is there another library I must use?

You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).

Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.


Certain String Characters To Int I have a char* array which looks like this "T 20" and I'd like to extract the "20" and convert it in to an integer. I was thinking of using atoi() but it seems that function will operate on the entire string, not just the bits I want. Memory is a bit tight so is there a function similar to atoi() which allows you to specify which charters to operate on?

How about

char array[5] = "T 20";
int num = atoi(array+2);

This obviously assumes that all your strings are of the same format "A NN". If not, you can try parsing it using strtok(). See this excellent answer.


GPS is not detected on SIM808 module! I'm trying to get GPS coordinates using my SIM808 module by connecting it with Arduino. When I use this code,

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "gps.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to start a connection as client.

GPSGSM gps;

char lon[15];
char lat[15];
char alt[15];
char time[20];
char vel[15];
char msg1[5];
char msg2[5];

char stat;
char inSerial[20];
int i = 0;
boolean started = false;

void setup() {
  //Serial connection.
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");
  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    gsm.forceON(); //To ensure that SIM908 is not only in charge mode
    started = true;
  } else Serial.println("\nstatus=IDLE");
  if (started) {
    //GPS attach
    if (gps.attachGPS())
      Serial.println("status=GPSREADY");
    else Serial.println("status=ERROR");
    delay(20000); //Time for fixing
    stat = gps.getStat();
    if (stat == 1)
      Serial.println("NOT FIXED");
    else if (stat == 0)
      Serial.println("GPS OFF");
    else if (stat == 2)
      Serial.println("2D FIXED");
    else if (stat == 3)
      Serial.println("3D FIXED");
    delay(5000);
    //Get data from GPS
    gps.getPar(lon, lat, alt, time, vel);
    Serial.println(lon);
    Serial.println(lat);
    Serial.println(alt);
    Serial.println(time);
    Serial.println(vel);
  }
};

void loop() {
  //Read for new byte on serial hardware, and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i = 0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i] = (Serial.read());
      delay(10);
      i++;
    }
    inSerial[i] = '\0';
    if (!strcmp(inSerial, "/END")) {
      Serial.println("_");
      inSerial[0] = 0x1a;
      inSerial[1] = '\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if (!strcmp(inSerial, "TEST")) {
      stat = gps.getStat();
      if (stat == 1)
        Serial.println("NOT FIXED");
      else if (stat == 0)
        Serial.println("GPS OFF");
      else if (stat == 2)
        Serial.println("2D FIXED");
      else if (stat == 3)
        Serial.println("3D FIXED");
    }
    //Read last message saved.
    if (!strcmp(inSerial, "MSG")) {
      Serial.println(msg1);
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0] = '\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

After some time, I get this error on the Serial Monitor of Arduino:

status=ERROR

The connections are as follows:

TX of Module = Pin 2 of Arduino
RX of Module = Pin 3 of Arduino
GND of Module = GND of Arduino
5V of Module = 5V of Arduino

The Arduino is powered by USB connected to my PC.

Your problem looks similar to mine. It is possible that your module is a GNSS module and therefore doesn't work with standard AT commands, which are used in "gps.h".

First check that the GPS Module receives enough current, at least 5V -- 2A from an external source like a battery.

Then try sending AT commands in the serial monitor to check if your GPS module works properly:

#include <SoftwareSerial.h>
SoftwareSerial SIM808(2,3); //(RX-Pin,TX-Pin)

void setup() {
  Serial.begin(19200);
  SIM808.begin(19200);
}

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

Upload this to the board an then open the serial monitor and send these commands:

AT+CGNSPWR=1

This should return OK.

After that input:

 AT+CGNSINF

This should return OK and your GPS Location in this format:

1,0,<time>,<your latitude>,<your longitude>,..........

If you get the following output:

1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,,

It means your GPS is not set. Try to put GPS antenna outside your room, on open space.

For more information about GNSS modules go to  http://www.elecrow.com/wiki/images/0/05/SIM800_Series_GNSS_Application_Note_V1.00.pdf


Possible ArduinoJson bug on ESP8266? I'm making a small IOT project using the ESP8266 in which I make 2 API calls:

api.openweathermap.org for weather data
api.timezonedb.com

The request logic is the same for both calls, the only difference being how I parse the response string. The first response is parsed fine, while the other isn't.

I print the String responses to Serial, they look fine.
Tried both Dynamic and Static buffers to no avail.
Making the request only to the second API, still not being parsed.
If I make a test and just make the response a String, char[] or char*, it parses fine.

Parsing logic [works]:

StaticJsonBuffer<1000> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);
float raw = root[String("main")][String("temp")].as<float>();

Parsing logic: [does not work]

StaticJsonBuffer<500> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);

String data = root[String("formatted")].as<String>();

The response object looks like this:

{
  "status": "OK",
  "message": "",
  "formatted": "2017-06-30 11:34:13"
}

Request logic:

String RequestAPI::performRequest(String url, char* host){
WiFiClient client;
if (!client.connect(host, port)) {
    lcd -> clearScreen();
    lcd -> drawText("Failed to connect to API", 0, 0, this -> randomUint16());
    delay(5000);
    return "";
}

char endOfHeaders[] = "\r\n\r\n";
client.print(
String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n"
);
// Skiping HTTP headers from the response
client.find(endOfHeaders);

unsigned long startTime = millis();
while(client.available() == 0){
    if(millis() - startTime > this -> timeout){
        lcd -> clearScreen();
        lcd -> drawText("API request failed", 0, 0, this -> randomUint16());
        delay(5000);
        return "";
    }
}

String response = "";
while(client.available()){
    response += client.readStringUntil('\r');
}
Serial.println(response);

return response;
}

Now I'm thinking, could the empty message be causing a bug? Or am I doing something wrong?

The issue was caused because of: https://en.wikipedia.org/wiki/Chunked_transfer_encoding

Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:

client.print(
  String("GET ") + url + " HTTP/1.0\r\n" +
  "Host: " + host + "\r\n" +
  "Connection: close\r\n\r\n"
);

Dunno why it worked for one API but not the other though.


Arduino, Serial and wrapper class I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.

Minimal use case to demonstrate behavior is in following files:

main.ino

#include <Arduino.h>
#include "testclass.h"

TestClass testClassInstance(Serial);

void setup() {

}

void loop() {
    testClassInstance.print("Hi There\r\n");
    delay(1000);
}

testclass.h

#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <Arduino.h>

class TestClass {
public:
    TestClass(HardwareSerial &serial);
    void print(const char * text);

private:
    HardwareSerial _serial;
};

#endif

testclass.cpp

#include "testclass.h"

TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
    _serial.begin(9600);
    _serial.print("Initializing\r\n");
}

void TestClass::print(const char *text) {
    _serial.print(text);
}

After reset, there are only two characters sent: "In"

In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.

modification of main.ino

TestClass *testClassInstance;

void setup() {
  testClassInstance = new TestClass(Serial);
}

There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.

Any help is greatly appreciated.

You can't do complex tasks (or anything that relies on the Arduino API in any form) in your constructor. Simply because that all gets called before the Arduino API initializes, and in so doing the serial port gets disabled.

Instead you should do your complex operations and API-based operations in .begin(), which is why 99.99% of all libraries (including HardwareSerial) have a .begin() method.


Preforming impedance termination for UART Communication (TX and RX) pins I need two Arduino devices (Arduino Mega and Nano) to communicate with each other via UART. The two Arduino devices are long distance apart from each other. The distance is 1.5 meters.

The Arduino 1 TX pin is connected to Arduino 2 RX pin.
The Arduino 1 RX pin is connected to Arduino 2 TX pin.

Now, I have to use resistor to preform impedance termination so that the long distance does not cause transmitting and receiving issues between the two devices. I did some research and found an  image that shows the signal differences when impedance termination is preformed and when it is not.

I have two questions:

1. Since the distance between both Arduino devices is 1.5 meters, what resistor value should I use? How is that calculated?

2. Where do you put the resistors? It's not really clear on where to connect the resistors. Between ground and the RX pins on each device?

I don't know the gauge ratings of my wire but if that information is needed, I am using this wire.

The relevant parameter is not the length of the link, but its
characteristic impedance. For a twisted pair connection, this is
typically in the order of 100 to 120 Ω. It should be specified in
the datasheet. Your cable is not a twisted pair, but its geometry is
quite close. Just make sure that there is a ground or Vcc line between
the two data wires in order to minimize cross-talk. If you want to
compute that impedance yourself, here is an online
calculator.

Connect the resistor in series with the TX pin, i.e. between the pin and
the data wire. Note that the pin already has an internal output
resistance of about 25 Ω, so you would add no more than 100 Ω
in series.

If you search online about termination resistors, you may learn tat they
are often put between the receive pin and ground, or even at both the
sending and the receiving end. In high frequency applications, the
latter is often the preferred configuration, as it prevents the signal
to be reflected from either end of the link. However, for logic-level
signals, that configuration would attenuate the signal too much. On the
other hand, terminating only at the receiver would put excessive load on
the TX pin. Thus, sender-side termination is your best option. A
resistor in series with TX does not prevent a reflection at the RX end,
but it prevents the reflected signal to be reflected again and cause
oscillations.


Can i use a range in a switchcase like in pascal? in pascal's case statement i can use this:

Var i : integer;
...
Case i of
 1..5 : DoSomething;
end;

i was wondering if there is a way in can do this with c/c++ in the arduino compiler using:

switch (var) {
   case 1..5:
     // statements
     break;

or is this only possible using if/else?

There are some GNU extensions available in the avr-gcc/avr-g++ compilers (used in Arduino IDE for AVR based Arduino boards). One of them is suport of ... for the case:

  switch (i)
  {
    case  10 ... 100:  Serial.println(F("First"));           break;
    case 101 ... 1000: Serial.println(F("Second"));          break;
    default:           Serial.println(F("Everything else")); break;
  }

But, it's not the part of C/C++ standard, it's just compiler extension, so there is possibility it fails to compile on different platforms (mainly different compiler). So it's better to avoid it in portable code.


SIM900 Shield read only sms headers without text I enable messages about new SMS

AT+CNMI=2,2,0,0,0

OK

and when received sms, output like this.

+CMT: "+79XXXXXXXXX","1","15/09/23,01:34:03+24"
Test

But when I read message, output only before <CR><LF>
I don't see text of message.

AT+CMGR=1

+CMGR: "REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"

AT+CMGL="ALL"

+CMGL: 1,"REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"
+CMGL: 2,"REC READ","+79XXXXXXXXX","1","15/09/23,01:34:03+24"

I use following  (via SoftwareSerial) code for test this.
SMSGSM.GetSMS and SMSGSM.GetAuthorizedSMS of GSM GPRS GPS Shield Library receive only phone number without sms text.

I use this shield:

AT+GSV

SIMCOM_Ltd
SIMCOM_SIM900
Revision:1137B05SIM900M64_ST_ENHAN

This is most likely a case of overrun SoftwareSerial buffer. You are reading too slowly from the modem, especially with the Serial.print()s in your code. You should look for SoftwareSerial.h in C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial if you're using Win 8 and above. Or just search your PC for it. Look for this line:

    #define _SS_MAX_RX_BUFF 64

Change 64 to 256 and save. If it solves your problem, try reducing 256 to 128 to see if it still works. The greater the size of the buffer, the lesser the amount of memory available to the rest of your program.

You could also try this, to interact with the module:

#include <SoftwareSerial.h>

SoftwareSerial SIM900(7,8);

void setup() {
  Serial.begin(19200);
  SIM900.begin(19200);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (Serial.available() > 0){
    SIM900.write(Serial.read());
  }
  while (SIM900.available() > 0){
    Serial.write(SIM900.read());
  }
}

It does the same thing as your code and doesn't require adjusting buffer size, though I still recommend you make the change if you will use other sketches.


arduino uno external power supply I have an arduino uno which is powered by batteries. I have 6 AA-Batteries (1,5V each) connected to Vin and GND.

Thats cool because I don't have any cables and works pretty good.
The reason I need 6 AA batteries is, that I have a SIM900-module connected to my arduino uno. My USB Port (5V and 500mA) and my standard external power supply (9V and 1A) doesn't deliver enough current for the SIM900. But with the batteries the SIM900 gets enough power (current).

But there is the problem, that the batteries get sucked empty pretty fast and i don't want to exchange them every day. :-)

I searched for an power supply which can deliver 3A with 9V and found one. But i'm not sure if the arduino uno can handle that input via the on-board power-jack? The reason I want a 3A power supply is, that some users on the internet say that the sim900 sometimes uses more than the maximum current written in the documentation (which is 2A).

I'm an electronic noob.

So is there a risk if I try to use the 9V-3A power supply?
Does the arduino only pull the power it needs? So when it needs only 900mA, it only takes 900mA even if the power supply can deliver 3A?
As far as I know, it should work, because the batteries deliver as much current as the arduino (ad sim900) needs. So the batteries don't have an ampere limit, right?

The Arduino itself has a limit of about 800mA. That is imposed by the voltage regulator that converts the incoming voltage to 5V.

If you need more than 800mA then you need to provide your own regulated 5V power source and feed it in to the 5V pin (not VIN).

Suitable power sources are mobile phone chargers (modern USB ones).  They generally come in multiples of amps.

And to answer your theory question - the current is the maximum that the supply can provide. It's the voltage that is fixed and the current varies depending on the load.


light leds from an array I have the project to build a robot for my school. It will record button pushes then move according to this record.

Before usig motors, i'm trying to do this using leds.

Thanks from posts from this community, I've succeed in recording button pushes in an array.

Now I'm trying to light the leds according to this array.
I have 4 buttons with 4 leds and one button tu run the recording when it's ready.

I'm stuck in lighting the leds when I push the play_button.

I hope someone can help me...

Here's my script :

int arr[10];
boolean previous = LOW;
unsigned long time1 = 0;
int debounce = 200;
unsigned long time2 = 0;
int index_state = 0;

int play_button = 13; //define pin # for play button

int button[4] = {2,4,6,8}; //store button pins in an array
int leds[4] = {3,5,7,9}; //store led pins in an array

void setup()
{
  for(int n=0;n<10;n++) arr[n] = 0;//initialisition
 Serial.begin(9600);
}

void loop(){
 boolean mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);
 while(mode == LOW) mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);//wait here till one of the pushbutton goes high;
 //Serial.println("value");
 if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {
 //find out which one is high and store that value in array;
 if(digitalRead(2)) arr[index_state] = 2;
 else if(digitalRead(4)) arr[index_state] = 4;
 else if(digitalRead(6)) arr[index_state] = 6;
 else if(digitalRead(8)) arr[index_state] = 8;
 else ;

 //print the value and the index;
 Serial.print(arr[index_state]);
 Serial.print(" Stored in index: ");
 Serial.println(index_state);
 index_state = (index_state + 1) % 10;
 //update value of time1 for button debouncing
 time1 =  millis();
}

  //update the value of previous button state
  previous = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead(8);

  }

Thank you

You have problems in including the further functionality (the playback), since your loop() function is solely written for providing the first part of functionality (the recording). You need an overall structure, that will execute the correct functionality at the correct time/logic order.

For this, an Finite State Machine (FSM) is the best way. It will help you to structure your code and the logic. It is an important principle to learn.

First you would have to divide your program logic into different states and transitions between them (don't look too close at the actual code at this point, but with a higher abstraction). Currently I see 2 states in your project: A state, where you are recording the button presses in an array, just like you already did. And a state, where the array is used for playback. The transition from the first to the second state happens, when the playback button is pressed. The transition back happens, when the playback is finished. It helps to draw a graph for this, to visualize the the states and their transitions. In my answer to this question I explained this further including an example of such a graph.

When you are finished creating the states and transitions, you can create the necessary code structure. The easiest way for a beginner is to use a simple state variable (simply an integer, or - if you want to use names for the states - an enum) in a switch()-case statement. You can also see this in the linked answer. Your code then goes into the case statements. The switch statement will only execute the code for the current state. To do a transition to another state, you simply change the state variable. So in the case statement of the first state, you put the code that you already have for reading the buttons, and an if statement, that checks the playback button. If the playback button was pressed, change the state variable to the second state.

You could also solve this problem without an FSM, but the structure won't be that good and easy to expand. Also you might get some extra points for implementing an FSM :D

Currently your code is blocking. That means, that it will block any further operation, until something happened, in this case, that one of the 4 buttons gets pressed. Often this is only a hindrance, when adding functionalities. It is better to use do-maybe code, means code, that will only do something, if some condition is met (like time). You are already doing this in the if statement

if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {

(it only triggers the recording of a new button, if a button was pressed and the debounce time has passed) so why are you blocking before this with the while loop? You could just write to mode without the while loop.


Are these GND connected resistors on the Arduino Due redundant? Does anyone know why these 4 resistors are there (attachment)? It seems like they are useless since connected in a loop to GND.
Full schematics here: https://store.arduino.cc/arduino-due

Yes, they are redundant. They are elements of resistor arrays (multiple resistors in one package) that aren't used. They have just connected all unused pins of those packages to ground.
If you want to know why they would have unused elements, it's all to do with optimizing the manufacturing process. If you have, say some 100k arrays elsewhere in your design and you want to have maybe one or two other 100k resistors elsewhere, rather than adding another component of a discrete 100k resistor it's cheaper to use a 100k array and not use some of the elements. One of the factors in the cost of pick-and-place operations is the number of different components. By keeping the number of component types to a minimum they keep the manufacture costs to a minimum.


How to add Attiny13 to Attiny board profile in Arduino IDE 1.6? Several months ago, I asked how to add (or where to get) Attiny13 to the list of boards in the Attiny package available in github: https://github.com/damellis/attiny In post 1.5 IDE, the package is installed by adding repo's JSON file to boards manager, as described in this post: https://arduino.stackexchange.com/a/23056/2955

Nowhere it says how to modify the files, not at all. And the package doesnot contain Attiny13 info.

The answer to my question was to do it myself and make a pull request. So ok, but how do I do it? I don't understand those files. The JSON file refferences some SHA-256 named zip files. That's hardly something that can be clearly and simply edited.

Can anyone tell me clearly what do I have to do to get Attiny13 working within that profile?

You can easily add entries for the ATTiny13 to the IDE, but won't show in the same listing as damelis's ATTiny cores, as he hasn't added the ATTiny13 yet.

Here is what I have found for ATTiny13 Arduino core files, working with  boards.txt, loading them into the IDE, etc.  The boards.txt is all laid out, just drop it into your personal workspace per the directions provided.

https://github.com/MCUdude/MicroCore

How to install
Boards Manager Installation
This installation method requires Arduino IDE version 1.6.4 or greater.
Open the Arduino IDE.
Open the File > Preferences menu item.
Enter the following URL in Additional Boards Manager URLs: https://mcudude.github.io/MicroCore/package_MCUdude_MicroCore_index.json
Open the Tools > Board > Boards Manager... menu item.
Wait for the platform indexes to finish downloading.
Scroll down until you see the MicroCore entry and click on it.
Note: If you are using Arduino IDE 1.6.6 then you may need to close Boards Manager and then reopen it before the MicroCore entry will appear.
Click Install.
After installation is complete close the Boards Manager window.

This will get you quite a lot of functions, configurable clock speeds, etc. The readme for this project helped me quite a lot  in understanding what is going on inside the box and how I can enable only the Arduino core functions that I want, to save space.

Microcore is based upon :
sourceforge.net/projects/ard-core13/files/latest/

And both projects have code updates as of this summer.

For other ATTiny (I'm using an ATTiny85 sometimes since for some things I ran out of space on the ATTiny13)

github.com/damellis/attiny

This will get you:
ATtiny 25 (8 pin)

ATtiny 45 (8 pin)

ATtiny 85 (8 pin)

ATtiny 24 (14 pin)

ATtiny 44 (14 pin)

ATtiny 84 (14 pin)


Why my serial message won't show on another when I try use 2 Arduino communication I am trying to make a simple chatting program with my 2 arduino uno and 2 PC. But when I tried write a message using PC1 serial monitor the message won't show up on PC2 serial monitor. I can't see the problem or maybe I miss something on the program.

Here is my code:
PC1:

#include <SoftwareSerial.h>

SoftwareSerial Serial1(10,11);

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

void loop()
{
    if ( Serial.available()) // Check to see if at least one character is available
    {
        char ch1 = Serial.read();
        Serial1.print(ch1);
    }

    delay(200);
}

PC2:

#include <SoftwareSerial.h>

SoftwareSerial Serial1(10,11);

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

void loop()
{
    if (Serial1.available())
    {
        char ch = Serial1.read();
        Serial.print(ch);
    }
}

I haven't tested this in a while but it has been my experience that even though you can have multiple IDE windows open, you can only have one Serial Monitor at a time. The way I got around this is to use a Terminal Emulator program for the second Arduino.


Audio.h Library Issues I'm trying to incorporate audio into my Arduino project for the first time, and have been have a lot of issues. I originally couldn't get the Audio library to work, but after installing it through the Arduino application, I figured the Audio.h library would work fine. However, it spit out this error:

  WARNING: library Audio claims to run on (sam) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s).
  In file included from /Documents/Arduino/libraries/Audio/src/Audio.h:16:0,
                   from /Documents/Arduino/boxgame/boxgame.ino:1:

Then it lists plenty of syntax issues, none of which have to do with my code. I think it's giving errors from the library, but I'm not really sure what's happening. Here's an example of one of the slew of errors:

  /Users/tschadius/Documents/Arduino/libraries/Audio/src/DAC.h:37:2: error: 'IRQn_Type' does not name a type
    IRQn_Type isrId;

Any ideas as to how I can fix this? The error message goes on for quite a while, but none of them appear to be from my code that I've written.

Thanks!

Occasionally people do not realize how many platforms the Arduino paradigm has been ported to.  In almost all cases the ported to platform far exceeds the features found on an Arduino Uno.  So there exists a considerable amount of software that can not run on an Arduino Uno or on an Arduino Uno with out additional hardware.  But, usually, such software is surrounded by "text", "web-pages" and other "readme"  type files explaining the situation.

For the Arduino Audio library, the web-page says this:

  Audio

  Compatible with Arduino Due only

  The Audio library enables an Arduino Due board to play back .wav files
  from a storage device like an SD card.

  The Due uses the DAC0 and DAC1 pins to play sounds.


Convert long to char array and back I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a long value correctly - I've build it down to converting it to char array and back.

My best try so far has been

long temp = 1418172669L;
unsigned char buf[4];
buf[0] = temp         & 0xFF;
buf[1] = (temp >>  8) & 0xFF;
buf[2] = (temp >> 16) & 0xFF;
buf[3] = (temp >> 24) & 0xFF;

long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

But l is very different from temp - currently the output is -26371. Am I making an obvious mistake?

I suggest using a union:

union {
    char myByte[4];
    long mylong;
} foo;

Char to Long:

Then you can just add the bytes:

foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];

Then you can access the long as:

myUnion.myLong;

Long to Char:

The same if you want to go the other way from long to char array:

foo myUnion
myUnion.myLong = 1234L;

To access bytes:

myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];


Multi-LED Toggle Switch I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB.  The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch.  I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever.  It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it.  If anyone can tell me what I am doing wrong please let me know.

Here is the Python3 GUI code:

import serial # import the serial library
import time # import the time library
from tkinter import * #import Tkinter GUI library

def toggleRed():
    if redBtn.config('relief')[-1] == 'sunken':
        redBtn.config(relief="raised")
        arduino.write('a'.encode())
    else:
        redBtn.config(relief="sunken")
        arduino.write('b'.encode())

def toggleGreen():
    if greenBtn.config('relief')[-1] == 'sunken':
        greenBtn.config(relief="raised")
        arduino.write('c'.encode())
    else:
        greenBtn.config(relief="sunken")
        arduino.write('d'.encode())

def toggleBlue():
    if blueBtn.config('relief')[-1] == 'sunken':
        blueBtn.config(relief="raised")
        arduino.write('e'.encode())
    else:
        blueBtn.config(relief="sunken")
        arduino.write('f'.encode())

def toggleYellow():
    if yellowBtn.config('relief')[-1] == 'sunken':
        yellowBtn.config(relief="raised")
        arduino.write('g'.encode())
    else:
        yellowBtn.config(relief="sunken")
        arduino.write('h'.encode())

print ('Connecting...')
arduino = serial.Serial("/dev/ttyACM0", 9600)
time.sleep(3)
print ('Connection established successfully')

appWindow = Tk() # creates the application window (you can use any name)
appWindow.wm_title("RGB LED Control") # displays title at the top left
appWindow.config(bg ="#037481")

mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
mainFrame.grid() #grid the frame into the App Window

btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
btnFrame.grid() #grid the frame into the main frame

redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
redBtn.grid(column=0,row=0,sticky='EW')

greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
greenBtn.grid(column=0,row=1,sticky='EW')

blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
blueBtn.grid(column=0,row=2,sticky='EW')

yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
yellowBtn.grid(column=0,row=3,sticky='EW')

appWindow.mainloop()# begins main loop

Here is the arduino code:

int ledRed = 13;
int ledGreen = 11;
int ledBlue = 9;
int ledYellow = 7;

//int ledRedStatus;
//int ledGreenStatus;
//int ledBlueStatus;
//int ledYellowStatus;

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledYellow, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() == '97') {
    digitalWrite(ledRed, LOW);
  }
  if(Serial.available() == '98') {
    digitalWrite(ledRed, HIGH);
  }
  if(Serial.available() == '99') {
    digitalWrite(ledGreen, LOW);
  }
  if(Serial.available() == '100') {
    digitalWrite(ledGreen, HIGH);
  }
  if(Serial.available() == '101') {
    digitalWrite(ledBlue, LOW);
  }
  if(Serial.available() == '102') {
    digitalWrite(ledBlue, HIGH);
  }
  if(Serial.available() == '103') {
    digitalWrite(ledYellow, LOW);
  }
  if(Serial.available() == '104') {
    digitalWrite(ledYellow, HIGH);
  }
}

Adding comments to your code would help us understand your intentions.

It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions.  And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.

Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the Serial.available() method call.  If your intentions were to read a byte of data you would instead call the serial.read() method.

It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value.  If you read the buffer many times you would be pulling a new byte of data from the buffer with each read.  If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.


Send Color value from Processing into Arduino I know this has been asked before, but I'm new to Arduino and Processing, and I'm trying to take this step by step.

I would like to pass an RGB value from processing, into Arduino via the Serial.Write/Read.

I have my Processing as:

void draw(){

  //orange colour in RGB values
  color _rgbColor = color(255, 40, 0);

  //convert colour into hex
  String _hexColor = hex(_rgbColor, 6);

  //convert colour into binary
  String _binaryColor = binary(_rgbColor);

  //pass colour to port
  myPort.write(_hexColor);
  delay(500);
}

I assume I can just pass the HEX value straight across, right?

First problem I get is that I can't debug what my Arduino device is getting (when I run the Processing program, the Serial Monitor wont work. Seems like I can only use one or the other). I can print the myPort.read within my Processing after the delay, and I get:

  -1

So I'm not quite sure what I'm doing wrong there.

On the Arduino side, I'm using Serial.read() to retrieve the Serial data, which I assume will all be broken down into bytes, so I need to then convert it into a HEX formate, right?

----- Update -----

I now know that I need to break down my color variable into a char-message. I'm guessing I can do something like this then, for example: And then on the other side (Arduino), I need to rebuild the message, right?

if(mousePressed == true){
    //Red
     myPort.write('2');
     myPort.write('5');
     myPort.write('5');
     myPort.write(',');

     //Green
     myPort.write('0');
     myPort.write('3');
     myPort.write('0');
     myPort.write(',');

     //Blue
     myPort.write('0');
     myPort.write('0');
     myPort.write('0');
     myPort.write('\n');
  }

My Arduino script is as follows, is this an okay route to go down?

String message;
void loop() {

  int _size = Serial.available();

  if(_size > 0){

    char value = Serial.read();
    message += value;

    //full message received (255,255,255)
    if(message.length() == 11){
      String _red = message.substring(0,3);
      String _green = message.substring(4,7);
      String _blue = message.substring(8,11);
      Serial.println("R:" + _red + " G:" + _green + " B:" + _blue);

      //apply to light system
      setColour(_red.toInt(), _green.toInt(), _blue.toInt());

      //clear buffer
      message = "";
      Serial.flush();
    }
  }
}

Add print(_hexColor); to you processing sketch. The value it's sending should appear in the Processing Console (at the bottom)


Connecting multiple load cells to the same microcontroller This is my first post and I am a little bit confused about one thing.
I would need to do the following project:
have about 5-6 load cells to be connected to a microcontroller.
I am not sure if there is a way to connect multiple load cells to the same arduino.
I would need each load cell to act individually, so I would need an individual result from all each load cell.

I believe I would need to connect 1 load cell to 1 load cell amp and then connect the load cell amp to the Arduino and repeat this process 5-6 times (for each load cell that I need)

I'm not sure if this is possible using one Arduino or I would need 1 Arduino for each individual load cell.

The main idea of the project is to have a load cell to be placed under different kitchen supplies (1 load cell to continuously check the weight of Flower, another one to check for bread, another to check for paprika, and so on)

After this is read from the sensors, I need to write the weight of each item in a table / DB every 30 minutes.

Also, if this can be done with another board, like a microcontroller (Raspberry Pi) I'm open to that.

All you need is the following :

Arduino (Mega, if you need alot of inputs.)
Load Cell Amplifier
Load Cells (I recommend only using four wire cells)
Resistors (Only if you are connecting one cell to one amplifier)

If you are using only one load cell per "Scale" , you would connect it as you say correctly. One load cell to each load cell amplifier and then to the Arduino.

Yes, a single Arduino can in theory take as many scales as the number of Digital inputs you have can provide. You can use the Analog inputs as well but from my experience I would recommend you only use the Digital inputs. You can just share the power and ground sources.

Usually each Load Cell Amplifier will need to use two(2) Digital inputs.

If you want to use multiple load cells together (to improve accuracy) to act as a single scale, you would connect them together in what they call a Quarter, Half or Full Bridge wiring configuration depending on how many you would like working together.

You can write to a DB if you want sure.
What I personally like to do is send the readings to the cloud using dweet.io or ThingSpeak. ThingSpeak.com would probably be best for you.

I usually use the NodeMCU arduino boards that have WiFi built in. They are cheap and work great.

I hope this helps.


How to make procedures triggered remotely I am installing lights in a model train and there are multiple prototypical lighting procedures that need to be activated. The lights are connected as follows:
Headlight Top - Pin 1
Headlight Bottom - Pin 2
Front Right Marker - Pin 3
Front Left Marker - Pin 4
Rear Right Marker - Pin 5
Rear Left Marker - Pin 6
Rear Left Headlight - Pin 7
Rear Right Headlight - Pin 8
Front Right Ditch Light - Pin 9
Front Left Ditch Light - Pin 10

I would like to simply address a forward procedure which would turn on pins 1, 2, 3, 4, 5, 6, 9, and 10. This is the lighting configuration when the loco is shifted into the forward gear. For reverse, pins 3, 4, 5, 6, 7, and 8 would be activated. There will be a few others too but those are the primary procedures. Is there a way I could set up a variable which names all those pins at once? Or is there some other way I could name a forwards or backwards lighting procedure with a single short name such as "Procedure 2"? I am using Arduino IDE.

perhaps an array and a loop? (dont have the Arduino IDE atm, so sorry about any typos)

int lights[] = {1, 2, 3, 4, 5, 9, 10};
int count = 7;//because there are 7 items in the array
//

main(){
    for (int i = 0; i < count; i++){
         digitalWrite(lights[i], HIGH);
         delay(1000);
    }
}

EDIT: still no IDE, but here is a little more depth.

forward(true) = forward lights on

forward(false) = forward lights off

reverse(true) = reverse lights on

reverse(false) = reverse lights off

void forward(bool state){
    int lights[] = {1, 2, 3, 4, 5, 6, 9, 10};
    int count = sizeof(lights) / sizeof(lights[0]);

    for (int i = 0; i < count; i++){
        switch (state){

            case true: //turn on
                digitalWrite(lights[i], HIGH);
                break;

            case false: //turn off
                digitalWrite(lights[i], LOW);
                break;
        }
        //delay(1000); //optional delay between lights?
    }
}

void reverse(bool state){
    int lights[] = {3, 4, 5, 6, 7, 8};
    int count = sizeof(lights) / sizeof(lights[0]);

    for (int i = 0; i < count; i++){
        switch (state){

            case true: //turn on
                digitalWrite(lights[i], HIGH);
                break;

            case false: //turn off
                digitalWrite(lights[i], LOW);
                break;
        }
        //delay(1000); //optional delay between lights?
    }
}


Arduino Resetting in Automotive Application I have a complicated problem with my Arduino circuit being reset/crashing, I will try to describe the best I can.

The Setup:
Basically I have a Arduino 328P circuit that is monitoring some temperatures in an automotive environment.  Several one wire temperature sensors connect to the PCB with various distances from 2-10 ft. Each is on a seperate pin.  I have also tried analog LM35 sensors.  The system works outside the car just fine.

The Problem:
When the car is shut off (not the PCB) the Arduino is being reset despite power still being connected.  There is no power spike or loss to the PCB. The car is not actually running, I am just turning the key on and off.

What I have learned:
-When I disconnect the temperature sensors from the PCB, problem goes away.
-It makes no difference if the wires to the sensors are shielded.
-It makes no difference if I use one wire digital or analog sensors.
-It makes no difference if I connect the PCB directly to the battery
-The problem goes away if I run the PCB on a battery not connected to the car. (fully isolated)
-The problem comes back if I ground the PCB to the chassis, but still leave the +12V isolated.
-The chance of a reset changes when the sensors are moved or the length of wire is changed.
-It only resets when the key is turned off, never when turned on.

I tried to explain the best I can without writing a novel.  I think I might need to isolate the ground to my PCB somehow.  The problem is in the ground or the long wires to the sensors.

There is no power spike or loss to the PCB. The car is not actually
  running, I am just turning the key on and off.

And did you verify that with a digital scope? I doubt it.

I don't think you understand how ugly the electrical system in a car really is. If there is a coil or relay switched then there will be spikes. Do some research on electronics for use in an automobile.

Automotive relays can have a resistor in parallel with the coil to control the level of the back emf when the relay is turned off. You would think that a reversed diode should be used but a diode causes the coil current to discharge too slow and that causes the contact arcing to be extended. A resistor can be used to speed up the discharge but at the cost of a voltage spike on the electrical system.

An Arduino board is not appropriate. There needs to be a lot more protection.And one wire devices are basically an antenna looking for trouble.

https://www.st.com/content/ccc/resource/technical/document/application_note/1f/d7/fc/6d/2e/27/48/98/CD00181783.pdf/files/CD00181783.pdf/jcr:content/translations/en.CD00181783.pdf

https://electronics.stackexchange.com/a/40425/195251

https://en.wikipedia.org/wiki/Load_dump

https://electronics.stackexchange.com/a/163861/195251


Formatting variables from a variadic function I have a function that concatenates a print line, however I am having trouble getting some of the strings to format correctly.

Using Serial.print formats the output from keypad.getKey() correctly, however when I try to output the same format using printConcatLine() it does not give me the same output. I've tried casting it as both a char and an int...

void printConcatLine(const char* mask, ...) {
    va_list params;
    va_start(params, mask);

    while(*mask != '\0') {
      if (*mask == 'i') {
          Serial.print(va_arg(params, int));
      } else if(*mask == 'c') {
          Serial.print(va_arg(params, const char *));
      } else if (*mask == 'f' || *mask == 'd') {
          Serial.print(va_arg(params, double));
      }
      ++mask;
    }

    va_end(params);
    Serial.println();
}

char btnPressed = keypad.getKey();
  if (btnPressed) {
    Serial.print("BtnPressed: ");
    Serial.println(btnPressed);
    // Output: "BtnPressed: 1"

    printConcatLine("ci", "BtnPressed: ", btnPressed);
    // Output: "BtnPressed: 49"

    printConcatLine("cc", "BtnPressed: ", btnPressed);
    // Output: "BtnPressed: "
  }

I also tried changing:

  va_arg(params, const char *)

to

  va_arg(params, char)

which also did nothing.

How can I modify the call to va_arg() to properly output the same output as Serial.print()?

With the format "ci", the argument is interpreted as an integer, and
the output is correct: 49 is the ASCII code of '1'.

With the format "cc", the argument is interpreted as a string (pointer to an
array of chars), which is incorrect.

One (bad) solution is to use the "cc" format and pass &btnPressed as
an argument. The problem with this approach is that the byte in memory
right after btnPressed may not be a zero, and the format expects a
NUL-terminated string.

A better approach would be to have one format for a char and a
different one for a string. I suggest "c" and "s" respectively. But
then you should be aware that there are special promotion rules
associated with variadic functions. When playing with your code, the
compiler reminded me of this one:

  warning: ‘char’ is promoted to ‘int’ when passed
  through ‘...’

So the function should expect an int, and cast it to char in order
to call the correct overload of Serial.print():

void printConcatLine(const char* mask, ...) {
    va_list params;
    va_start(params, mask);

    while(*mask != '\0') {
      if (*mask == 'i') {
          Serial.print(va_arg(params, int));
      } else if(*mask == 's') {
          Serial.print(va_arg(params, const char *));
      } else if(*mask == 'c') {
          Serial.print((char) va_arg(params, int));
      } else if (*mask == 'f' || *mask == 'd') {
          Serial.print(va_arg(params, double));
      }
      ++mask;
    }

    va_end(params);
    Serial.println();
}

Used like this:

printConcatLine("sc", "BtnPressed: ", btnPressed);
// Output: "BtnPressed: 1"


Is there a way to use functions defined in a library in any class? I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit_ST7735 + Adafruit_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.

So... For example there's a function public void drawRect(); in Adafruit_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?

Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class.

I've tried a bunch of different things but I've come to a dead end.

EDIT:

main program:

#include "_v0_0_0.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

#include "Point.h"
#include "Rectangle.h"
#include "SomeView.h"

#define     TFT_CS  4
#define     TFT_RST 0
#define     TFT_DC  10

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
SomeView a_view;

void setup()
{
    tft.initR(INITR_BLACKTAB); // initializes the display
}

void loop()
{
    a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc)
    while (true) {}
}

SomeView.h:

#include "Rectangle.h"

class SomeView {
private:
    Rectangle a_rectangle;
public:
    SomeView();
    void draw();

    const Rectangle& getRectangle() const {
        return a_rectangle;
    }

    void setRectangle(const Rectangle& rectangle) {
        a_rectangle = rectangle;
    }
};

SomeView.cpp:

#include "SomeView.h"

SomeView::SomeView() :
        a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) {
}

void SomeView::draw() {
    a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6));
    a_rectangle.draw();

    a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100));
    a_rectangle.draw();
}

Rectangle.h:

#include "Point.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

class Rectangle{
private:
    Point p1;
    Point p2;
public:
    Rectangle();
    Rectangle(Point& p1, Point& p2);
    void setCorners(const Point& p1, const Point& p2);
    void draw();

    // ... getters and setters for the points
};

Rectangle.cpp:

#include "Rectangle.h"

Rectangle::Rectangle() : p1(), p2()
    {
    }

Rectangle::Rectangle(Point& p1, Point& p2) : p1(p1), p2(p2)
    {
    }

void Rectangle::setCorners(const Point& p1, const Point& p2) {
    this->p1 = p1;
    this->p2 = p2;
}

// this is where I want to use a function from the adafruit library
void Rectangle::draw() {
    Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);

}

Yes, there is a way.

However that's not how object oriented programming (OOP) is supposed to be used, at least in theory.

Most likely you won't like my advice, but here it is: take it easy, find a good book or online course and learn to program on a system that is simpler to debug, than a microcontroller.

Your PC, for example.

C is closer to the HW than java. C++ can be seen as both of them, but there is not so much you can do without learning C, properly.
From that perspective, C++ can be seen also as a superset of C, only much more complex.

Have a look at this explanation, for example.
It's quite simple, but exhaustive. Read it carefully and you will find out that pointers are not so difficult to grasp, after all.

If you spend enough time to get the basics right, it will save you lots of frustration (and, yes, time!) later on.

For a more systematic approach, try this.


Powering Arduino from a shield I'm designing a shield for Arduino which drives two stepper motors. They are small and require 5V but their max combined current is around 1A, way too much for the USB supply. Therefore I will have external 5V power supply connected to my shield.

The entire device will usually operate being connected to a PC through USB, but still I'd like to have a possibility to run it separately.

The question is: how to power Arduino itself?

From my external PSU through the pins: Sounds as the simplest solution but I'm bit worried about the onboard regulator of Arduino while reverse powered.
Separate power circuits for electronics and motor: My L293D chips allow for separate power and even different voltage for the motors. It could even be an advantage for my shield, as I could use other motors and different power for them in the future. I will, however, lose the possibility of running the device without USB connection.
Same as above with additional barrel jack power connection to supply Arduino when USB is disconnected. This, however, could fail with 5V supply, because of the voltage drop of the regulator which handles power coming from barrel jack.

Option 1 is by far the simplest. Just have one 5V power supply for everything.  Make sure you have enough capacitance on there to absorb the noise of the motors - maybe separate the digital side from the drive side with an inductor.

You can add a diode connected backwards between the 5V and VIN pins to bypass the regulator when reverse powered.  That is, anode to 5V and cathode to VIN.


One Arduino collects data, several other Arduinos use the data. What is a simple way to do this? I am looking for a way to exchange a few bytes of data from one Arduino to two or more additional Arduinos. It's a one way communication and speed is not a problem. 10Hz is fast enough.

Data Collector Arduino: I have one Arduino with SPI and I2C shields which collects and analyzes data from a CAN-BUS in a motorcycle. The CAN-BUS supplies lots of information but I filter it down to few info like which lights are on, intake temperature, motor RPM, which gear.

Light Control Arduino: This Arduino should know which lights are on. Depending on low beam, high beam, indicators, etc. it will control additional lights which are not part of the original bike.

Motor Control Arduino: This Arduino should know the current RPM, gear, etc. and work with that data.

The question is how do I "transfer" the data from the data collector to the other Arduinos? If it would be a little simpler I would connect some digital pins which the data collector would write and the others would read. But there are not enough pins for my needs and why use 10 pins when maybe 2 are enough.

All the Arduinos use SPI and I2C connected devices so I don't think it's a good idea to use SPI or I2C for communication between the Arduios.

I guess Serial communication would work with 2 Arduinos but not with 3 or even more. Maybe I could use multiplexing or something like that?

Maybe I could let the data collector Arduino write data into some kind of shared memory and the other Arduinos could read it?

What do you suggest? I am sure there are simple solutions out there but I didn't find anything. I don't mind any extra ICs.

Before someone suggest to do all in one Arduino: Maybe it would be possible. But I really like to keep the modules (Arduinos) separate and I want to be able to add others later if I want to. Then I only want to change the software of the collector Arduino and don't touch the others.

It is possible to send out data from one Arduino to multiple others at once via serial (UART). You simply connect the TX of your master Arduino to the RX of all the slave Arduinos. All receiving Arduinos will get the same data with that. You only need 1 pin (for the connection sender TX to the multiple RX). This is a bit limited to the number of slaves and the speed, but that doesn't seem to be an issue here (since you only have a few).

This is a 1-way communication, since at any line there must not be more than 1 TX (sender). If you have more than 1 TX on a line, you will burn your hardware as soon as both TX send out data simultaneously.

I remember some sites that stated it to be possible to also do multiple sender UART, when you adhere to a protocol and put in some safety hardware (I think they used diodes and current limiting resistors). But that is somewhat out of scope here. If you really need a 2-way communication, you maybe should rethink the whole structure of your solution. As Juraj suggested in his comment, it might then be easier to unite the functions to less Arduinos.

Be sure, that the Arduinos share the same ground. This is needed for any communication, when you don't utilize extra hardware (like an optocoupler).


Understanding global variables on Arduino I am rewriting a set of LED manipulation functions to be more object oriented, and I have found that, mysteriously, my global variable memory space has been over consumed, despite a reduction of the use of global variables.

I played around with a number of things, and found something curious.

Here is a fragment of a function that does not live in an object, and is called directly from loop():

Animation *getNewAnim(int index)
{
    switch(index)
    {
        case 0:
            return new RedClouds();
        case 1:
            return new TwoLayerClouds();
        case 2:
            return new LavaLamp1();
        case 3:
            return new Bubbles1();

        ...  (20 or so more cases)
     }

This is a function that lets me switch between display modes based on the value of index.  Only one of these objects is ever created at a given time; I delete the old one before calling this, so there will never be multiple instances in use simultaneously.

Now the curious thing is that if I remove a few of these return statements, collapsing the block into something like this:

Animation *getNewAnim(int index)
{
    switch(index)
    {
        case 0:
        case 1:
        case 2:
        case 3:
            return new Bubbles1();
}

The amount of global memory space used falls considerably.

My hypothesis is that the Arduino build environment is pre-allocating space for each of these objects in the global memory space before the program is even run, rather than doing so dynamically as needed.

Is my hypothesis correct?  And if so, is there any way to tell the build environment not to do this, as I'd rather use the same memory for my new object that was used by the old one.

To clarify: When I build I see this sort of output:

Sketch uses 6,550 bytes (21.3%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,167 bytes (57.0%) of dynamic memory, leaving 881 bytes for local variables. Maximum is 2,048 bytes.

When I refer to "global memory" I am referring to the Global variables number on that output.  I'll also note that when I compile with the second example, the program storage space reported also falls dramatically.

NEW HYPOTHESIS

Here is what I think may be going on.  When I omit the classes from the switch statement, the compiler seems to optimize them out of the codebase, which is what I expect, and is consistent with seeing the program storage space shrink.  Each class has a method that returns it's name.  This method contains an embedded string, and I now believe that this string is stored in the global variable space.  Therefore, if the class is included, more global variable space is consumed to hold the name, and if it is optimized out, less is consumed.  This theory is consistent with all the facts I have, and makes more sense than my previous hypothesis.

I suggest you take a look at https://stackoverflow.com/questions/16274451/operator-new-for-arduino the new operator is not coming from the c++ libraries, it is coming from the Arduino libraries.  It's a wrapper for malloc Is using malloc() and free() a really bad idea on Arduino?


Inaccurate voltage readings on an esp32 as opposed to multimeter I am working on detecting the amplitude of a signal coming from a guitar pickup. I am using an esp32 and an LM386 module for amplifying the signal.
I get quite stable readings with a multimeter, but the readings on the Arduino IDE show peaks and also peaks come when no signal should be there.

Here is a link for short videos of both the esp32 readings and the multimeter:
https://drive.google.com/drive/folders/1gpvkN_sz627jG0TNPpUps82105EB89OF?usp=sharing
Thanks!
EDIT (Adding simple code being used) :
int ampedVoltagePin = 12;

void setup() {
  pinMode(ampedVoltagePin, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(ampedVoltagePin));
  delay(100);
}

EDIT (Adding diagram):

I see multiple problems with your setup:

You only take a measurement every 100ms. That measurement takes the voltage during a very short time span. But the lowest string on a guitar in standard tuning has 82.41Hz (E2). You are measuring at 10Hz. According to the Nyquist–Shannon sampling theorem you need to measure at at least twice the frequency of your lowest frequency to measure. Otherwise your measured data will not have any real meaning and will not represent the input wave. So you need to measure at least with 165Hz.

The amplifier can output voltages up to it's supply voltage, so 5V. You connect the output directly to the ESP32, which is a 3.3V device. That can damage the pin, that you are using.

Currently you are trying to measure the signal directly. But you wrote, that you want to have the amplitude. Currently you would need to calculate that in code (for example by taking the min and max value over a time range greater than one period of the lowest frequency, so at least 12ms (1/82.4Hz)). A multimeter most likely will do that in hardware with analog electronics.

I'm not sure if it is good to connect a speaker and the ESP in parallel. As a speaker is basically an inductor moving in a magnetic field, you might get backwards voltage induced by it. That might be harmful to the ESP. Others here might know more about that.

You connect the Arduino ground to speaker ground. But that is most likely not the same as the amplifiers ground. Most likely the amplifier drives the speaker symmetrically, so also with negative voltages in reference to the speaker ground. That can damage the ADC of the Arduino. Also it's unclear, how good that ground actually is. That pin is not meant for grounding a microcontroller. Driving a speaker is different from measuring the voltage with an Arduino, so you would need different amplifiers to do it.

I'm not an expert in the field of analog electronics, but I guess you could use a diode to get one half-wave and then feeding it into a low pass filter. The resulting voltage is relatively steady (depending on the cut-off frequency of the filter) and can then be measured by the ESP. I'm sure, that this will only give you a rough measurement of the amplitude, but enough for typical applications like amplitude visualization. For really precise measurements you most likely need to use a more complex electronics setup to work against the non-linearities of the parts (especially the diode).


How to rotate servo every 12 hours using RTC module? I am trying to make a auto fish feeder to feed my fish every 6hours. I want to implement RTC module to my code. So far I've been using only an arduino and a servo using this as a code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(15);
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
      // Wait for 12h
    delay(6 * 3600000);
}

The RTC module I have is the DS1302. It's library cn be downloaded here
The code for the clock is this:
// DS1302_Serial_Hard
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
// web: http://www.RinkyDinkElectronics.com/
//
// A quick demo of how to use my DS1302-library to
// retrieve time- and date-date for you to manipulate.
//
// I assume you know how to connect the DS1302.
// DS1302:  CE pin    -> Arduino Digital 2
//          I/O pin   -> Arduino Digital 3
//          SCLK pin  -> Arduino Digital 4

#include <DS1302.h>

// Init the DS1302
DS1302 rtc(2, 3, 4);

// Init a Time-data structure
Time t;

void setup()
{
  // Set the clock to run-mode, and disable the write protection
  rtc.halt(false);
  rtc.writeProtect(false);

  // Setup Serial connection
  Serial.begin(9600);

  // The following lines can be commented out to use the values already stored in the DS1302
  rtc.setDOW(FRIDAY);        // Set Day-of-Week to FRIDAY
  rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  rtc.setDate(6, 8, 2010);   // Set the date to August 6th, 2010
}

void loop()
{
  // Get data from the DS1302
  t = rtc.getTime();

  // Send date over serial connection
  Serial.print("Today is the ");
  Serial.print(t.date, DEC);
  Serial.print(". day of ");
  Serial.print(rtc.getMonthStr());
  Serial.print(" in the year ");
  Serial.print(t.year, DEC);
  Serial.println(".");

  // Send Day-of-Week and time
  Serial.print("It is the ");
  Serial.print(t.dow, DEC);
  Serial.print(". day of the week (counting monday as the 1th), and it has passed ");
  Serial.print(t.hour, DEC);
  Serial.print(" hour(s), ");
  Serial.print(t.min, DEC);
  Serial.print(" minute(s) and ");
  Serial.print(t.sec, DEC);
  Serial.println(" second(s) since midnight.");

  // Send a divider for readability
  Serial.println("  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -");

  // Wait one second before repeating :)
  delay (1000);
}

So the question here is, how can I set up my code to work with RTC, in order to move the servo every 6 hours?

You have to spend some time and practice coding, it does not come over night. As far as your timing look up for an alarm clock sketch that will do what you want.  Once you understand that you should only have to add a few lines of code. As far as open source the tools you are using are open source. Remember there are people out there that are expertes and there people just starting so expect what you find to fall some in that range of quality.


Decreasing Arduino pro micro power consumption I'm working on a project that involves sending GPS coordinates wirelessly from an arduino board to another one. I was thinking of using an arduino micro for this task. The problem is that I want it to last as long as possible on a lithium battery. I searched and found too many tutorials on how to decrease arduino pro mini power consumption, but I didn't find anything related to the arduino pro micro. So I was thinking, does the same procedure used to decrease the arduino pro mini consumption apply for the arduino pri micro?
Also, what microcontroller do you suggest for this project? (PIC, Arduino mini, micro, nano...)

Bringing Down power consumption by taking the LED out and lowering the
  clock ?

Yes, you can do that! And you are okay with Arduino unless you want to complicate things more...If you want to check out other methods then you can check out the Microcontrollers Schematics and also the datasheets of their Components...


How do you write to a free location on an external EEPROM? I want to log GPS positions to an external EEPROM over I2C.

For example:
Latitude: 51.0000
Longitude: 4.0000

If I remove the decimal place then each of these addresses would consume up to two bytes each.

My question is: How can I log each new set of GPS data to a new memory address on the EEPROM each time?

Bearing in mind that the Arduino might be switched off between entries.

You can divide EEPROM space into entries and provide each entry with a single "dirty" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.

Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "dirty" bit in the LSb. When you log coordinates the first time, you'll have:

 /---"dirty"
01 51 00 00 04 00 00
00 00 00 00 00 00 00
 \---"clean"
...
00 00 00 00 00 00 00

(of course, you don't have to store GPS coordinates as BCD, it's just an illustration).

Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "clean" one and go back one step. Also note that the first entry is always "dirty".

This will go on until all your entries are "dirty":

01 51 00 00 04 00 00
01 52 00 00 05 00 00
...
01 53 00 00 06 00 00

At this point (when you have to write new data but there are no "clean" entries), you start writing from the first entry again, inverting the value of the "dirty" bit:

 /---"dirty"
00 54 00 00 07 00 00
01 02 00 00 05 00 00
 \---"clean"
...
01 53 00 00 06 00 00

(remember that the first entry is always "dirty"? Thanks to this, it's possible to simply swap the values representing "dirty" and "clean" entries without actually erasing anything).

To sum up, the algorithm is:

read the "dirty" bit from the first entry
scan entries until the value of the "dirty" bit changes, or until you reach the end.
to read the last logged data, use the last "dirty" entry
to write new data, use the first "clean" entry. If there are no "clean" entries, start from the beginning, inverting the "dirty" bit.


2WD robot - logic error I am making a basic 2WD robot using Arduino Uno with motor shield.
I am getting no compile errors - but something in my logic flow is not working as expected.

Expected Operation:

Ping sensor does distance check.
If distance is less than 5cm.
Turn both Channel A & B motors half-speed for 1 second.
Stop motors.
Take new distance reading ping, start again.

What however is happening, is that channel A works as expected, but channel B motor keeps running??
Where is my code / logic mistake?

Later date I will add to else statement to turn one wheel to change direction.

/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v
 GND to arduino GND
 Echo to Arduino pin 7
 Trig to Arduino pin 8
 */

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 1000; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
  // put your setup code here, to run once:

Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

  pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
  pinMode(9, OUTPUT); /* Motor Channel A */

  pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
  pinMode(8, OUTPUT);

  }

void loop() {

  /* Distance check begins */

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 /* End distance check */

 if (distance >= 5){
 /* Distance great enough to provide room to move */
  Serial.println("Move!");

  digitalWrite(LEDPin, HIGH); /* LED show movement */

  digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
  digitalWrite(8, LOW);
  analogWrite(11, 123);

  delay(1000);

  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
 }

 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW);
 }

 //Delay 50ms before next reading.
 delay(500);

}

I believe that your error is in that you declare LEDpin as pin 13 and then your motor B as pin 13 as well, that to me would result in errors when you write to the led in the else statement at the end of your code. I would recommend that you clean this up, don't use pins for different things. Try this first.

Your logic is ok in terms of functionality.

Also why is there inconsistency at this part on your code:

digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
 digitalWrite(8, LOW);
  analogWrite(11, 123);

Why do you say pin 12 must beLOW and 13 HIGH when moving forward? Is this the way your un-mentioned circuit setup works, if possible could you add this info?