other interrupts in rc channel reader I have the sketch from James Waldby (Read RC receiver channels using Interrupt instead of PulseIn) working beautifully. I want to use a switch on my TX to start and stop a sequence of lights (emulating guns firing on a ship model). But first, I need the delayed flash routine to work. I have tried a loop counting millis() differences to separate the sequences, but the delays don't delay.

 void loop(){
  rc_read_values();//Mr. Waldby's interrupt routine
  currentMillis = millis();
  previousMillis = currentMillis;
  if(fireGun ==1){
    interval = 3000;
  }else{
    interval = 1500;
  }
  interval = 3000;
  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

//if(fireGun ==1){
  analogWrite(led, 255);
  delay(50);
/* a real gun flash doesn't cut right off; it fades away.
  This sequence simulates that  */
  while(brightness > 0){

    // change the brightness for next time through the loop:
    brightness = brightness - fadeAmount;
    analogWrite(led, brightness);
    delay( 7);
  }
  brightness = 80;
}

The intention here is to flash the led every 3 seconds. The flash loop works fine, but the 3 second delay doesn't.

The delay routine works ok in a sketch by itself.

Any thoughts about what I might be doing wrong?

currentMillis = millis();
  previousMillis = currentMillis;

So currentMillis and previousMillis will always be exactly the same, right?

  if (currentMillis - previousMillis >= interval) {

So if 0 >= interval (which it won't be) do something?

Therefore your fading code will never be executed.


Arduino: The program exited the loop early and execute setup() repeatedly I'm working with Arduino Uno, Adafruit PN532 NFC/RFID Shield and along with other modules. I'm posting this test program because I found there's conflict with the serial output while writing code to integrate all the modules together. I tried troubleshooting by running this code. The result wasn't what I'd expected.

In Arduino, as far as I know, setup() only runs once after starting the program and then loop() will be executed repeatedly. I ran the example sketch called readMiFare provided by Adafruit alone and it was fine. This code can be found at https://github.com/adafruit/Adafruit_NFCShield_I2C/blob/master/examples/readMifare/readMifare.pde. However, when I did the following in main,

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

void loop(void)
{
  nfctestloop();
}

the following conflict showed up. When happened was that whenever I scanned a card to the reader it executed the loop() partially and exited the loop. Even worse, it executed the setup() again and again whenever I scanned a card.

In nfctestsetup(), I just commented out    Serial.begin(115200); from readMiFare.

My hardware setup was a no brainer since I'm using I2C.

Appreciate the help.

After spending a good amount of hours on troubleshooting, I found something interesting. When I commented out all other files except NFC and main, it worked like a charm. So I suspect there could be redefinitions on the pins that the NFC shield uses on other files. I suspect the following code in the other file gave me the problem because I commented out the rest of the code in this file and ran this block of code together with NFC and main. In fact, it's the last line of code in this block that gave me the problem.

Also, I probed on the RESET pin (see the readMiFare link above). It generated a high-low-high pulse whenever I scanned a card. Is this related to the problem?

#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 3     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

Any thought is appreciated.

This can happen when your sketch uses too much memory - the board can no longer assign addresses so it resets leading to an endless loop. Try reducing the amount of memory you are allocating.


How do I pass an Int Array into void for a foreach loop? I know its probably an odd question...but I found a workaround for a foreach loop in C. I have a whole bunch of int arrays that I would like to be able to pass into a void, which has that foreach loop in it. This is my code right now:

int example[] = {1, 2, 3, 4, 5};

void setup () {
    Serial.begin(57600);

    #define foreach(item, array) \
        for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
            keep && count != size; \
            keep = !keep, count++) \
        for(item = (array) + count; keep; keep = !keep)
    }
}

void Words (int w[]) {
    foreach(int *v, w) {
        Serial.println(*v);
        delay(500);
    }
}

void loop () {
    Words (example);
}

However when I run it, it only returns the first number of the array, I need all 5 of them. I know theres all sorts of additional things that could be it, like the * or & symbol but I really don't understand what they do. Any ideas as to how to get that to work?

What you want will not work the way you think: in C++ (just like in C), arrays and pointers are almost the same, and the compiler won't be able to make a distinction between

void f(int* array)

and

void f(int array[])

In particular, inside f() the compiler won't be able to know the actual size of array: for the compiler sizeof array will always be the same as sizeof(int*), i.e. just the size of a pointer, always 2 bytes on Arduino UNO, whatever type it points to.

If you want your foreach macro to work correctly, you have to pass it the actual array count of items as an additional argument:

#define foreach(item, array, size) \
    for(int keep = 1, \
        count = 0;\
        keep && count != size; \
        keep = !keep, count++) \
    for(item = (array) + count; keep; keep = !keep)

And also pass the count of items in Words:

void Words(int w[], size_t size) {
    foreach(int *v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

In loop() you can use sizeof example, because the compiler knows what its size is, from its initialization (an array of 5 integers, i.e. 10 bytes):

void loop() {
    Words(example, sizeof example / sizeof example[0]);
}

You could even define a macro to compute the count of items in an array:

#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

It will work as long as you use it with an argument that is completely known by the compiler:

void loop() {
    Words(example, ARRAY_SIZE(example));
}

Important comments on your original code

You mentioned that you want to "save space", but defining a macro will not help in this regard, as a macro is NOT a function, hence its binary code will be repeated everywhere it is used. It can just help make your source code shorter and possibly clearer.

The way you defined your macro seems weird and overly complex to me: why use 2 for loops when you need only one?
It would have been possible to define it in a simpler way, for example:

#define foreach(type, var, array, size) \
    for(type* var = array; var != array + size; var++)

It would be used as follows:

void Words(int w[], size_t size) {
    foreach(int, v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

Using C++ templates may probably help too, but this is an advanced topic. I'd recommend reading first some good book about C++ before digging into templates.


Arduino Mega timeout communication with programmer error I have an Arduino Mega 2560 and it was working fine until about lunch time when I started getting this error:

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

I know it isn't the code I'm running as I tried to load it onto an Uno and it seemed to load without issue. I need to use the Mega as it has more ports, though.

From what I have read this is potentially an issue with the bootloader and is possibly related to the current version of Arduino. I know virtually nothing about the bootloader; all I know is that it is used to upload code to the Arduino (I think...), therefore I have a fear of just messing around with related files unknowingly.

These pages are the ones I've been looking at, but like I said, I don't really know enough to feel comfortable with just messing around with the files.

Mega2560: timeout communicating with programmer....
Upload Timeout Error on Mega 2560 - Not Sure What Changed

I tried uninstalling my Mega totally, then reinstalling it. I also downloaded an older version of Arduino (0022) and neither option seemed to work.

I don't know what to do, or how to change the 'AVR' files if necessary.

The bootloader on an arduino is just a piece of software written to enable you to update your sketches using the usb connection. Without the bootloader you can't upload sketches using just the arduino ide.

More information about the bootloader can be found here: http://arduino.cc/en/Guide/Environment?from=Tutorial.Bootloader
Look under the heading entitled uploading which explains the part the bootloader plays in uploading sketches.

When you use the "Burn Bootloader" button in the arduino ide it will attempt to write a new copy of the bootloader onto the attached Arduino board. To do this the board must be attached in a specific manner - that is - using the icsp/isp header rather than the usb cable.

Now to program the avr chip directly you have to use an external (hardware) programmer. Fortunately you don't have to buy one if you have a second arduino because the second arduino can be used as a programmer. Instructions for doing so can be found here: http://arduino.cc/en/Tutorial/ArduinoISP

Even more info about the bootloader: http://arduino.cc/en/Hacking/Bootloader?from=Main.Bootloader


Arduino crashing during serial print for no obvious reason I've written some Arduino Code which kept crashing and i couldn't find out why. Then i reduced the code as much as i could in order to see the problem.
The reduced code currently doesn't do anything extraordinary except printing some strings over the serial line.

This is the reduced code:

void setup()
{
  Serial.begin(9600);
  Serial.print("Begin\r\n");
  send_wifi_beacon();
}
void loop()
{
  delay(1000);
}
void send_wifi_beacon()
{
  send_wlan_chip_command("AT+CIFSR");
  Serial.print("notreached"); // this part is never reached
  send_data_over_network(); // can't remove this line otherwise the crash won't happen which is weird since this is never called
}
void read_response_from_serial()
{
  delay(2000);
  Serial.print("==-1\r\n"); // crashes here
}
void send_wlan_chip_command(char* command)
{
  Serial.print("Sending command to wifi module: ");
  Serial.print(command);
  read_response_from_serial();
  Serial.print("Command response: ");
}
// this function is never called, since the crash happens before the call, but it can't be removed otherwise the crash won't happen
// also it can't  be altered then, the crash also will not happen.
void send_data_over_network()
{
  char number[3] = "12";
  //char number[3] = "";
  char length_of_payload[20] = "0123456789012345678"; // 20 digits if assuming 64 bit integer is the maximum this code will ever run on
//  char length_of_payload[20] = "";
  char *command;

  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);
  free(command);
}

This is the according output:

  Begin Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin

Which means that the arduino keeps crashing and resetting. This goes on forever.

The weird thing is, if I change the following two lines to: (in the"send_data_over_network" function as in example above)

char number[3] = "1"; // changed from => char number[3] = "";
char length_of_payload[20] = "123"; // changed from => char length_of_payload[20] = "0123456789012345678";

The output now changes to :

I call this behaviour weird since it shouldn't have any influence on the result because this function(send_data_over_network) is never called in the crash example from before.

Troubleshooting options i already tried:

Reinstalling Arduino IDE , i tried with mutliple versions 1.8 , 1.6, 1.4. 1.0
Different Arduino Boards (Arduino Uno and Arduino Mega)
Different Laptops (since i thought maybe it's related to power issues of my laptop)

Maybe it's something obvious and i just can't see it, but i already spent +16h debugging, so help would be really appreciated.

This code looks wrong:

  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);

First you allocate 26 bytes, then a new string is created, which you strcat to it. This happens in memory that is not allocated (or overwrites other data).

Instead of

  command = "AT+CIPSSEND";

use

  strcpy(command, "AT+CIPSSEND");

Also check that 26 bytes is enough, change it to 128 bytes to be sure (check the correct amount you need later).


Measuring acceleration in g's I am using adxl335 accelerometer with Arduino uno r3 to measure acceleration due to gravity along x axis. I am using 50 ms delay and printing to serial.
I have two questions, which are;

Can I measure fractional values, like .8 in acceleration due to gravity?
when I shake the accelerometer up down along x axis, I don't see any variations in 'g'?

I am using analog pins and 3.3V power supply from Arduino to power the sensor.

If you read the datasheet you can quickly find that the output of the device is 300mV per g.  That means:

Read the analog value
Convert it to millivolts
Divide it by 300

The result is the g value.  If you do it using floating point then yes, you get fractions of a g resolution.

For instance:

float mv = analogRead(0) / 1023.0 * 5000.0;
float g = mv / 300.0;

If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step.  Divide that by 300 and you get a resolution of 0.01628g

As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down.  It's all in the datasheet - it makes for good reading, I suggest you take a look.


Storing and parsing data with Arduino I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:

client.println("GET http://ramp.local/api/actions?");

The response I get is:

[{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17},
{"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20},
{"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17},
{"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}]

How to collect a data in a string variable and parse it to get action_status?

Ideally, you would use a proper recursive JSON parser, like the one
suggested in prakharsingh95's answer. However, if code speed and size
are critical considerations, and if the format of the response is
narrowly constrained, then you can build a fast special-purpose parser.

Here is a simple example. It assumes the response has been stored in the
response char array:

static const char key[] = "\"action_status\"";
const char *p, *q;
char action_status[16];

for (p = response; ; p = q) {
    p = strstr(p, key);    // find key
    if (!p) break;         // not found
    p = strchr(p, ':');    // find ':' between key and value
    p = strchr(p, '"');    // find opening quotes for the value
    q = strchr(p+1, '"');  // find closing quotes

    // Report finding.
    strncpy(action_status, p+1, q-p-1);
    action_status[q-p-1] = '\0';
    Serial.print("Found action status: ");
    Serial.println(action_status);
}

Of course, in production code you would check that every strchr call
returns a non-NULL pointer. And you would check that the status you
found fits in your buffer.

Edit about the pros and cons of this method:

Compared to a proper JSON parser, this approach will give you smaller
and faster code, the drawback is it being more fragile. For example,
this will not detect a corrupted JSON, and it will return garbage if the
action_status happens to be a number instead of a string, or is a
string with embedded double quotes, or if the string "action_status"
appears as a value of some other field... A full JSON parser should
correctly handle all these cases.

On a non-embedded computer, a proper JSON parser would probably be the
only appropriate answer. On a constrained microcontroller environment,
you sometimes have to make trade-offs. In this particular instance, the
“best” answer depends on how much you weight speed and size vs.
robustness against unexpected input.


What is the difference between Tools > Board settings in Arduino IDE? ex: ESP32-Dev v. Huzzah32 I had a recent memory issue where the resolution was to change the Tools > Partition setting.  However this setting wasn't available in the Arduino IDE for the boards I was using (Huzzah32 and NodeMCU-32s).  I changed the board setting to ESP32-Dev Module, and the addition menu items under Tools appeared.  My project compiles and works fine now.

However it never occurred to me to set the Board to the "wrong" type.  What's the purpose of a vendor specific board setting when the more generic one appears to work fine?  What settings should you use and under what circumstance?

My guess is that the vendor specific board settings are more about the peripheral hardware on the boards (USB ports, LEDs, etc) and that the more of those you are using the more likely you'll need to use a board specific setting.   In my case, since my project uses just the WiFi and Bluetooth built into the ESP32 chip itself, that I'm ok, but if I was using a bunch of GPIO and other things I'd need to use the actual Huzzah32.  Is that right?

For ESP32 boards the differences are very minor. In general an ESP32 is an ESP32. The only changes are name to pin mappings, and how to upload code.

There are a couple of different ESP32 modules, but in general all the boards use the same (cheapest) module.

If you look at the pins_arduino.h file for a variant you see that it is pretty much all in the format:

static const uint8_t SDA = 21;
static const uint8_t SCL = 22;

Just mapping names to pins. Note that some are special, like SDA and SCL above, which are used as defaults for the Wire library.

The biggest differences are in the boards.txt portion for the board. This is where any differences in the module will be defined.

In general though all the "specific" boards are just the "ESP32-Dev Module" with some options removed, and a new name give to it.  So you can usually use ESP32-Dev Module for any board as long as you select the right mode for things like flash.

One big benefit of using the correct board, though, is that a #define macro is provided identifying the board. If you want the same code to run differently on different boards (such as using different pins on different boards) you can use that macro to direct the flow of your code.


Can you pass the entries of a strut array to a int array? if so how? typedef struct {
  uint8_t  pitch;
}LearnNote;

#define  MAX_NOTE  500

LearnNote  Noteseq[MAX_NOTE];

int learnindex=0;
void loop() {
 MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity){
Noteseq[learnindex].pitch=pitch;
learnindex++;
}

Its not very clear what you are asking, but I think you are saying can you do this

uint8_t anArray[MAX_NOTE];
anArray = Noteseq.pitch;

In general the answer is no.  However in this specific case off the top of my head I think you probably can (maybe).  You have a struct which only contains bytes.  The compiler will probably pack the sequentially so you will effectively have a contiguous sequence of bytes which you would be able to copy to the byte array by doing:

memcpy (anArray, Noteseq, MAX_NOTE);  // THIS IS BAD PRACTICE!

You can only do this in this case because the types are both 8bit numbers.  Its not a good idea to do this copy between an array of structs and a POD type array is just asking for trouble.

Instead use a function to do it.

int* CopyPitch (LearnNote* source, int* destination, int count)
{
    for (int i = 0; i < count; ++i)
    {
        destination[i] = source[i].pitch;
    }
}

(You should really check for null pointers and stuff, but its just an example)


client.connect() fails except the first time I am communicating with the Web server's database via Arduino GSM shield + GPRS connectivity

void loop()
{
  if (client.connect(server, port))
     {
       .......
      }
  else
     {
      Serial.println("Server not found");
      }
  delay(1000);
}

The first time when the loop() runs in the serial port, the code works perfectly and stores in my server's db. The second time when the loop() runs after some delay, It is unable to connect to the server and results "server not found" . I don't know what is the problem.

Please let me know if there is a way to connect continuously. Thank you

You have to disconnect before being able to connect again otherwise the controller will crash due to memory starvation. Every connect you do takes some memory to register state information. Not sure of the exact commands involved, but it'd look a bit like this:

   if (client.connect(server, port))
     {
       .......
       client.disconnect( .... );
      }
  else
........

Alternatively you can check if you are already connected, and only do a reconnect when necessary, but I don't know which library you are using, let alone if there is a proper check available in it.


Connect ESP32 via MQTT For a project I am working on, I need to connect my ESP32 board to another server via MQTT protocol. I am using the Mosquitto MQTT Broker and it is presently on my laptop. Following is the test code I am using, which I'll build around this program.

#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*****";              //WiFi Name
const char* password = "********";      //WiFi Password
const char* server= "***.***.**.***";    //RPi or Machine IP on which the broker is

WiFiClient espClient;
PubSubClient client(espClient);

int setup_WiFi(){
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Attempting MQTT connection...");
  client.connect("esp32");
  if (client.connect("esp32")){
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
    }
    return 0;
}

int reconnect() {
  unsigned long startAttemptTime = millis();
  while (!client.connected())
  {
    Serial.println("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("esp32")){                 //if (client.connect("esp32", MQTT_USER, MQTT_PASS)) {
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
  return 0;
}

int send_mqtt(){
  setup_WiFi();
  char sss[15]="Hello World";
   if (!client.connected()){
    reconnect();
  }
  client.publish("esp32/test", sss);    //send message
  WiFi.disconnect(true);
  Serial.println("Sent");
  return 0;
}
void setup() {
  Serial.begin(115200);
  client.setServer(server, 1883);   //mqtt server details
  setup_WiFi();
  reconnect();
  send_mqtt();
}

void loop() {
  send_mqtt();
  delay(10000);     //Wait 10 secs before next transmission
}

I tried connection but got this error

Attempting MQTT connection...failed, rc= -2

What am I doing wrong? Any changes I need to make to the .conf file about which I don't know?
Guide me.
Thank You in advance

The code in your sketch is unlikely to be the problem. It works fine for me after I enter the IP addresses and password for my network.
According to the pubSubClient API documentation, the rc = -2 code returned by client.state() is due to the network connection having failed. As your code has already checked that it is connected to WiFi before trying to contact the MQTT broker, it is probably the communication between the two devices that is the issue, not the WiFi connection itself.  Things to check:

Are both devices are on the same network, and do they have a route to contact each other? From the laptop running the MQTT broker, try running ping XXX.XXX.XXX.XXX (replacing the XXXs with the IP address reported by the ESP32), and check you get a response. You might wish to comment out line 67 of your code so it doesn't disconnect from WiFi after every attempt at sending a message, otherwise you will see lots of lost packets.
Have you got the right IP address for the MQTT broker in your sketch? It should be the IP address for your laptop, not the loopback address, 127.0.0.1.
Can you use another device on the same network to connect to the MQTT server? (e.g. a cellphone running a MQTT dashboard app)
Is Mosquitto configured to listen out for remote connections? If you are running v2 of Mosquitto, you have to deliberately configure it to accept incoming connections, otherwise it will only listen to the localhost interface. You would also have to either set up an authentication mechanism or explicitly configure it to allow anonymous connections. This might be why you can connect from the laptop running the broker, but not from other devices.
On the MQTT server, can you see any connection attempts in Mosquitto's log file (/var/log/mosquitto/mosquitto.log)? There might be some error messages that give you further clues.


Does any board provide more than 1024 analog input values? The Arduino boards provide an analog input range of 0V to 5V which translates to 0 to 1023 integer values. The range is determined by the on-board ADC, which in the case of the Uno is a 10 bit ADC (2^10 = 1024).

Do any of the official boards have a larger (>10 bits) ADC? Do any boards provide a wider range of analog input values?

AVR-based Arduinos only have 10-bit ADCs, but the ATSAM3X in the Due has 12-bit ADCs. Additionally, it is possible to interface to higher-resolution external ADCs via I2C or SPI.


How to get each byte in byte array out and be able to work with them on their own? I am currently sending data via my bluetooth and to it I send with me 4 different values looking like this:

byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

And now I am looking for a way to store all these Hello's in different values.

What I have started with is something like this:

if (Bluetooth.available())
{
 while (true)
 {
   delay (50);
   char c = Bluetooth.read();
   readString += c;

   if (readString.length() >0) {

    if (readString[0] == "HelloOne")
    {
       Serial.println ("Hello One has been sent!");
    }

    if (readString[1] == "HelloTwo")
    {
       Serial.println ("Hello Two has been sent!");
    }

    if (readString[2] == "HelloThree")
    {
       Serial.println ("Hello Three has been sent!");
    }

    if (readString[3] == "HelloFour")
    {
       Serial.println ("Hello Four has been sent!");
    }

   }

 }

}

And I have not actually been able to debugg (not currently at home but eager to get to fix this problem asap) so there is a slim chance that my current code might be working? Very unlikely though.

So my question is, what is the correct way to get each value out in a byte array that is being sent with bluetooth to arduino?

Sorry if this sound patronising, its not meant to, I'm just trying to cover all aspects.

byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

You are assigning 4 strings to the array mByte.  A string (lets ignore the Arduino type string for now) is a char* or a char[], so:

char hello1[] = "HelloOne";
char hello2[] = "HelloTwo";
char hello3[] = "HelloThree";
char hello4[] = "HelloFour";

(You don't need to do this in the code, how you have done it is fine, it just shows what you are really saying)

In English mByte should be an array of strings which in code is

char* mByte[] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};

You could do it as

char mByte[][] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};//ERROR

But this won't compile, because the inner array (the text) is different length and the compiler doesn't like that.

Assuming that writeAsync takes a byte as a parameter then the code to write the data becomes this:

for (int stringCounter = 0; stringCounter < 4; ++stringCounter)
{
    // get a pointer to the first element of the string
    // & means get the address (so the value can be set to a pointer)
    // (byte*) means cast (change) the value into a byte pointer.
    byte* currentLetter = (byte*)(&mByte[stringCounter][0];)
    // currentLetter != NULL means the pointer is not equal to NULL, because looking at a null pointer will crash the code.
    // *currentLetter != NULL means the thing pointed to by currentLetter is not the end of the string.
    while (currentLength != NULL || *currentLength != NULL)
    {
        // Write the thing pointed to by the pointer to the function.
        writeAsych(*currentLetter);
        currentLetter++;  // Move on the pointer
    }
}

Sorry I can't compile that at the moment, but it looks about write.  I hope it helps you understand it.


ESP8266 UDP multicast doesn't receive packets I am currently working on an ESP8266 with the Arduino IDE. I try to implement an ESP8266 in STA mode as multicast receiver. I was writing my code with the help of this documentation. Especially the following part:

  The WiFiUDP class supports sending and receiving multicast packets on STA interface. When sending a multicast packet, replace udp.beginPacket(addr, port) with udp.beginPacketMulticast(addr, port, WiFi.localIP()). When listening to multicast packets, replace udp.begin(port) with udp.beginMulticast(WiFi.localIP(), multicast_ip_addr, port). You can use udp.destinationIP() to tell whether the packet received was sent to the multicast or unicast address.

Sending to the multicast group with udp.beginPacketMulticast(addr, port, WiFi.localIP()) and udp.write(message, messageLength)works flawlessly.

The receiving part of my code is as follows:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#define BUFFER_LENGTH 256

const char* ssid = "xxxxxx";
const char* password = "xxxxxx";

WiFiUDP Udp;
IPAddress multicastAddress(226,1,1,1);
unsigned int multicastPort = 4096;

char incomingPacket[BUFFER_LENGTH];

void setup(){
    WiFi.mode(WIFI_STA); //station
    WiFi.setOutputPower(0);
    while (WiFi.status() != WL_CONNECTED)
    {
        WiFi.begin(ssid, password);
        delay(500);
    }
    Udp.beginMulticast(WiFi.localIP(), multicastAddress, multicastPort);
}

void loop(){
    int packetLength = Udp.parsePacket();
    if(packetLength){
        int len = Udp.read(incomingPacket, BUFFER_LENGTH);
        if (len > 0){
            incomingPacket[len] = 0;
            Serial.printf("%s\n", incomingPacket);
        }
    }
}

When sending a packet with a simple multicast sender (with matching IP and port), my multicast receiver on my linux laptop receives the packet, but the ESP8266 doesn't.

Maybe some of you have experienced a similar behavior and are able to give me some hints, where I might be wrong.

EDIT:
Since the time I asked this question I completely ruled out an error of the sender on the linux machine by using a verified, 100% working sender. The ESP8266 still doesn't receive any multicast datagramms.

I recently had the same problem.

The unequivocal answer is that there is a power optimization (internal by Espressif) to save power, I guess, and it really creates havoc in the UDP Multicast receiving. Why? I have no idea. Same problem with the ESP32 and ESP8266.

Solution:

#include "user_interface.h"

and after:

WiFi.mode(WIFI_STA);
// the below instructions and now u will receive.
wifi_set_sleep_type(NONE_SLEEP_T); //LIGHT_SLEEP_T and MODE_SLEEP_T


Arduino Uno - External Power not working properly I am a newbie to Arduino and created my first project. The project is using a Sharp short range sensor and a 7 seg LED board (http://embedded-lab.com/blog/new-version-of-max7219-based-4-digit-serial-seven-segment-led-display/) to count objects.

Everything works fine when on USB power to my computer or if I use a 5v 1A wall adapter with a USB cable. The problem is when I use an external power adapter or use a DC power supply to the Vin. The board powers up and I measured the output voltage on the 5v pin and is measuring around 4.8v.

The Sharp sensor is connected to the A0 Analog in and I see the voltage fluctuate when an object passes, but the LED is not displaying a value when on the external power. The display is connected to GRD, 5v where DIN, CLK, and LOAD pins of the display are connected to pins 7, 6, and 5 as the instructions stated.

I tried two different Arduino boards and several different AC to DC power adapters ranging from 9v to 12v plus used a DC power supply to the Vin and same results.

The code is below and pretty simple (although I am sure there is a lot better way of doing it but this is my first project in C so go easy on me and the function for digits is from a website and not written by me).

If a picture of the project would help I can upload one.

Any ideas or thoughts?
Thanks,
Steve

#include "LedControl.h"
#include <stdio.h>
#include <math.h>

// Arduino Pin 7 to DIN, 6 to Clk, 5 to LOAD, no.of devices is 1
LedControl lc = LedControl(7, 6, 5, 1);
int sensorpin = 0;      // analog pin used to connect the sharp sensor
int val = 0;            // variable to store the values from sensor(initially zero)
int cnt = 1;

void setup()
{
    // Initialize the MAX7219 device
    lc.shutdown(0, false);   // Enable display
    lc.setIntensity(0, 10);  // Set brightness level (0 is min, 15 is max)
    lc.clearDisplay(0);     // Clear display register

}
void loop()
{

    val = analogRead(sensorpin);       // reads the value of the sharp sensor
    if (val >= 650)
    {

    //write values to LED
    if (cnt<=9)
    {
        lc.setDigit(0, 0, cnt, false); // Display 4 to Digit 1-9, " "
    }
    if (cnt >= 10 && cnt <= 99)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt,0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
    }

    if (cnt >=100)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt, 0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
        lc.setDigit(0, 2, getDigitFromNum(cnt, 2), false); // Display 2 to Digit 1-9, " "
    }

    delay(400);
    cnt++;

}
}

// Function: getDigitFromNum returns a digit at a given index of a integer.
// Goes from right to left with the starting index of 0.
int getDigitFromNum(int num, int digit) {
    num /= pow(10, digit);
    return num % 10;
}
// Function: getDigitFromDec returns a digit at a given index of a double.
// Goes from left to right with the starting index of 0.
int getDigitFromDec(double dec, int digit) {
    dec *= pow(10, digit);
    return (int)dec % 10;
}
// Function: getDigitFromNum returns the decimal values of a double.
double getDecimals(double dec) {
    return dec - (int)dec;
}

The only difference between powering from USB and powering through the barrel jack is the voltage is reduced to 5V through a Low Dropout (LDO) voltage regulator. These are typically a clone of the popular LM1113-50 and vary in current handling capacity from around 500mA up to 1A.

I notice your board is not a genuine Arduino - therefore the components used may be at the cheaper end. So we'll assume a low-grade LDO that only handles 500mA before going into thermal shutdown with good heatsinking. Since there isn't on these boards we shall therefore assume a maximum of 400mA before it gets too hot. Probably somewhat conservative.

So if your entire circuit is drawing more than about 400mA you can expect the regulator to shut down, or at least to reduce the current and/or voltage available.

The fact you're seeing 4.8V rather than 5V could be an indication that there is voltage droop occurring - i.e., the regulator is not able to supply enough current so the voltage drops. This would be accompanied by the regulator getting very hot.

The regulator is the device with 3 pins on the right side and a single tab on the left directly above the barrel jack socket. See how hot that is getting.

As a rule of thumb if you can hold your finger on it without crying for 10 seconds it's not too hot.

Another thing you can do is to reduce your circuit to the bare minimum. Unplug absolutely everything and upload the Blink example sketch. Power that from the external DC and see if the LED blinks for you. If it does then the power supply is working OK. You can then add your peripherals one at a time to see when it fails.

If it doesn't blink then there must be something inherently wrong with the supply.

One possibility is that the LDO is oscillating due to insufficient or incorrect input and output capacitors. This basically means the "5V" voltage it gives out is actually wildly swinging between say 4.5V and 5V or 4.75V and 5.25V, which really confuses the microcontroller. Cheap LDOs are often more sensitive to the capacitors they are paired with and can suffer from this kind of problem.

To diagnose that kind of thing you would really need access to an oscilloscope to analyse the voltage.

If it is oscillating a 10µF ceramic capacitor connected between the lower two pins of the LDO (as orientated in your picture - that is Vout and GND) may cure it. A 1206 surface mount capacitor fits nicely across those pins and is reasonably easy to hand solder. You could also try a through-hole capacitor (ceramic again) between 5V and GND on the power header, but you really want it as close to the LDO as you can get it, so soldered direct to the LDO's pins is best.


Arduino board to control microwave oven? So I've taken apart an old microwave oven with a touch-sensitive LCD screen. I understand that I could die from playing around with this, so I've disconnected the high-voltage transformer and the magnetron. I'm also not going to remove any of the safety switches like the door switch. My question is, how is the microwave controlled? I'm thinking there is a computer chip somewhere in the circuit, and I'm looking to replace it with an Arduino board plus some extras, like AC relays and such. I'm curious as to how the microwave oven controls its functions, like power level, cooking time, and the beeping. Any advise as to how I could get started interfacing?

Is the power level controlled by PWM by any chance? Can you PWM alternating current?

It's pretty much all proprietary. It can be done, but you'd have to replace all the circuitry with the Arduino, interfacing with the existing magnetic and mechanical devices and doing everything in your own code.

Power level is controlled by PWM, but it's extremely low frequency PWM, on the order of 0.05Hz (20s period). That's why there are two different sounds that come from the microwave when it's not at full power; one when the magnetron is active, and one when it is off.


USB Device not recognized (error 43, arduino uno) I know that there's already post about this, but mine is different. Instead of not recognized, it gets recognized, and I can upload codes, but after a while, windows starts to not recognize it. And there is a temporary fix for this for my laptop, I need to restart. And even after restarting, it still becomes not recognized after a while

Edit : forgot to mention, even if it is not recognized, it still sends power to the arduino

The USB microcontroller Atmega16U2/Atmega8U2 on the Ardunio UNO board might be corrupted. Try uploading the USB to Serial HEX file with boot-loader found in C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\firmwares\atmegaxxu2\Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
using Flip OR any other other ardunio (as an ISP programmer). for doing this you have to first enter BOOT-LOADER by shorting the Reset Pin of the USB controller to GND  both pins can be found on ICSP2 of the UNO.
This will surely solve the issue.
But,
if the problem still persists then your USB controller is damaged and have to replace the controller and again upload the USB to serial firmware, the process is same as mentioned above, but you don't need to short reset and GND as you don't have an boot loader installed in the new controller.


Control I2C relay board from two Arduino Uno how can I make multi master Arduino device to work with single I2C device?
As both the master device are 20 m away from Slave device,

I am using the I2C relay board to connect with 2 Arduino boards and need to connect I2C device and create the two way switching technique from this.

Any suggestions here will be a great help.

What you want is to operate in multi-master mode.  This is a supported configuration of I2C - however the Arduino API has no support for it.

It involves each master identifying if a collision has occurred and stopping transmission if it has - to then retry transmission later on.

The Arduino hardware can do it, but the software can't. You would have to bypass the software and control the I2C interface yourself (or locate a better library than the Wire library that supports multi-master).


ESP8266 problem with recieved data trasmission via TCP I am having small project where I want to read couple of analog inputs from Arduino UNO, send it via software serial to ESP8266-01 and from that to python server using TCP.

Data is sent to ESP using this code on Arduino UNO

#include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    int pin = 5;

    void setup() {
      mySerial.begin(9600);
      delay(20000);
    }
    void loop() {
      delay(1000);
      int data = analogRead(pin);
      mySerial.println(data);
    }

Code on ESP is bellow

void loop() {
    while(Serial.available()>0){
    char data = Serial.read();
    client.print(data);
    }
}

When data is sent to Python server, it prints it out but data is sent in two seperate parts, so it always looks like this

9
59

, but number sent from arduino is just 959!

Python server code snipet:

while True:

        #Receiving from client
        data = conn.recv(1024)

        print data

        #send data to database
        post.create(
            current = str(data)
        )

         if not data:
            break

So the question is, why data sent to server is separated in two parts? Maybe it have to do something with how data is reading from serial on esp?

You assume all 5 bytes of 959\r\n are received by the server at the same time. The data is sent byte after byte, based on the client.print(data) in the ESP code and assuming the underlying library doesn't buffer bytes before transmitting, so there's no way they'll arrive at the server simultaneously. Most likely, your first pass with conn.recv(1024) grabs the first byte 9 and times out. And then on the second pass, the others (at least 2) arrive and are read. The newline between the packets is typical Python 2 print behaviour.

What you need to do is parse the data at the server. Basically read data till you get CRLF i.e. \r\n, which is a good enough delimiter and you're sending it already anyways, and then use that to know when to write to your database.


Using Arduino as a standalone compiler I mostly program in C/C++ so I conviniently have a GCC compiler for all my compilations. I was wondering if there is a special compiler for Arduino that can be used just like the GCC Compiler? Because just taking a .ino sketch and passing it to the comiler with a few arguments will be a lot easier for me that all those things in the IDE, and furthermore I use Sublime Text as my text editor. And making a C program work in Sublime is as simple as providing it a path to the compiler. So I would like a portable smaller version of the Arduino Compiler that is NOT the whole IDE folder. Hope I get nice answers!! Thanks in advance.

First of all: The Arduino IDE brings its own GCC compiler. It is a version, that can compile for the AVR platform (don't know, if the standard version is capable of that).
When you activate verbose output for compilation in the preferences of your Arduino IDE, you can actually see, what calls to GCC the IDE is doing. You could use that to replicate it.
If you only want to use the sublime text editor for programming and not rebuilding the compilation environment of Arduino for fun (which I wouldn't able to help with), you might wanna have a look at the Arduino-cli. It gives you a tool to invoke important function, that normally the IDE does, via commandline (like installing cores and libraries, compiling and uploading). Thats what I'm currently using with sublime for programming in Arduino. It allows me to invoke building an uploading from sublime without having the Arduino IDE open.
If you want to go that way, here are the sublime-build files, that I use for my Arduino Nanos and ATtiny84s. Maybe you can adapt them for your needs. (Note: I omitted multiple variants, that I use to upload on different com ports, because the com port is the only thing, that changes there. Also I'm on Ubuntu, so on Windows or Mac it might look a bit different)
For the Nano:
{
    "cmd" : ["arduino-cli compile --fqbn arduino:avr:nano"],
    "working_dir": "$file_path",
    "shell":true,
    "file_patterns":["*.ino"],
    "variants": [
        {
            "cmd" : ["arduino-cli compile --fqbn arduino:avr:nano && arduino-cli upload -v --fqbn arduino:avr:nano:cpu=atmega328old --port /dev/ttyUSB0"],
            "working_dir": "$file_path",
            "shell":true,
            "name": "Compile & Upload ttyUSB0"
        }
    ]
}

For the ATtiny84:
{
    "cmd" : ["arduino-cli compile --fqbn ATTinyCore:avr:attinyx4:chip=84"],
    "working_dir": "$file_path",
    "shell":true,
    "file_patterns":["*.ino"],
    "variants": [
        {
            "cmd" : ["arduino-cli compile --fqbn ATTinyCore:avr:attinyx4:chip=84 && arduino-cli upload -v --fqbn ATTinyCore:avr:attinyx4:chip=84 --programmer arduinoasisp --port /dev/ttyUSB0"],
            "working_dir": "$file_path",
            "shell":true,
            "name": "ATtiny84: Compile & Upload ttyUSB0"
        }
    ]
}


Serial plotter looks different and doesnt print graph When I open my serial plotter to get the graph for my HC-SR04 sensor it doesn't show anything. My plotter looks different too. I have attached images below as well.

Only those numbers on the top-most move with time.(100,200,300)
Here's my code:
int trigPin = 12;
int echoPin = 11;

int pingTravelTime;
float pingTravelDistance;
float distToTarget;

int baudRate = 9600;

int dT = 10;
int dT2 = 500 ;

String msg1 = "The distance is equal to ";
String msg2 = "cm";

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

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(dT);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(dT);
  digitalWrite(trigPin, LOW);

  pingTravelTime = pulseIn(echoPin, HIGH);

  pingTravelDistance = pingTravelTime * ((765. * 5280. * 12.) / (3600. * 1000000));
  pingTravelDistance = 2.54 * pingTravelDistance;
  distToTarget = (pingTravelDistance / 2);

  Serial.println(msg1 + distToTarget + msg2);

  delay(dT2);
}

What do I do??

The serial plotter expects you to send numbers, and only numbers. If it
reads any other text, like for example
“The distance is equal to 9.88cm”
It assumes these are the names of the columns of data that are to
follow. So it chooses one color for each column and prints the color key
on top of the graph.

What do I do??

Just remove the prose and print only the numbers. You may print
something like “distance(cm)” in setup() if you want to have the key
displayed, but that is not required.


Sending data from Processing and receiving as uint32_t I need to send data from a processing sketch to an Arduino to pass to a function that takes a uint32_t.  How to I send the data in Processing to be run on the Arduino

I recommend studying up on bitwise shifts (<< and >>), along with the bitwise OR and AND. They're what you're going to need, especially since atoi() would only give you a 16 bit, signed integer.

Let's say that your variable's binary is this (split up into 4 segments):

10010010 10110101 01010010 10010100

Sending

uint32_t myVarCopy = myVar;
for(int i = 0; i < 4; i++) {
    Serial.write(myVarCopy & 255);
    myVarCopy = myVarCopy >> 8;
}

The first line in the loop modifies the variable by bitshifting right eight to allow us to read the data eight bits at a time. We have to, whenever sending data through the serial port, "trim" any data that is in the 9th digit or above using the & 255 part. This allows us to split this int up into four bytes.

How the myVarCopy variable would look over the four iterations:

After 1: 00000000 10010010 10110101 01010010 (sent 10010100)
After 2: 00000000 00000000 10010010 10110101 (sent 01010010)
After 3: 00000000 00000000 00000000 10010010 (sent 10110101)
After 4: 00000000 00000000 00000000 00000000 (sent 10010010)

Reading

uint32_t buffer = 0;
for(int i = 0; i < 4; i++) {
    buffer = (buffer >> 8) | (Serial.read() << 24);
}

This code works by adding the newest data onto the digits 25-32 after it moves everything else over eight bits.

This is how the buffer variable would look over the four iterations:

After 1: 10010100 00000000 00000000 00000000
After 2: 01010010 10010100 00000000 00000000
After 3: 10110101 01010010 10010100 00000000
After 4: 10010010 10110101 01010010 10010100

Depending on how Processing works, you might have to worry about little/big endian encoding to ensure that your data is in the right order. Warning: I haven't tested these yet as an IDE isn't installed on the computer I'm typing this on. Also, I don't know the exact function calls for Processing, so it might not compile.


Powering 8-channel relay correctly Replication Steps:

595N shift register powered by arduino
Each output on register connected to 1 of 8 relays in relay board
Arduino programmed to loop over each 8, triggering 1 relay at a time
Dedicated 5v power line connected to relay board as so
Begin loop

Expected: LED's light and relays make contact iterating over each of 8
Actual: Occasionally relay/led fires, then immediately goes out/disconnects OR occasionally relay/led x should fire, but instead relay x+1 fires

Disconnect separate DC supply from relay board

Expected: Relays will not fire/make contact, LED's will continue buggy pattern from step 5 actual.
Actual: Relays don't fire (expected), LED's light in correct order always, no bug

Friend who is more hardware savvy thinks it could be simple matter of Separate DC supply needed more voltage as my supply is providing enough amperage to fire all 8 contacts simultaneously. However, this board is rated for only 5V correct?

What gives?

you need a ground connection between the arduino and the relay board


How to choose alternate I2C pins on ESP32? I'm a begginer with Arduino and this may be a basic question but I'm facing an issue.

I'm using a HTU21D sensor with an ESP32. This sensor use I2C communication. Inside the Arduino library, there is this function to start to collect data:

//Start I2C communication
void HTU21D::begin(TwoWire &wirePort)
{
  _i2cPort = &wirePort; //Grab which port the user wants us to use

  _i2cPort->begin();
}

As you can see, we can set in this function which port we want to use. Perfect. But my probleme is that I don't know how to use the type TwoWire. I checked some documentation but I was still unable to find a solution. I want to use GPIO_16 as SDA and GPIO_17 as SCL.
So I tried something like that without result: htu21d.begin(Wire(16, 17));

How to set SDA and SCL pin in TwoWire type ? (in my case GPIO_16 and GPIO_17)

I was able to resolve my issue thanks to Juraj comment.
I did :

Wire.begin(16, 17);
htu21d.begin(Wire);


Can I monitor data of variables while simulating Arduino on Proteus? I simulate Arduino UNO on proteus 8 Pro. I use Arduino software for writing a program.

Is it possible to trace or know the data that are stored in valuables while running the code on Proteus?

I would like to know how the code is running step by step so that I can find logical errors.

Thank you,

It is possible. By using several tools on "Virtual Instruments Mode" such as SPI-Debugger, I2C-Debugger, Virtual Terminal, or Logic Analyser.

  I would like to know how the code is running step by step so that I can find logical errors.

For example, you can use Virtual Terminal and print the value of variables you want to examine


Forward kinematics of a differential drive robot I've been braking my head over this for the past few days and can't make it work.. So, I have a small robot with a rotary encoder on each wheel and i want to track its position (in x and y) on a flat plane. I know it's called forward kinematics, but i can't seem to get it working. I found a lot of great public sheets, but i think, out of all of them, this is the best one It had the equations of how to calculate the X and Y on page 74:

Vicc=L * (Din / (Dout–Din) + ½) (page 73) //Din is the inner wheel of the turn traveled distance, Dout is the outer wheel
Xtδ=Xt+Vicc*(sin(θt+θΔ) – sinθt)
Ytδ=Yt+Vicc*(cosθt - cos(θt+θΔ))
θtδ=θt+θΔ //angle measurement

Where Xtδ and Ytδ are the position of the robot (x, y); Xt/Yt/θt is the position of the robot when the counting of the position has been started; θΔ is the angle of the robot now;
. Here's The code that I tried to write using the equations. I expected it to write my coordinates in x and y, but when i moved the wheels, it sent me big, random numbers, which are fluctuating up and down, which looks like a sine wave. What am I doing wrong? Could you guide me to the right path? My end result, that I want to reach is controlling 2 both motor speeds and knowing the robots position (doesn't need to be very precise though).
Thanks in advance!
EDIT: Added code from PasteBin
#include <Encoder.h>

Encoder Left(3, 2);
Encoder Right(0, 1);

float R = 385; //mm
float r = 12.5; //Wheel diameter in mm
float L = 8; //Distance between the wheels in cm

double LeftDist = 0;
long LOldPos  = -999;
float LNewPos;
int Correction;

double RightDist = 0;
long ROldPos  = -999;
float RNewPos;

int angle= 0; // Robots current angle
unsigned long t;

int Xold= 0; //position at the start of the calculation
int Xnew= 0; //new, calculated position
int Ystart= 0; //position at the start of the calculation
int Ynew= 0;//new, calculated position
int OldAngle= 0; //angle at the start of the calculation
int NewAngle= 0;// new angle at the end of the calculation
int Vicc;

void setup() {
  Serial.begin(9600);
  t = millis();
}

void loop() {
  Encoders();
  if ((millis() - t) >= 100) {
    Xold= Ynew; //setting the new position to old
    Yold= Ynew; // setting the new position to old
    OldAngle= NewAngle; //Setting the new angle to old

    Vicc = (L * (LeftDist / (RightDist / LeftDist))) + 0.5;
    Xnew= Xold + (Vicc * (sin(OldAngle + Angle) - sin (OldAngle))); //Calculation of X
    Ynew= Yold+ (Vicc * (cos(OldAngle) - cos(OldAngle+ Angle))); //Calculation of Y
    NewAngle = OldAngle+ Angle;

    t = millis();
  }

  Serial.print(angle);
  Serial.print("        ");
  Serial.print(Xnew);
  Serial.print("        ");
  Serial.println(Ynew);
}

//0.9mm/1 deg
void Encoders() {
  LNewPos = Left.read();
  if (LNewPos != LOldPos) {
    LOldPos = LNewPos;
    LeftDist = ((LNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  //-----------------------------------------------------
  RNewPos = Right.read();
  if (RNewPos != ROldPos) {
    ROldPos = RNewPos;
    RightDist = ((RNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  angle= (abs(RightDist - LeftDist) * 0.9) - Correction; //calculate the angle the robot has turned
  if (fi >= 360) Correction += 360;
  else if (fi <= -360) Correction -= 360;
}

From your use of the number 360 at the end of the Encoders() function, I am thinking that you are using degrees for the angles.  That won't work with sin and cos.  The trig functions all expect angles in radians.  To convert degrees to radians, multiply by PI/180.


LEDs instruction code does not loop I am using Neopixel Library and a Trinket Pro 5V Microcontroller to chase first three LEDs on a strip and then burst the last 2 (could be modified based on the number of LEDs).
The LEDs chase only once. See the code below. I am not sure why, even though the logic is inside the loop function, it only executes once. Any suggestions?

#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino? How many Neopixels do you want to chase (starting from the first in address 0. How many do you want to burst at the end?
#define NUMPIXELS      5
#define NUMPIXELSCHASE 3
#define NUMPIXELSBURST 2

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
  // End of trinket special code

  pixels.begin(); // This initializes the NeoPixel library.
  clearLEDs();
  pixels.show();
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  for(int i=0;i<NUMPIXELSCHASE;i++){

   pixels.setPixelColor(i, INDIGO);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay (200);
  }

  for(int i=NUMPIXELS-NUMPIXELSBURST;i<NUMPIXELS;i++){

   pixels.setPixelColor(i, AQUA);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay(0);
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<NUMPIXELS; i++)
  {
    pixels.setPixelColor(i, 0);
  }
}

Thank you.

Your 1st pixel should go indigo & stay there, & the other 2 very briefly show Aqua before going back to Indigo. Try a longer delay than 0 at the end, and then clear them down for the next loop.


Can't flash ESP8266 anymore (NodeMCU) So I've been happily making away with these nodeMCU boards now for a while but I came across a strange issue when updating some code on my board.The problem was that I couldn't flash anymore with Arduino's IDE (OR the NodeFlasher tool)

The error I was getting in Arduino's IDE was:

warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

I tried flashing over all the memory with the flash tool but that didn't work, I also tried connecting D3 to 3.3v output, that did nothing. I've also tried holding the flash button down while flashing without any effect.

The fix ended up being to use a 220ohm resistor between D3 and GND (It has been pointed out, though I haven't tested it, that just wiring D3 to ground on startup should have the same effect). Then unplugging the USB cable, plugging it back in, then flashing the blink program to test. That got it going. I tried a 10kohm resistor too per some documentation I read but that didn't end up working. Wanted to post in case someone else stumbled on this issue.

Source

GitHub Issue

Helpful Articles:

ESP8266 bootloader modes

NodeMCU Pinout


Transistor slows motor instead of turning it off I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat.

I'm using an Arduino Uno's digitalWrite() feature to activate a transistor, allowing the external 9V battery to turn on the motor.

Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that.

Here's the schematic of my circuit:

simulate this circuit – Schematic created using CircuitLab

Code:

void setup(){
  pinMode(9, OUTPUT);
}

void loop(){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(1000);
}

Why isn't the motor completely turning off?

I can't make much sense of your diagram-  but this is the correct way to do it:

simulate this circuit – Schematic created using CircuitLab

R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on.

You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.


Overheating Shift-Register(74HC595) I am working on a project where I need to use around 50 LED's connected to an Arduino UNO board. To begin with i worked on the tutorial provided by Arduino (https://www.arduino.cc/en/Tutorial/ShiftOut) to connect two shift registers(74HC595). Everything works fine, but the shift registers get very hot in just a few minutes. Is this normal?

I can only think about two things:

(least probably): the entrance (VCC) voltage is too high.
(most probably): the resistors to the LEDs are (too) low .. Recalculate the values and check the max amperes which can be handled by the output pins of the shift registers.


Possible to drive Waveshare E-ink without driver hat? I bought and E-Ink display from waveshare and it came with such a “driver hat”: https://www.waveshare.com/wiki/E-Paper_Driver_HAT#Display_Config_Switch
I am wondering what exactly is the role of this component? Why can’t I directly connect the cables from the display to the GIPO pins and drive the display without the driver hat - given the right software?
(I am also happy to get a pointer to a better forum to ask in if this here isn’t the right place.)

No, you need the hat, or something equivalent. Turn it over. You see all those components? They exist to generate the right voltages for the ePaper display. Without those it won't work.
Sure, you can recreate it from the schematic, but why bother when you have it already?


Mediatek GPS periodic mode I'm trying to build a low power GPS datalogger and I am trying to get the Mediatek based GPS module (Quectel L80-R) to run in periodic mode. I've sent the PMTK225 code to the module with various parameters, but it never seems to go into stand by or back up mode. Code below.

//Testing that commands sent to the GPS unit work

#include <NeoSWSerial.h>
NeoSWSerial gpsPort(3,2); // pins 3/2

#include <NMEAGPS.h>
NMEAGPS gps;

void setup() {

  // connect at 115200 so we can read the GPS fast enough and echo without   dropping chars
  // also spit it out
  Serial.begin(115200);

  gpsPort.begin( 9600 );
  gps.send_P( &gpsPort, F("PMTK605")); //firmware version
  delay(100);
  //gps.send_P( &gpsPort, F("PMTK314,-1")); //reset to default
  //gps.send_P( &gpsPort, F("PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC_GGA
  //gps.send_P( &gpsPort, F("PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC only
  delay( 100 );
  //gps.send_P( &gpsPort, F("PMTK220,200") );  // 5Hz
  //gps.send_P( &gpsPort, F("PMTK220,1000") ); //1hz
  delay( 100 );
  //gps.send_P( &gpsPort, F("PMTK225,0")); // normal mode
  //gps.send_P( &gpsPort, F("PMTK223,1,25,180000,60000")); // ephemeris data receiving
  gps.send_P( &gpsPort, F("PMTK225,2,3000,10000")); //period mode but not working
  //gps.send_P( &gpsPort, F("PMTK161")); //stand by mode
  //gps.send_P( &gpsPort, F("PMTK103")); //cold start
  delay(100);
  gps.send_P( &gpsPort, F("PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC only

  //gps.send_P( &gpsPort, F("PGCMD,33,0") );   // No antenna status messages needed
  delay( 100 );

  Serial.println("Ready!");
}

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

Quectel L80-R does NOT have periodic mode, while the L80 does.


Quick Programming Check/Review I've been racking my head trying to start programming in a library organized method. My code works, but the translation and split to a .h and .cpp file is riddled with errors.

It's gotta be stupidly simple all I'm asking for is a review:

Header File

# ifndef _INITIALIZE_H
#define _INITIALIZE_H

#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

//-Extra Includes-
#include <config.h> //Provides baud...
#include <SSC32.h>

#define STANDARD 0
#define DEBUG    1
#define VIRTUAL  2

class Initialize {
    private:
        int _mode;
    public:
        Initialize();
        void begin();

};

#endif

associated .cpp file:

//Comments
#include <Initialize.h>
SSC32 SSC;

Initialize::Initialize()
{
    _mode = STANDARD;
}

void Initialize::begin()
{
    SSC.begin(baud);
    if(Serial.available() > 0){
        if(sscReturn == 1){
            Serial.println("ver");
        }
    }
}

The error from the compiler:

D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp: In member function 'void Initialize::begin()':
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:12: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected primary-expression before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected ';' before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected ')' before ';' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:17: error: expected primary-expression before '==' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:21: error: expected ';' before ')' token
Failed compiling libraries

Sorry, figured it out.

In the "config.h" file I was pulling, I had a
 #define = 18;

instead of a #define 18

I might be wrong, but the compiler stopped complaining


Project 2: Arduino controlled spaceship interface The circuit diagram attached shows that the switch is open. Yet, the LED connected to pin 3 of the arduino board lights up.

I don't understand this - the circuit is open, so why should pin 3 light up?

I discussed this with one of my friends - he said that each pin on the board receives voltage after the battery is connected. If this is true, then that would answer my question.

This is my code:

int switchState = 0;
//configures the digital pins
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(2, INPUT);
}

//Checks the voltageo of the digital input and chooses the pin for voltage ( pin 2 )
void loop() {
  switchState = digitalRead(2);

  if (switchState == LOW) {
    //Button is not pressed

    digitalWrite(3, HIGH); //Green LED
    digitalWrite(4, LOW); //Red LED
    digitalWrite(5, LOW); //red LED
  }

  else { //the button is pressed
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);

    delay(250); //wait for a quarter second
    //toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); //wait for a quarter second
  }
} //go back to the beginning of the loop

So everyone else knows where this is from enter image description here.

EDIT

I have edited the image you gave to attempt to answer your question on 'wiring' :

The first image shows simply and crudely how the parts are basically connected or there relationship.

The second one shows how the current flows on the circuit, there is a key.

What you need to do is take the information from the link you give in the comment and apply logic to it, like if you used a logic probe and stuck it one end of the switch, the right side in that image, it would be high, if though you do so on the left it would be low. Hence no current flows in that circuit but there is current flow in the circuit looking at it.

What you have not examined is the code related to your project or the description of the project.

Looking at the code:

// Create a global variable to hold the
// state of the switch. This variable is persistent
// throughout the program. Whenever you refer to
// switchState, you’re talking about the number it holds
int switchstate = 0;

void setup() {
  // declare the LED pins as outputs
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // declare the switch pin as an input
  pinMode(2, INPUT);
}

void loop() {

  // read the value of the switch
  // digitalRead() checks to see if there is voltage
  // on the pin or not
  switchstate = digitalRead(2);

  // if the button is not pressed
  // turn on the green LED and off the red LEDs
  if (switchstate == LOW) {
    digitalWrite(3, HIGH); // turn the green LED on pin 3 on
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
  }
  // this else is part of the above if() statement.
  // if the switch is not LOW (the button is pressed)
  // turn off the green LED and blink alternatively the red LEDs
  else {
    digitalWrite(3, LOW);  // turn the green LED on pin 3 off
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, HIGH); // turn the red LED on pin 5 on
    // wait for a quarter second before changing the light
    delay(250);
    digitalWrite(4, HIGH); // turn the red LED on pin 4 on
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
    // wait for a quarter second before changing the light
    delay(250);
  }
}

From this we see that the default state of this code in the first if() statement is to turn on PIN3 and leave the rest off when the button is not pressed.

From Arduino:

   A green LED will be ON, until you press a button. When the Arduino
 gets a signal from the button, the green light will turn off and 2
 other lights will start blinking.


Yun UBoot Prompt Not Showing I have a Geeetech Iduino Yun Shield. I accidentally flashed the wrong firmware image (not the sysupgrade) to the board. I then tried using the Yun UBoot Reflash method. However, when I open the console monitor from the IDE and restart/reboot the board, I do not get the UBoot prompt. I have attempted to run it at least ten times without receiving any console/serial output.

EDIT: The shield is running on a Leonardo base board.

Is there anything I can do to load the correct firmware onto the board and get it operational or is the board truly bricked? If so, is it possible to obtain a new Atheros AR9331 board to replace the existing one or should I buy a new Yun?

Update: I have tried to get the shield to do an FTP boot, as detailed here by Majenko. I get to the stage where I get the dr_boot> prompt. However, when I type in tftpboot 0x81000000 dragino2-yun-common-v2.0.6-kernel.bin, I get no feedback; it just sits there indefinitely (unless I interupt the process). I can't figure out what I'm doing wrong.

The shield is very different to the real Yun when it comes to serial communication.

Typically the Atheros's UART is mapped to pins 0/1 of the shield for communication with the board it is plugged in to. Those pins are also the pins you use to communicate with the PC, so the normal YunSerialTerminal sketch can't be used.

Instead you will have to lift those pins out of the socket they go into (depending on the shield you may just be able to bend them slightly) and then manually connect them (along with ground) to an external USB to UART adaptor (e.g., FT232) to use for the communication.  Nothing needs to be installed into the Arduino board since that is now just being used as a power supply.

See this answer for which pins to use to run the shield stand-alone.


LiquidCrystal_i2c and Pin 2 I'm trying to read temperature and humidity from a DHT11 sensor and write values to a 20x4 LCD.
I hit a behaviour I don't understand. When I use the DHT tester program that come with the DHT library, everything works well. I get the DHT information on the Serial console. This DHT tester program use the pin 2 to read the data from the DHT.

I wrote the following code who works perfectly:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>  // F Malpartida's NewLiquidCrystal library
#include <DHT.h>

#define DHTTYPE DHT11
#define DHTPIN 13      // Digital

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
  }
  Serial.println("Serial OK!");

  dht.begin();
  lcd.begin(20,4);
  lcd.setBacklight(0);
  lcd.clear();
  lcd.print("Hello! ");

  Serial.println("Init finished!");
}

void loop() {
  delay(2000);

  float DHT_hum = dht.readHumidity();
  float DHT_temp_c = dht.readTemperature(false);
  float DHT_temp_f = dht.readTemperature(true);

  if (isnan(DHT_hum) || isnan(DHT_temp_c) || isnan(DHT_temp_f)) {
    Serial.println("Failed to read from DHT sensor!!");
    lcd.clear();
    lcd.print("fail! ");
    return;
  }

  float heat_index = dht.computeHeatIndex(DHT_temp_f, DHT_hum);

  Serial.print("Humidity: ");
  Serial.print(DHT_hum);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(DHT_temp_c);
  Serial.print(" *C ");
  Serial.print(DHT_temp_f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(heat_index);
  Serial.println(" *F");

  lcd.clear();
  lcd.print("Humi: ");
  lcd.print(DHT_hum);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print("Temp: ");
  lcd.print(DHT_temp_c);
  lcd.print("C");
  lcd.setCursor(14, 0);
  lcd.print("HI: ");
  lcd.setCursor(14, 1);
  lcd.print(dht.convertFtoC(heat_index));
  lcd.print("C");

}

As you can see, I use pin 13 for the DHT11 (DHTPIN).
If I set to it to "2" then my program is no longer working (having the pin connected or not doesn't change the result).
The serial display

Serial OK!
Init finished!
Failed to read from DHT sensor!!

and that's all, it even doesn't loop to display "Failed to read from DHT sensor!!" again. LCD text doesn't change too. Like if the program is totally exiting after "Serial.println("Failed to read from DHT sensor!!");"

I'm lost... The LCD lib I use is the very common one from fm
https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

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

Are you not using pin 2 in the LiquidCrystal_I2C constructor? So you can't also use it for the DHT sensor.

I withdraw that suggestion.

Can you please try saving some RAM?

Use the F macro with your prints, eg.

  Serial.print(F("Humidity: "));
  Serial.print(DHT_hum);
  Serial.print(F(" %\t"));
  Serial.print(F("Temperature: "));

Ditto with the lcd.print() calls.


How can I measure the point of contact between two wires? I'm not sure the best way to ask this question, so I'll try to explain what I'm looking for, and roughly what I think is involved.

I want to measure the point of contact between two wires. This seems like it could be a resistance measurement, but I wasn't sure if that was the best way to go as it seems like the amount of change would be too small to measure.

Specifically I have two wires (more likely some sort of conductive ribbon) on a glove. One wire runs along the index finger, and the other is at the tip of the thumb. When someone touches their thumb to their finger, I want a value that indicates approximately where they touched.

For example, if they touch the tip of their finger to their thumb the value would be 1. If they touched their thumb to their first knuckle, then the value would be 0.75. And so forth. With a touch between two "points" producing a value in between.

Ideally someone could slide their thumb down their finger and produce a slowly changing value from 1 to 0.

Is resistance the way to go for this? It seems like there could a lot of other variables (surface area of contract, humidity, etc) that could dramatically change the resistance. Is there a better method?

Update: Because of some overzealous votes to close and confusion, this will be using the Arduino platform (maybe an ESP32, if that matters) once I figure out what sort of sensors and systems to work with.

you could try 4 terminal sensing.

I have not used it myself, but the basic idea is to try to normalise for some of the external factors you mention.

As for the Arduino, the analog to digital converters have 10 bits of precision. This means you will get 1023 distinct values as the input voltage varies betwee 0 and Vmax (+5 or +3.3 depending upon the actual device). So that is fairly precise, usually you just use the value from the analog read - but you can convert to a value between 0 and 1 by dividing:

    int analogInt = analogRead(<your port here- e.g. A0>);
    double analogFloat = analogInt / 1023.0

Which begs the question, did you try using a 2 wire system? Assuming just 1000 data points, and a finger being, say, 5cm in length; that's roughly 1 point per .05 mm. I know it won't work out exactly like that, but that is my point - it is likely to be a rough estimate anyway due to the size of a finger at the touch point.


Change one specific byte of an IP address So if I have an IP address IP Address: 192.64.5.1, is it somehow possible to change a specific byte of that IP to like IP Address: 192.64.**6**.1

My idea is to change the IP Address into variables IP Address: a.b.c.d
Now I could say a= 192; b= 64; c= 5 + 1; d= 1

But what if I receive the IP Address: 192.64.5.1 as a String. Is it somehow possible to split it up into 4 parts that I can each individually assign to an integer (a, b, c or d)?

You can do it all with the IPAddress class.

For instance: create an IP address from a string:

IPAddress myAddr(myString);

Create a new IP address with one byte changed:

IPAddress myNewAddr(myAddr[0], myAddr[1], myAddr[2] + 1, myAddr[3]);


Comparing a String after reading it from Serial fails I have bought an Arduino starter kit online, everything seem to work but when I try for example to use ifs (and other conditional statements), the LEDs do not turn on. Here is a code for a little project I am currently working on:
int redpin = 3;
int greenpin = 2;
int bluepin = 4;
String color;
String msg = "Insert color: ";

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(msg);
  while (Serial.available() == 0) {}
  color = Serial.readString();

  if (color == "red") {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "green") {
    digitalWrite(greenpin, HIGH);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "blue") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, HIGH);
  }

  if (color == "off") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
}

I tried turning on the RGB LED with single digitalWrite() functions and it works. I think that the if statements in the code are the problem.
I`m using an Arduino MEGA 2560 BTW.

After color = Serial.readString(); color also contains a newline character.
You can remove that by adding the line color.trim();, or even better, avoid the newline altogether by using Serial.readStringUntil('\n'); which discards the terminating newline character.
Also, you could, and maybe should, avoid using the String class and use:
char color[10]; // char array as buffer for reading from Serial

int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end

if (strcmp(color, "red") == 0) //Use strcmp(), not ==

respectively.


Upload code on Arduino Leonardo using command line I'm trying to upload a compiled .hex file on an Arduino Leonardo, using the terminal. Uploading a sample code using the Arduino IDE works well, and from the Arduino IDE I got the upload command

avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

But executing it I got the following error

Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: Recv: . [15]

avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

What's wrong?

After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write .hex into flash.

In Arduino core CDC.cpp we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.

https://github.com/vanbwodonk/leonardoUploader

Only use this simple command:

leonardoUploader /dev/ttyACM0 Blink.ino.hex

I hope it helps other people searching for this.


Can I use this cheap GPS module with arduino For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.

Here is the link--
http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8

Yes.  You can tell that from two entries in the specification:

  TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

  Output SiRF binary system OR nmea0183 V3.0(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.


Arduino compatible's serial port not showing Mac OSX I bought an Arduino-compatible Freaduino board atmega8 (I selected the board type as Arduino ng or older atmega8). I installed the Arduino IDE on Mac OS X and the FTDI drivers. But my serial port looks like this when I connect the board:

And when I try to upload the program, this is the error I get:

Can someone tell me what is the mistake? I am clueless.

UPDATE: the problem was I had not installed the driver properly (I guess). I uninstalled and reinstalled them and it worked perfectly. Also made a YouTube tutorial regarding the same. http://youtu.be/BwatajQO_88

From the OSX System Report we learn that your board is based on an SiLabs CP2102 converter (or workalike), but according to your question you installed the drivers for an entirely different product from FTDI

(Arduino.cc has used FTDI in the past and CDC/ACM today, I don't believe they have ever used SiLabs so their instructions probably don't cover that, but other vendors obviously have)

Install the CP2102 drivers and it should work if you use the /dev/tty.XX device which then appears when you plug in the board.

SiLabs appears to provide the drivers at

http://www.silabs.com/products/mcu/pages/usbtouartbridgevcpdrivers.aspx

Just for sake of completeness, there are at least 5 distinct protocols/chips in use for serial-like USB communication with embedded devices:

FTDI
CDC/ACM Virtual Com Port
SiLabs CP210x
Prolific PL-2303
ch340

(Additional possibilities could include actual RS232 serial or serial-over-bluetooth)


How do I configure the Arduino IDE to look for source code in a subdirectory within the directory that holds my sketch? I'm writing an Arduino program that contains various .h and .cpp files. Due to organizational needs, I have configured the directory that contains my Arduino sketch (.ino) to possess a subdirectory. This subdirectory contains related source code.

An example layout of my project directory is located below:

mysketch
    mysketch.ino
    mycode.h
    mycode.cpp
    mylibs
        mylib1.h
        mylib1.cpp
        mylib2.h
        mylib2.cpp
        mylib3.h
        mylib3.cpp

With this, I'm able to successfully #include the header files. However, the compiler then complains that mylib1.cpp, mylib2.cpp, and mylib3.cpp are not defined (however they are). I'm guessing that the Arduino only looks for source files within the same directory that the sketch lives in. Thus subdirectories contains source code are ignored.

I can then modify my directory layout such that all of the 'mylib.h/.cpp's' are in the same directory and the project compiles fine.

So my question: how do I configure the Arduino IDE to reference source code within a subdirectory? Also, I would prefer that the mylibs exist within the same directory, and not within the Arduino 'library' directory. This will allow me to then easily distribute the code as a single zipped folder.

The behavior of the Arduino IDE with this sort of thing has changed over time so it depends on which version of the Arduino IDE you're using. With recent versions you can put the files in a src subfolder of your sketch folder and then do:

#include "src/mylib1.h"

or:

#include "src/mylib1/mylib1.h"

depending on how you want to organize the folder structure.

When doing this you may find that Arduino libraries often use incorrect include syntax in their source code. For example in mylib1.cpp:

#include <mylib1.h>

although wrong, would still work if the library was located in one of the Arduino libraries folders but with the library located in the sketch folder this no longer works and you need to change it to:

#include "mylib1.h"


ATTiny84 blink mystery Novice mode, please.

I programmed my ATTiny84 using Arduino Ethernet (Arduino IDE 1.6.7) using https://github.com/damellis/attiny branch - 1 MHz internal oscillator mode. I uploaded ISP sketch to Arduino with all cables disconnected (first I did it with all of them connected but Arduino didn't seem to mind), connected the whole setup using 10 uF capacitor and the sketch got sent into ATTiny84 without problems.

Blink sketch is using atttiny84's digital pin 7 (that is physical leg No. 6) set to 1 s blink rate.

But, when I connect an yellow LED, it won't blink. I'm not yet good enough with my oscilloscope (don't know how to hook it up) but my multimeter is showing something weird - voltage is slowly rising on DP7 (I measured against ground) - over approx. 5-6 seconds to 400 mV, then immediately jumps to 1V (not sure about this, could be measurement bug) and then right to 0V.

Blink sketch:

int led = 7;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

I'm clueless. Please confer.
Thank you.

Images of my setup:

I solved my own problem. Wiring was completely OK, so was flashing.

The problem was RESET pin (4th physical pin). As soon as I disconnected it after flashing, LED started blinking. If someone knows why, I'd appreciate some info.


Arduino Serial Monitor only returning Null Characters I'm trying to simply access my HC_05 bluetooth module and conduct some AT commands through the Serial Monitor. For some reason though, it only seems to be returning Null characters, though it does some to be actually responding to the command in some way (given by the length of Null characters it returns.

So you can clearly see that the command AT and AT+NAMEdevice return different data, but they are both all NUL blocks. I am viewing the monitor in text. Changing the view to Hex or ASCII does not change results.

Code for this simple program is below:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Wire Diagram is as here
NOTE I have used both a direct connection to the 5V and also used a Voltage Divider. Neither changes the NUL return.

First, change all Serial.write to Serial.print I think that might be half your problem.

Next,

  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);

The way you are doing this will probably put the HC-05 into 9600 baud mode. You can fix this one of two ways:

Change BTSerial.begin(38400); to BTSerial.begin(9600);

Or, as jfpoilpret suggested, tie the Key pin directly to VCC.  The reason is that in order to go into 38400 baud mode, there must be voltage on Key at the time the module is powered up.  By the time the digital write in your code happens, it's too late.

If for some reason you'd like to have digital control over the Key pin rather than directly wiring it to VCC, yet you'd like the module to operate at 38400 baud, you can simply change the default baud rate by issuing the appropriate AT command - I believe it's AT+UART= off the top of my head.

Also, I'm not sure, but jfpoilpret might be right as well about how your serial read/write handling is done within loop() but here is code that I know works:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX
char myChar;

void setup()
{
  ...
}

void loop() {
  while (BTSerial.available()) {
    myChar = BTSerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    BTSerial.print(myChar);
  }
}