After burning bootloader, Windows 10 doesn't recognize the USB device I just built my own version of an Arduino Micro, using the ATMEGA32u4 chip. I burned the bootloader to it via another Arduino (Arduino Nano from banggood.com).

The Arduino Nano uses an ATMEGA328 chip, so it should work as an ISP programmer. None the less, I hooked up the Nano to my custom board, according to Sparkfun's Guide, and proceeded to burn the bootloader. The Arduino IDE says that I have successfully burned the bootloader.

However, when I plug in the newly burned custom board, Windows 10 throws the error, saying, USB Device Not Recognized followed by The last USB device you connected to this computer malfunctioned and Windows does not recognize it.

I have searched for a solution, but none seem to come up. My question is, what do I need to do in order to get this custom board working as an Arduino? Thanks!

You need a number of things to be true before the (new) bootloader will work:

The hardware needs to be wired correctly
You have used an appropriate crystal as the clock
You have installed the correct bootloader (ie. one for the Atmega32U4)
The fuses are set to boot into the bootloader
The fuses are set for the correct bootloader size
The fuses are set correctly for the clock type and the clock speed (for example, don't have the "divide clock by 8" bit set)

I have a sketch that analyses your chip signature and fuses which will also report on what bootloader it detected (assuming it is one from a recognized list). You could run that and amend your question to post the resulting display from the serial monitor.

I also have a sketch that programs a bootloader for various chips including the Atmega32U4. This sketch also sets the appropriate fuses.


Serial Communication between ESP8266 and Arduino Uno I want to send data from arduino to ESP8266. I have done all the RX and TX connections.
The problem is that data is not sent every second, it stops after a single byte. When I remove the arduino cable then data is read.

My Arduino Code :

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

void loop() {

    Serial.write("50");
    delay(1000);
}

My ESP8266 Code :

void setup() {

Serial.begin(9600);

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
  }
  Serial.println("Connected !");

}

void loop() {

 Serial.print(Serial.readString());

}

Since you are  Arduino Uno, it has only one Serial. This Serial can be used to transmit data in USART mode to another Serial Device as well as see any Debug data in the Serial terminal.

However, both the functionality can not be used simultaneously. The Tx Rx pair of Arduino can be connected to one pair of other device i.e. either to the computer via the cable or to the Tx Rx of ESP8266.

But if you really need to plug in the Uno to the computer and send data to ESP8266 simultaneously, then you have to use SoftwareSerial library to convert any digital pin to Tx Rx pin, and connect them to ESP8266 for transmitting data.


Button Matrix Code and Wiring Bear with me here, I'm new to arduinos, so what I'm saying might only make sense in my own mind.

I'm trying a button matrix and I not completely sure on my wiring and I have a few questions.

Is the diagram correct?
I wire D2 to D3 and set them to output and input respectively. In the code I digital write to D2 a HIGH, will D3 then read high?
What is the best way to read the state of each button? Is there a Library that can simplify it?

I'm sorry if this is all just confused gibberish.

EDIT: I got the idea from this video, which explains some of it, but no code. He however uses an arduino micro.

EDIT #2: I realized I wired the buttons incorrectly.

@Jot commented to use the Keypad Library. Which I got to work using the tutorial. Took a few minutes to set up.


How can I get my Attiny85 interupt to trigger I have an ATTiny85 set up to detect a magnet passing over a hall sensor. Every 2 detection's I want it to light up an LED.

I decided to do the code using the arduino IDE and the code is as follows:

const int hallPin = 2;     // the number of the hall effect pin
const int ledPin =  1;      // the number of the LED pin

// variables will change:
volatile int hallState = 0;         // variable for storing the hall counter

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  digitalWrite(hallPin, HIGH);

  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

void loop()
{
  if(hallState>1)
  {
      digitalWrite(ledPin,HIGH);
      delay(2000);
      digitalWrite(ledPin,LOW);
      delay(2000);
      hallState=0;
  }
}

void pin_ISR()
{
    hallState++;
}

I've dry run this a bunch of times and cant see anything wrong with it. I use the digitalWrite on the hall pin to enable the internal pullup. But the circuit just doesnt work.

Here is the circuit:

I connected a multi meter to the hall effect sensor on its own just to check if it was working. I added an external pull up using a 10k resistor and it worked as expected 5v when no magnet present and almost 0 volts when a magnet is brought in range.

So my guess is my interrupt routine isnt working in my code, what could I be doing wrong? I've read in the documentation that pin 0 is the correct interrupt pin on the attiny85

Edit: Adding Schematic

You main problem is that you have wired up your MCU wrong.

Pin 5 (PB0) is not the external interrupt pin. Pin 7 (PB2) is the external interrupt 0 (INT0) pin.

As a result your code will not do anything when the hall sensor changes because it is not looking at it.

I would suggest not trying to use the attachInterrupt() abstraction. Instead I would simply enable the external interrupt directly:

GIMSK |= _BV(INT0);

And use a proper ISR handler:

ISR(INT0_vect) {
    //Your ISR code here.
}


Sense person connected to TENS unit So let's say I use a store-bought TENS unit for liability. I want to make a challenge where you need to hold on to the TENS unit for 10 seconds before it activates a solenoid. How can I have an Arduino detect if someone is touching some metal posts connected to the unit? Would I need to measure the current for the tens unit or something? Any ideas/suggestions? Thanks!
Edit- Not sure if this should be in Arduino or Electrical Engineering, feel free to move it.

I think the main problem here is that you want to measure in the presence of high voltage from the TENS. Not having experience with TENS circuits, I would suppose that their contact pins are connected to the high voltage source through resistors to limit the current. (Or some equivalent current-limiting scheme.)  If so, the voltage between the contacts should drop when there is a person connected. You should be able to detect that drop with the Arduino.  The "obvious" approach would be to use voltage dividers to reduce the no-load voltage to less than 5V so the Arduino ADCs can handle it. You'd need high-value resistors in the dividers so they don't load the TENS... maybe 1 Megohm or more for each divider.  One problem with this simplistic approach is that the TENS is putting out its stimulus using brief pulses, which may be too quick to catch with the ADCs.  To get around that, you'd feed the output of each divider through a diode to an R-C filter.  (Note that you need the diode anyway, since the TENS output is probably AC and the Arduino ADCS only want DC.)  This may take a fair amount of experimentation to get the values right, which you should do without the Arduino... just a DVM or scope that you can start at a high-voltage range until you sure you have everything worked out to 0-5V.


Using 3.3V XBee with Arduino Pro Mini 5V Version The Xbee requires a 3.3V power input and the Arduino Pro Mini (5V version) only provides a regulated 5V.

Question: What will be the simplest way to provide a 3.3V rail to the XBee from the Arduino Pro Mini?

If we use a voltage divider consisting of 2 resistors, the ratio should be 66/100, but how do we choose the resistor values?

If we choose a 3.3V voltage regulator, will the STMicroelectronics L78L33ACZ be suitable?

Between the voltage divider and voltage regulator, which is the preferred method? Is there a better alternative?

This is part of a Fritzing circuit I used to control the x'mas tree lights (the relays and sensors have been snipped out) with an XBee. This circuit uses a 3.3v LDO you may have to change the capacitor values depending on your regulator specs. I chose to use a separate 5V regulator (not shown) but it will work off the Pro Mini's +5V power rail.

There are two FETs that do the actual level shifting, the bonus transistor allows you to reset the Arduino and thus gives you the ability to program it over the air via the XBee (beyond the scope of the question, but if you want to go wireless, go wireless all the way - do the Google for wireless programming over XBee if needed). Note the 0.1uF across the XBee power pins, I recommend this capacitor be placed as close to the XBee as possible to minimize noise (I solder it across the back of the XBee interface board).


Setting Fuse Bits From Arduino IDE? I've come to understand fuse bits in the last few weeks. I'm working on a bitbanging project on an Arduino Pro Micro, and the signals I'm working with are around 30uS each. For this reason, I think I'll need to unset the CKDIV8 to unlock the full 16MHz speed of my micro controller.

Regardless, I can't figure out how to even do that. Is it possible to modify fuse bits through the Arduino IDE? If so, where?

The only other info I've found on this subject so far is that I can do it by chaining two micro controllers together, but at that point we're getting into application specific stuff and I'm nervous to play with the fuse bits by myself until after I've followed a step-by-step guide. I'd hate to, say, erase the bootloader.

The Arduinos are shipped without CKDIV8 enabled.

New chips without bootloader and the chips after chip erase are having CKDIV8 active.

And you can change the clock prescaller in software, but it mess up everything that depends on it. Delays, serial baud rate and USB as well.

However fuse setings are stored in boards.txt definition file. None of the bootloaders would work with default settings. They are usually compiled for 16MHz @5V and  8MHz @3.3V with xtal or resonator. But the custom boards may have much more options.


How to use setModemRegisters in RF24 The below picture is the introduction of setModemRegisters .

First: What is the mean of ModemConfig* config? I mean: how to write the parameter. Maybe just give a example, and it will be better if it's suitable for this SO question.
Second: What is the mean of data rate? It is the speed of SPI between the SI4463 and MCU or speed of two SI4463  ?
Third, What is the mean of bandwidths? I never saw it...

Thanks for any help .

ModemConfig * config is a pointer to a ModemConfig struct.

You need to create a ModemConfig struct, populate it then pass a pointer to it in the call to the setModemConfig() function.

Something like this:

// create the struct
ModemConfig mc = ModemConfig();

... //populate the struct values

// then call the function
setModemConfig(&mc);

The datarate is the rate at which you are sending information over the radio channel (not between the MCU and the Si4463).

The bandwidth is the range of frequencies used in the radio transmission (e.g. in FSK if a low/0 is 99.95MHz and a high/1 is 100.05Mhz then the bandwidth would be 100Khz)


Problem using ICSC (by majenkotech) in RS485 bus I want to communicate with an RS485 Bus consisting of 5 Arduino Pro Minis as slaves and one Arduino Mega 2560 as Master. I found a great library for this.

According to the documentation provided by the author of library I can use:

ICSC icsc(1, 9600, 7); //ID, BaudRate, DEpin

But I also have to define a Serial port for ICSC to work with:

ICSC icsc(1, 9600, Serial1);

I cannot mix these two sentences. I mean I cannot define both DEpin and Serial port for the ICSC in one sentence. But I need it to be defined. I don't want to use Serial for that, which I need for Serial Monitor. I want to use Serial1 for this. What can I do? I couldn't find any updated documentation about this.

UPDATE:

I found out how to define Serial port and DEpin for ICSC. The problem is I cannot get an answer!

Here is Master code:

#include <ICSC.h>
ICSC icsc(Serial1, 1, 7); //Stream, ID, DEpin

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  icsc.begin();
  icsc.registerCommand('R', &showTemperature);
}

void loop() {
  icsc.send(2, 'T', 0, NULL);
  icsc.process();
}

void showTemperature() {
  Serial.println("ACK");
}

And here is the Slave code:

#include <ICSC.h>
ICSC icsc(Serial, 2, 7); //Stream, ID, DEpin
String strAck = "ProMini2:ACK";

void setup() {
  Serial.begin(9600);
  icsc.begin();
  icsc.registerCommand('T', &sendTemperature);
}

void loop() {
  icsc.process();
}

void sendTemperature() {
  icsc.send(1, 'R', sizeof(strAck) + 1, (char*)&strAck);
}

Assume that there is just one slave and one master. I tried this code but got no answer. Where is the error?

The documentation for the constructors is out of date (I am re-writing as we speak, and is now here).

The constructors in the header file are like this:

ICSC(Stream *d, uint8_t station);
ICSC(Stream &d, uint8_t station);
ICSC(Stream *d, uint8_t station, int depin);
ICSC(Stream &d, uint8_t station, int depin);

That means you need to provide the serial object as the first entry:

ICSC icsc(Serial1, 'A', 5);

You need to manually start the serial object before ICSC.

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

This change was made to enable support for software serial and other Stream based devices.

Addendum for your update:

Don't spam the sending like you are. Send periodically, not constantly, or you will never be able to receive.
You cannot use String objects like that.
1 and 2 aren't good choices of station IDs. Yes, they work, but not great, since 1 is the SOH character.


Trying to Pulse an LED a number of times outside of the main loop I'm trying to call a class function that pulses an LED "x" number of times. I dont want to use a delay, which is making it tough. If I use a while loop, the LED just stays on. I attach an interrupt in the begin() - the location of the LED is pin 13

I call the following in my sketch like so:

robot.lights.pulse(0, 2000, 10000, 500); //in milliseconds

My goal is to pulse an LED "x" number of time at a rate I specify.

This is the code inside my class:

void StatusLights::begin(int locations[]){
    for(int i=0;i<NUM_OF_LIGHTS;i++){
        this->locations[i]=locations[i];
        pinMode(locations[i], OUTPUT);
    }

    ledState = LOW;
    previousMillis = 0;
    attachInterrupt(0, pulse_ISR, RISING);

};

void StatusLights::pulse(int location, int interval, int count, int speed){

    int value = 0;
    previousMillis = 0;
    // while(pulsecnt<count) {
        long currentMillis = millis();

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            value = 128+127*cos(2*PI/interval*(speed-currentMillis));
            analogWrite(locations[location], value);
        };
    // };
    // digitalWrite(locations[location], LOW);
};

void pulse_ISR() {
    pulsecnt++;
};

This is my first time using interrupts to do this - I'm really trying to avoid delays since i need other things to happen synchronously.

Thanks!

You'll want a class function that decides whether 'now' is time to toggle the LED or not, and returns quickly. Call that function frequently from your loop function. Your other class functions will set or clear the whether the LED is to toggled, and when, how many times, etc.  Something like the following pseudo-code, which is not a full solution but should point out the essential details:

void loop()
{
   myStatusLights.updateLED();     // call this frequently
}

...

void StatusLights::updateLED(){
  if LED_active,
     if it's time to change the LED,
        toggle LED on/off;
        if LED has toggled enough times,
           set LED_active false;
        endif;
     endif;
  endif;
}

Update:

  How would you refresh the count, track the pulses, and refresh the state of the status light without any parameters?

Some class-function must initiate the blinking, whether it knows to do it itself or it is called from your application code. That class-function will need to set those parameters. If it to be called from outside, perhaps the outside sets them - ? Only you know that. Either way, they will need to get saved in the class' private data so the .updateLED() function can have access to them. The .updateLED() function will, for instance, count down the remaining number blinks to display, keep track of whether the LED is on or off, actually turn it on or off, etc., until there is nothing left for it to do. In that case it just quickly returns without doing anything.


How can I pulse a stepper motor whilst also wanting to handle other tasks? A Polulo A4988 driver board listens for a LOW -> HIGH pulse on a digital pin to step a stepper motor.

A simple way to pulse this with a delay of say 100μs, is to use the delayMicroseconds function:

#define STEP_PIN  3
#define DELAY     100

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

void loop(){
    //heavy computation taking time
    digitalWrite(STEP_PIN, LOW);
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(DELAY);
}

Although this works, the issue is that all the time that the processor spends in the delayMicroseconds function is wasted. This means that if I wanted to, for example, handle inputs from a serial line, I would have no time to do this. In addition, the time for these computations to complete would result in the pulse time increasing which is not ideal as the speed of the stepper would no longer be uniform.

How can I efficiently pulse the stepper at the correct time, whilst leaving my self room to run other tasks between pulses?

P.s. This is for this project: https://github.com/joeiddon/chess_robot.

Instead of delaying between pulses, loop around the main loop() function as fast as possible constantly checking the time to see if we should pulse the motor.

This means that computations can occur in the loop (so long as they are reasonably fast).

To implement this, the micros() function can be used to get an unsigned long representing the microseconds that have passed since the start of the program.

Then in each loop cycle, we need to check if the difference between the current time and the last time that we pulsed is >= the pulse delay. In which case, we send a pulse to the motor

However, instead of setting the last pulse time variable to the current time, we instead increment the last pulse variable by the delay time. This has the affect that even if we were slightly late in pulsing, we pretend that we did in fact pulse at the right time so that they do not drift over time.

This would look something like:

#define STEP_PIN  3
#define DELAY     100

uint32_t last_pulse;

void setup(){
    pinMode(STEP_PIN, OUTPUT);
    last_pulse = micros();
}

void loop(){
    //heavy computation taking time
    if (micros() - last_pulse >= DELAY){
        last_pulse += DELAY;
        digitalWrite(STEP_PIN, LOW);
        digitalWrite(STEP_PIN, HIGH);
    }
}

Note that there is a slight subtlety here in that the result from micros() and therefore the value of last_pulse will overflow after ~70 minutes. However, because we are taking a difference of two unsigned numbers, this method will still work, so long as micros() is never a whole cycle ahead of last_pulse which in practice will never be the case.


Controlling bigger motors with an arduino board i am german and my english is not the best, anyway i hope you will understand my problem.
At the moment i construct a little car with some friends. We have still completed the frame and now we think about controlling it in a electronic way. For example with a controller of a playstation or with our smartphones, however, it should be electronic, so i think about to do this with an arduino board.

We have two motors. One for the direction and the other one for the movement.
The first has about 8 ampere and about 12 volt, the other has 800 watt, so around 40 ampere and 24 volt.

My question is, whether it is possible and if so how to control them (or one them) with an arduino board and what do i need in addition?

It would be great if you could help us :)

DC motors are typically driven with some sort of BJT/MOSFET solution that will be able to sink enough current to drive the motor because a microcontroller pin can only usually provide a few mA of power.  See this link for info on basic microcontroller DC motor control.  If slow response is acceptable and only one level of power is required (i.e. no PWM) even power relays could be used to turn on off the motor.  Some applications could use this.  However, for your application, it sounds like you will want more responsive control over the motor and need a particularly high power MOSFET to properly drive your application as your motor is very high power.  Such FETS such as these could be used to properly control such a motor using the microcontroller.  Do note additional protection circuitry will be necessary and is probably the topic of another feed, but this would be a place to start if you wanted to build it from scratch.  Otherwise go with an over the shelf driver board which will probably have something like the link above used on it.


Dereferencing char into a struct I am sending some data over an NRF24 link, using the RF24Network  library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as

struct payload_t {                  // Structure of our payload
   unsigned long data;
   unsigned long datatype;
   char sensorid[20];
   unsigned long counter;
};

As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.

At the moment I am using sensors without an internal ID, so in loop(), I am calling:

 writeToNetwork(voltage,'v',"nosid",packets_sent++);

My writeToNetwork function is defined as

 bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){

and within that, I am setting up the payload with

 payload_t payload = { data,type,sid, package };

Which gives me an

 error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]

Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the sid - pointer to get my array into the struct. How can I do that?

Or am I barking up the wrong tree? I tried to transfer the id as a string:

#include <string.h>
bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
char sidchar[20];
sid.toCharArray(sidchar,20);
payload_t payload = { data,type,sidchar, package };

Which gives me the error

array must be initialized with a brace-enclosed initializer

Which I do not understand. Doing

char sidchar[20]={0};

gives me the same error.

In your situation, your best bet is probably to use the standard C function strcpy:

payload_t payload;
char* source = "abcdef";
strcpy(payload.sensorid, source);

Note that source string does not have to be declared as char source[20] and can be declared as the rather standard C string char*.

Also, since you are limiting the size of the string to be passed in payload, you may prefer to use strncpy which will ensure no more than 20 characters get copied:

payload_t payload;
char* source = "abcdef";
strncpy(payload.sensorid, source, 20);
// Explicitly add a string termination to the end of string
payload.sensorid[19] = 0;

In the snippet above, please notice the last line, it is necessary in the situation where source string length is 20 or more non-null characters, as in this case, strncpy will copy all 20 characters but will not add the terminating 0 at the end of the string.


Upload s sketch to a 5v Pro-Micro board as 3.3V by mistake I have 2 types of Pro-Micro(as shown here), both 5v, micro-usb, which worked as expected, until, accidentally were flashed as 3.3v using the Arduino IDE.
At first I thought that the fact it stoped working right after, has nothing to do with that error, but since again, did the same mistake, I understand that this is no coincidence.
After doing so, boards seemed to be powered on ( leds are ON ), but are not found under port in the Arduino IDE.
Are they really can be destroyed by such an error ?

Holding RST and GND pins after re-connecting USB, showed it on port menu.
needed another such holding, prior to upload.
All good now.


what is causing my esp8266 setup function to reinitialise? Here is code I have written:

#include <stdio.h>
#include <ESP8266WebServer.h>

#define MAX_WIFI_INIT_RETRY 50
#define WIFI_RETRY_DELAY 500

const char* wifi_ssid = "ssid";
const char* wifi_passwd = "password";

ESP8266WebServer http_rest_server(80);

const int numParams = 20;
String params [numParams];

String toString(String my_array[], int size)
{
  String string;
  for (int i = 0; i < size; i++) {
    string = string + ", " + my_array[i];
  }
  return string;
}

int init_wifi() {
  int retries = 0;
  Serial.println("Connecting to WiFi AP..........");
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_passwd);
  // check the status of WiFi connection to be WL_CONNECTED
  while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
    retries++;
    delay(WIFI_RETRY_DELAY);
    Serial.print("#");
  }
  return WiFi.status(); // return the WiFi connection status
}

void readParams(String (& params) [numParams])
{
  int mn = WiFi.scanNetworks();
  for (int i = 0; i < mn; i++)
  {
    //    Serial.println(WiFi.SSID(i).c_str()); // prints name of all hotspots in serial monitor.
    params [i] = WiFi.SSID(i).c_str();
  }
}

void listHotspots() {
  String results = toString(params, sizeof(params));
  Serial.println(results);
  http_rest_server.send(200, "text/plain", results);
}

void config_rest_server_routing() {
  http_rest_server.on("/", HTTP_GET, []() {
    http_rest_server.send(200, "text/html",
                          "Welcome to the ESP8266 REST Web Server");
  });
  http_rest_server.on("/hotspots", HTTP_GET, listHotspots);
}

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

  init_led_resource();

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  readParams (params);

  if (init_wifi() == WL_CONNECTED) {
    Serial.print("Connetted to ");
    Serial.print(wifi_ssid);
    Serial.print("--- IP: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.print("Error connecting to: ");
    Serial.println(wifi_ssid);
  }

  config_rest_server_routing();

  http_rest_server.begin();
  Serial.println("HTTP REST Server Started");
}

void loop(void) {
  http_rest_server.handleClient();
}

when I access the root url: i.e. 192.168.0.101/ It opens the root page fine, but when I try to open the 192.168.0.101/hotspots It reboots the ESP8266  until the page stops to make a new attempts and I get nothing in result.

In the serial monitor I am seeing this exception when I try to visit the ip/hotspot page .

Exception (9):
epc1=0x4020148a epc2=0x00000000 epc3=0x00000000 excvaddr=0x4d2d5456 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffde0 end: 3fffffc0 offset: 01a0
3fffff80:  3fffdad0 3ffee553 3ffee5a4 40201347
3fffff90:  402086b8 6505a8c0 feefeffe feefeffe
3fffffa0:  3fffdad0 00000000 3ffee5e0 40206614
3fffffb0:  feefeffe feefeffe 3ffe8510 40100479
<<<stack<<<

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

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
Connecting to WiFi AP..........
######Connetted to Hometelecom1N5E--- IP: 192.168.0.101
HTTP REST Server Started

is it something wrong with the toString function ?

When a program crashes, you can debug the crash based on the Fatal exception number.

 Exception (9)  Unaligned read/write operation addresses
     1. Unaligned read/write Cache addresses
     2. Wild pointers

This leads than as Juraj points out to a WD reset:

 rst:4     Hardware WDT reset

To get the exact part of the code paste the >>>stack>>> into the window of the espExeption decoder in the ArduinoIDE. Details how to install and use.

My educated guess is that the heavy use of String class in combination with lot of String operations with the getHotspot function leads to heap corruption and crashes the Esp8266. Try defining fixed char arrays and get rid of the String class to get a stable running system. Post the espExeption decoder result as edit to your question if you thing something else might be fishy


Stopping a countdown timer when it hits 0 I am trying to modify the following sketch to count down (which seems to be partially working).  What do I need to modify, to get the timer to stop at zero? Right now it counts down from 10 seconds, goes past zero and into the negatives.  I really struggle with coding, I've tried studying other peoples sketches, researching on-line, purchased (and studied) a couple Simon Monks books, but I'm still unable to work through this.  Can someone please point me in the right direction?

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define WAITING 0 // waiting to start
#define TIMERONE 1 // timer one running
#define FINISHED 3 // timer complete
#define countdown 10
const int resetPin = 6;
const int buttonPin = 7;
const int ledPin =  13;      // the number of the LED pin

long startTime = 0;
long timeOne = 0;
int timer = WAITING; // timer state. Initially waiting for first button press
int reset = 0;  // reset button state
int button = 0; // main button state

void setup()   {

  pinMode(buttonPin, INPUT); //init button pin to input
  pinMode(resetPin, INPUT);  //init reset pin to input
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3c
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(55, 00);
  printDigits(0);
}

void loop() {
  //-------- main loop -------
  switch (timer) {
    case WAITING: // initial state - waiting for first button press.
      display.clearDisplay();
      display.setCursor(55, 00);
      printDigits(0);
      display.display(); // display screen showing 00:00
      button = digitalRead(buttonPin);
      if (button) { // button is pressed.
        timer = TIMERONE;
        startTime = millis();//read the time the button is pressed.
        while (digitalRead(buttonPin)) {
          //--- wait for button to be released.
        }
      }
      break;
    case TIMERONE:
      timeOne = millis();
      button = digitalRead(buttonPin);
      reset = digitalRead(resetPin);
      display.clearDisplay();
      display.setCursor(55, 00);
      printDigits (timeOne - startTime);
      display.display();
      //-----------------------------------
      if (reset) { //reset button was pressed. Clear screeen and start again
        timer = WAITING;
        while (digitalRead(resetPin)) {
          //--- wait for reset button to be released.
        }
      }
      if (button) { // button was pressed
        timer = FINISHED;
        while (digitalRead(buttonPin)) {
          //--- wait for button to be released.
        }
      }
      break;
    case FINISHED:
      reset = digitalRead(resetPin);
      if (reset) { //reset button was pressed. Clear screeen and start again
        display.clearDisplay();
        display.setCursor(55, 0);
        printDigits(0);
        display.display();
        timer = WAITING;
        while (digitalRead(resetPin)) {
        }
      }
      break;
  }
}

void printDigits(long timeInMillis) {
  int seconds;
  int hundredths;

  seconds = countdown - timeInMillis / 1000;
  hundredths = (timeInMillis % 1000) / 10;

  if (seconds < 10) { // print leading zero if necessary
    display.print("0");
  }
  display.print(seconds);
  display.print(":");
  if (hundredths < 10) { //print leading zero if necessary
    display.print("0");

  }
  display.print(hundredths);

}

In this line you are calculating the time you are going to display.   You could use that same calculation in an if statement to put you into the FINISHED state in your state machine.

printDigits (timeOne - startTime);
if(timeOne - startTime >= someInterval) {
    timer = FINISHED;
}

where someInterval is the number of milliseconds you want the timer to run for.


Arduino 433Mhz weather sensor receiver I want to monitor the temperatur around the house and outside. I want to save the data to mysql and then create some kind of webapplication that displlays the data. It is pretty easy to find temperature sensors that transmitts over 433Mhz, and I have thought about Telldus tellstick to receive data and store them. This receiver costs about 30 - 40 $ and 10 - 20 $ for each sensor.

But since I just learned that Arduino can be used for everything, I would love to hear more about it.

Can someone please give me an introduction to what I would need to make this solution? The arduino should basicly receive data from 433 Mhz sensors and store it to MySQL.

What woulds be the challanges when doing something like this?

You could use an Arduino with an ethernet shield to store the data to a MySQL server on the local network. See this blog post for an introduction to a library.

The tellstick is designed to be plugged into a USB host, so it doesn't make much sense in combination with an Arduino. You can get a USB host module but it's an expensive solution and you are using way more hardware than necessary.

Instead you could get 433 MHz receivers dirt cheap on ebay, but I'm afraid they only work on one channel, and there are a bunch of channels in the 433 MHz spectrum. So they might not work with the sensors you are talking about.

Another option would be to use eg. Arduino Pro Mini's in combination with a 433 MHz transmitter, powered by a battery. You could get the temperature reading from the internal sensor, or use an external one. The internal sensor takes quite a bit of calibration work to give a precise reading though.
You can get Pro Mini clones on ebay for a few dollars. You would have to dive into sleep modes and such, if you don't want't the batteries eaten away in a short time. To program it, you'll need an FTDI cable, or another Arduino programmed as an ArduinoISP (In System Programmer).
As an alternative to the Pro Mini board you could use a plain AVR chip, but it will be more work.


Arduino as a real device to computer Suppose we have a computer mouse , now when we connect it to a computer then  computer understands it is a mouse which is been connected to it. Same thing happens for keyboard and many other devices. As per my understanding, the mouse has a microcontroller and a TTL serial converter which is programmed a certain way that enable computer's default mouse driver to understand the instructions coming from the connected device.

Let me to talk about one of my projects where I build a device driver for my own device. Like arduino send serial instructions to a port say COM3 and the driver which is a java program reads those instructions and performs accordingly.

As we all know that the arduino library provides support for Mouse and keyboard which works fine. Mouse operations are performed without a custom driver.

Now what I want is when arduino connects to a computer it gets detected as a Joystick or as a pendrive or something like that.

I go through different header files of mouse and keyboard which are present in arduino library but those are very complex and without proper documentation hard to understand.

Can you tell me where I could find study materiel regarding the existing library? Arduino website provides documentations only on different methods not on how it works.

Or if I think of building my own library then how I should start?

One more thing where I can find the information regarding the protocols that a conventional device like mouse, keyboard, pendrive, CD-ROM follows during communication (like the code or the algorithm that is burn into the microcontroller of the device) ?

I know it is a out of the box question but still if you help me, I will be grateful to you.

As per my understanding, the mouse has a microcontroller and a TTL serial converter which is programmed a certain way that enable computer's default mouse driver to understand the instructions coming from the connected device.

No, the mouse's microcontroller is a USB device.

  Like arduino send serial instructions to a port say COM3 and the driver which is a java program reads those instructions and performs accordingly.

No, that is the application you are talking about. The driver is what you install in Windows to make COM3 appear (that is, in any version of Windows before windows 10. Every other operating system, and Windows 10, has the driver built in already).

  Now what I want is when arduino connects to a computer it gets detected as a Joystick or as a pendrive or something like that.

There is no support for that in the Arduino API.

  I go through different header files of mouse and keyboard which are present in arduino library but those are very complex and without proper documentation hard to understand.

Even with proper documentation and understanding of how USB works it's hard to understand.

  Can you tell me where I could find study materiel regarding the existing library? Arduino website provides documentations only on different methods not on how it works.

  Or if I think of building my own library then how I should start?

Don't. Trying to do what you want without an in-depth understanding of how USB works is nigh on impossible.  I understand how USB works and struggle with writing USB driver code for microcontrollers.

Instead invest in a device that already does what you want (such as a Teensy 3.x), or move away from Arduino and use a professional environment with professional tools and examples to work with.

  One more thing where I can find the information regarding the protocols that a conventional device like mouse, keyboard, pendrive, CD-ROM follows during communication (like the code or the algorithm that is burn into the microcontroller of the device) ?

From the USB Implementer's Forum Inc.

http://www.usb.org/developers/docs/devclass_docs/

  Mouse or pendrive have a special type of microcontroller which are capable of direct communication to pc ? if so then is their any programmable microcontroller in market?

Yes, and there are plenty. Any of the Arduino boards based around the ATMega32U4 (such as the Leonardo) are that kind of microcontroller. The "serial" interface chip on the Uno is that kind of microcontroller (it is capable of being reprogrammed so it looks like a completely different device, and if you google around you will find people that have done it).

  What is the difference between actual driver and my java program which reads COM port?

The driver is what makes the COM port. Your program is what uses the COM port.

[USB device]---->[USB)- Driver -(COM3]<-----[Your program]


Converting an int to an unsigned char for display on a Nokia 5110 I've been working on a small project getting some images displayed in a Nokia 5110 screen via an Arduino. I've been getting it working, but one of the issues I have is that I would like to have a list on integers and convert that an unsigned char array that the display requires. Generally I have something like this which works out of the box.
unsigned char src [] PROGMEM = {0x00, 0x00}

Surprisingly, I found that this also works
unsigned char src [] PROGMEM = {255, 255}

But when I have a list like this
int src [] = {255,255}

and try to convert it to an unsigned char array, things don't display correctly
unsigned char new_src[2];

for (int i=0; i<2; i++){
    new_src[i] = (unsigned char) src[i];
}

When I try to display this, it's clearly broken. I thought simply casting the int to an unsigned char would be enough (it doesn't work even if I don't cast it).
Here's how I display the array (for 84x48, the above arrays were just an example) :
Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);
display.drawBitmap(0, 0,  src, 2, 48, BLACK);
display.display();

On more note:
The end game is to have a file with a list of ints. I would then read that list of ints into an array and convert it into an unsigned char array and then display that.

The idea is that I would read a list of ints from a file ( I have
several files that I would iterate through) and convert that list to
the unsigned char array on each loop iteration.

The file could be a stream of bytes just as well as a stream of ints (or uints). If it were, no conversion would need to be done - just read a byte & store it, read a byte & store it, ....  If instead, it is a character representation of values, "37, 150, 8, ...", again, read the characters of one value, convert them to int8_t or  uint8_t and store them in your byte array. Look up the atoi() or sscanf() functions to do the conversion.


Operating HB100 backpack with Arduino Due I need to connect a speed sensor module with an Arduino Due and calculate the speed of an approaching object.

the sensor is:
http://www.limpkin.fr/index.php?post/2013/08/09/Making-the-electronics-for-a-%247-USD-doppler-motion-sensor

The sensor already output a signal that its' frequency represents the speed of the object.

I would really appreciate any help understating how can it be connected and operated by the Arduino without burning it, and how can I sample its output?

If more details are needed I'll be happy to supply.

Thanks.

The articles and tutorials I've read on the subject say that the HB100 module produces a very weak signal which needs to be amplified before your Arduino can read it. They recommend building an op amp. This post on the Arduino forums, for example: http://forum.arduino.cc/index.php?topic=61989.0

BUT looking at your picture and linked article, I find that your device already includes the signal amplification and filtering you need in the backpack board. I found the store page for this module, which has a more noob-friendly explanation. From what I gather:

VCC: provide the module with a 5v supply.
VOUT: analog reading of the amount of return signal being received. My guess is you could use this with analogRead() to get a rough estimate of the size or distance of the object being read. If you want only the speed reading, you don't need this pin.
FOUT: digital output of the speed that the sensor is reading. Thanks to @sachleen's link, you can use either pulseIn() or FreqCounter library to measure the frequency and then convert it to a MPH or KPH speed.
GND - ground, aka common, aka -.

So connect VCC to 5v, GND to ground, and FOUT to an input pin on your Arduino. If you use pulseIn(), frequency f = 1 / t, t being the return value from pulseIn(). If you use the FreqCounter library, it no doubt has documentation on its usage.


LED pin 13 not flashing properly This is my first program on Arduino Uno (the starter kit), although I do have prior experience with programming (JavaScript, coding class last year 7th grade). It blinks the internal led (pin 13) in a Morse Code message:

.... . .-.. .-.. ---   .-- --- .-. .-.. -..
. = dit();

- = dah();

(interval between parts of letter) = wip();

(interval between letters/words) = wah();

Here's my code:
/*
 * Roman's first program
 * Decipher the message!
*/

int ledPin = 13;
int index = 0;

void setup() {
  //initialize pins as outputs
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sequence[] = {1,0,1,0,1,0,1,3,1,3,1,0,2,0,1,0,1,3,1,0,2,0,1,0,1,3,2,0,2,0,2,3,3,3,1,0,2,0,2,3,2,0,2,0,2,3,1,0,2,0,1,3,1,0,2,0,1,0,1,3,2,0,1,0,1};
  int arrLength = sizeof(sequence)/sizeof(int); //however THIS works?!
  if (index < arrLength-1) { //0-based array
    index++;
  } else {
     index = 0; //restart the sequence once finished
  }
  if (sequence[index] == 0) {
    wip();
  } else if (sequence[index] == 1) {
    dit();
  } else if (sequence[index] == 2) {
    dah();
  } else if (sequence[index] == 3) { //because sometimes I the values are screwed past arrLength...
    wah();
  }
  //Serial.println(String(sequence[index])+" , "+String(index));
}

void dit () {
  digitalWrite(pinMode, HIGH);
  delay(300);
  digitalWrite(pinMode, LOW);
}

void dah () {
  digitalWrite(pinMode, HIGH);
  delay(900);
  digitalWrite(pinMode, LOW);
}

void wip () {
  delay(900);
}

void wah () {
  delay(2100);
}

Yet nothing is happening, except for the four/five startup flashes on the led when I restart it (red button). And yes, I saved and compiled.

Well, mainly digitalWrite(pinMode, HIGH); looks suspicious. I though you called LED pin as ledPin

If you fix this, it should be working. As this one is working too, it's just simplified a little:

int ledPin = 13;
int index = 0;
const int8_t sequence[] = {1,0,1,0,1,0,1,3,1,3,1,0,2,0,1,0,1,3,1,0,2,0,1,0,1,3,2,0,2,0,2,3,3,3,1,0,2,0,2,3,2,0,2,0,2,3,1,0,2,0,1,3,1,0,2,0,1,0,1,3,2,0,1,0,1};
int arrLength     = sizeof(sequence);

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(57600);
}

void loop() {
  Serial.println(String(sequence[index])+" , "+String(index));
  switch (sequence[index++]) {
    case 0: wip(); break;
    case 1: dit(); break;
    case 2: dah(); break;
    case 3: wah(); break;
  }
  if (index == arrLength) {
    index = 0;
  }
}

void dit () {
  digitalWrite(ledPin, HIGH);
  delay(300);
  digitalWrite(ledPin, LOW);
}

void dah () {
  digitalWrite(ledPin, HIGH);
  delay(900);
  digitalWrite(ledPin, LOW);
}

void wip () {
  delay(900);
}

void wah () {
  delay(2100);
}


Timer 2 interrupt with ATmega328p and make measurement in ISR I am working in my project and i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

I read in some article that using delay instruction is not as good as using timers'Interruptions so, I tried this code put it didn't work properly :

void setup(){

cli();

  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2  = 0;
  OCR2A = 99;
  TCCR2A |= (1 << WGM21);
  TCCR2B |= (1 << CS21);
  TIMSK2 |= (1 << OCIE2A);
sei();

Serial.begin(9600);
}
void loop()
{
Serial.print(digitalRead(1));
Serial.print(' ');
Serial.print(digitalRead(2));
Serial.print(' ');
Serial.print(digitalRead(3));
Serial.print(' ');
Serial.print(digitalRead(4));
Serial.print(' ');
Serial.print(digitalRead(5));
Serial.println(' ');

}

Well let's start from the start ...

Analog readings

  to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

Serial.print(digitalRead(1));

That is not reading analog pin A1, it is reading digital pin 1. If you want to read A1 you need:

Serial.print(analogRead(1));

Check the time

By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.

Example:

void setup()
{
  Serial.begin(115200);
}  // end of setup

unsigned long lastReading;
const unsigned long INTERVAL = 100;  // ms

void loop()
{

  // is time up?
  if (millis () - lastReading >= INTERVAL)
    {
    lastReading = millis ();  // when we took this reading
    Serial.print(analogRead(1));
    Serial.print(" ");
    Serial.print(analogRead(2));
    Serial.print(" ");
    Serial.print(analogRead(3));
    Serial.print(" ");
    Serial.print(analogRead(4));
    Serial.print(" ");
    Serial.print(analogRead(5));
    Serial.println();
    }  // end of if time up

  // do other things here

}  // end of loop

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

Using timers

If you really want to use timers (and I don't see what they achieve here) I have a page about timers that describes using them, and interrupts, in some depth.

The very least you would need is a timer 2 "compare A" interrupt like this:

ISR (TIMER2_COMPA_vect)
  {
  // Timer 2 has reached its comparison value
  }


ESP8266 NodeMCU first WS2812 LED lights up green I'm trying to power some WS2812 LEDs from my ESP8266 ESP-12E NodeMCU board (circuit here). I'm simply trying to use the NeoPixel Strandtest which works perfectly on my Arduino UNO with the same LED strip, but when I change the #define pin 6 to #define pin D4 (or 12 as GPIO) only the first LED lights up and it's green. I did throw in a 470 ohm resistor between data and DIN, but that didn't do anything different.

When I use one of the other pins, nothing seems to light up, even if I disconnect all pins and hit reset. Here is my wiring:

Don't mind the actual 3v -> 5v. It works fine with 3v. I have also tried powering it off externally. I have tried all other pins from D0 to D7 (I saw many people say "STAY AWAY FROM PIN D8"). Could my ESP8266 be dead on arrival?

So here comes my solution: I was playing around with NeoPixelBus by Makuna and the examples. I noticed in one of his examples, it said:

// You can also use one of these for Esp8266,
// each having their own restrictions
//
// These two are the same as above as the DMA method is the default
// NOTE: These will ignore the PIN and use GPI03 pin
//NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(PixelCount, PixelPin);

So I tried outcommenting that line and used that instead, and then it worked! I've always used Neo800KbpsMethod whenever I saw NeoPixelBus being used, because that was what other people did. Notice it also said:

These will ignore the PIN and use GPI03 pin

That pin is the RX pin on my board. No other example I have seen, has used the RX pin on the board.
After 6+ hours of constant troubleshooting, I can finally power on my strip and control each LED!


Powering Arduino and L293D with the same Power Supply I am relatively new to Arduino and plan to power an Arduino and an L293D Motor Driver with the same 9V power supply as in the diagram below.
I tried to simulate this with Tinkercad, but it seems like Tinkercad always powers the Arduino with an extra USB Cable, so I can't test it with only 1 power supply.
Would the 9V battery power both the Arduino and the L293D in this example?

I don't see any problem. You used the Vin for 9V, and shared grounds.
I suggest using a bypass capacitor (typically 0.1 uF) for the L293D VCC, but I don't have experience with using a L293D.
Also, you need to check if the battery can deliver enough current for both motors and the Arduino.


Check if servo is connected to arduino #include <Servo.h>

Servo esc;

void setup(void) {
  esc.attach(7, 1000, 2000);

  if (esc.attached()) {
    // this always runs
    // even if there's no servo connected to pin 7
  }
}

I've written code kind of like the above.

The problem is that after using Servo.attach the method Servo.attached always returns true, even if there's nothing in the pin that I've attached to.

How can I check if the pin, in this case 7, actually has a wire in it?

You cannot check, if a servo or a wire is physically connected to the pin, without extra effort. The Servo library uses Timer interrupts to create a PWM signal for the servo on the used pin. For this the pin is configured as OUTPUT and cannot measure anything except of the value, that was written to it. In most servo motors the PWM input is high impedance, so that the current draw from the PWM pin is very low.

To solve your problem you have 2 possibilities:

Use a special connector, that has 2 extra pins with a mechanical switch, which gets closed, when the connector is put together. (The same principle as in SD card holders)
Measure the current, that the servo uses through it's power supply pins, with a suitable circuit.


Analog Read dummy file Can we use just a analog Read without storing it
i hear it it a good practice to take two reads
for better accuracy
example:
// Read extra analog inputs
    for (int i = 0; i < 8; i++)
{
    // Read analog pin to nothing.
        analogRead(i]); // analog-read is not writing to anything
}

// Read the analog inputs
for (int i = 0; i < length; i++)
{
    // Write the state of the analog pin to the response buffer.
    slave.writeRegisterToBuffer(i, analogRead(analog_pins[address + i]));
}

how about this ?
// Read the analog inputs
for (int i = 0; i < length; i++)
{
    analogRead(analog_pins[address + i]); // for pre read

    // Write the state of the analog pin to the response buffer.
    slave.writeRegisterToBuffer(i, analogRead(analog_pins[address + i]));
}


ESP8266 OTA update with different flash size settings? I have an ESP8266 in a project.  It's specifically this ESP8266 SMT Module - ESP-12F item.  It's been working great with OTA, but I realized belatedly that I didn't change the flash settings when I started compiling through the Arduino IDE several versions ago.  I had been using the setting "1 MB (FS:64KB OTA:~470KB)", and I've updated OTA over multiple versions with the same basic structure of firmware and using the same server-side set-up.
I can no longer update with that setting because my compiled sketch is now over the OTA size limit.  My chip actually has 4 MB, however, so this limit is artificial.  I tried changing to "4 MB (FS:2 MB OTA:~1019KB)", and that works under the following test conditions:

I compile the "old" program with the 4-MB settings and I re-upload the old program via wired connection.
I compile the "new" program that's to come via OTA with those same 4-MB settings.

That's fine for a test, but I already have one of these chips "deployed" in a location where it's hard to access it.  I'd like to update that deployed chip OTA while also changing the flash partition.  I'm willing to lose any files stored outside of the program itself.  So I'd like instead to have:

A deployed, OTA-enabled chip with firmware running on the 1-MB partition structure noted above:
(Any intermediate step needed)
OTA update to new firmware that has been compiled with the 4-MB partition structure.

I'm willing to upload a dummy sketch at "Any intermediate step needed" to work around the current size of the sketch, but, after some experimentation, OTA seems to fail when the partition structure is different regardless of the size of the binary.
That's consistent with #2 in the answer here: esp8266 OTA issue, but that older question took a different direction with the OP and the #2 point there is stated without any detail.  I understand that in a broad sense, the prior answer covers my case, but I'm looking for more detail on the specific aspect of the flash partition settings.  Especially for these related questions:

Is there any work-around strategy available to change the flash partitioning between different versions served OTA?
If no, is the limitation determined by the software in the current OTA framework in the public libraries, or is it somehow fundamental to how the program is laid out in the hardware memory?

In theory at least, it seems like I ought to be able to force the new program to be written OTA at the same location that it would have been written had the old program also had the 4-MB partition. (Again noting that I'm willing to lose any other data in the flash to make this update work.)

The basic problem is that when you upload over OTA you don't upload the partition structure.
The ESP32's flash is split into a number of "partitions" or areas.  It might look something like:
+----+-+-------------+-------------+---------------------+
|BOOT|P|OTA Program 1|OTA Program 2| SPIFFS              |
+----+-+-------------+-------------+---------------------+

When you upload over UART you upload all that structure, and that structure can be changed.  When you upload over OTA you only upload one of "OTA Program 1" or "OTA Program 2". One of those is active and the other is inactive. You upload to the inactive one and then at the next reboot that becomes the active one. This allows the system to confirm that the program has been written correctly before running it to reduce the chances of bricking a device in the field.
Because of this you can never upload anything that doesn't fit into one of the OTA program partitions.
One risky option which you would have to do thorough local testing of first, is to write a program which, when executed, will change the partitioning. You would have to make sure that it runs in the lower OTA partition so that the inactive one is the one that gets both moved and expanded, which may take a little trial and error.
Once that has happened you should be able to upload a larger OTA program into the new, bigger, inactive OTA segment.
But that's only supposition and it's not something I have ever done or heard of anyone doing.


OTA push sketch to NodeMCU Similar questions regarding Arduinos mention the existence of tools that would enable the pushing of sketch updates to NodeMCU via WiFi / OTA (Over The Air).

Does this proceed?  If so, please indicate the proper tools.

Arduino IDE supports upload to a network port. Network ports are detected with mDns and made available in Tools>Port menu.

The ArduinoOTA library bundled with the esp8266 Arduino boards package supports upload from IDE with 'network port' over WiFi. See the example of the ArduinoOTA library available in Examples menu in IDE.


7 segment 4 digit not showing numbers 2,3 and 0 https://www.instructables.com/Using-a-4-digit-7-segment-display-with-arduino/
I used this link to make my circuit and I used this code also but some numbers like 2,3 and 0 doesn't display correctly.

It looks like you have the center segment and the top left vertical segment reversed. For the image you show, if you switched the on/off states of those 2 segments, you'd see 1230.
I don't know if the problem is in your code or in your wiring. The simplest fix would be to swap the pins for those 2 segments.


ESP8266: system_adc_read_fast() always give 1024 as output I need to use system_adc_read_fast (uint16 *adc_addr, uint16 adc_num, uint8 adc_clk_div) to get a sampling rate close to 100ksps. And I am able to achieve that using adc_clk_div = 32.

However, when I print out the values stored in adc_addr, I always get 1024. Why is this?

I have a NodeMCU v3. I have connected an electret microphone to it. +ve terminal is connected to 3.3V through 10k; GND is connected to GND. +ve terminal is connected to A0 on NodeMCU.

simulate this circuit – Schematic created using CircuitLab

It works fine when I use system_adc_read() (except the sampling rate is then 10ksps which is not desirable).

Sketch

// Expose Espressif SDK functionality - wrapped in ifdef so that it still
// compiles on other platforms
#ifdef ESP8266
    extern "C" {
        #include "user_interface.h"
    }
#endif

ADC_MODE(ADC_TOUT);

#define num_samples 512
uint16_t adc_addr[num_samples]; // point to the address of ADC continuously fast sampling output
uint16_t adc_num = num_samples; // sampling number of ADC continuously fast sampling, range [1, 65535]
uint8_t adc_clk_div = 32; // ADC working clock = 80M/adc_clk_div, range [8, 32], the recommended value is 8

int i = 0;
unsigned long start = 0;
unsigned long total = 0;
unsigned long tim = 0;

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

void loop() {
    // put your main code here, to run repeatedly:
    #ifdef ESP8266
        // Serial.println(system_get_sdk_version());

        wifi_set_opmode(NULL_MODE);
        system_soft_wdt_stop();
        ets_intr_lock( ); //close interrupt
        noInterrupts();

        start = micros();

        // Serial.println(system_adc_read());
        system_adc_read_fast(adc_addr, adc_num, adc_clk_div);

        unsigned int tot = micros() - start;

        interrupts();
        ets_intr_unlock(); //open interrupt
        system_soft_wdt_restart();

        tim += tot;
        total += num_samples * 1000000.0 / tot;
        i++;

        for (int j=0; j<adc_num;  j++) {
            Serial.println(adc_addr[j]);
        }

        if (i == 100) {
            // Serial.print("Sampling rate: ");
            // Serial.println(total / 100);
            // Serial.print("It lasted: ");
            // Serial.println(tim / 100);

            i = 0;
            tim = 0;
            total = 0;
        }
    #endif
}

I created a test circuit using an AC transformer to produce a 50 cycles / second sine wave signal and tried a number of variations on the system_adc_read_fast sample program in the Espressif SDK manual "2C-ESP8266_Non_OS_SDK_API_Reference__EN".

The ESP8266 ADC returned realistic values for adc_clk_div = 8 and 16, but, as you found, the values returned were always 1024 when I tried 32.

I found that the ADC unit was capable of performing ADC conversions in about 6-10 microseconds...

In a test program to collect data for a 40 millisecond period (ie two complete sine waves - I used a diode to chop off the negative halves) I called the system_adc_read_fast function 40 times collecting 116 samples in each call (using "number of samples" = 116).

I collected all the readings in a two-dimensional array before printing any values because the Serial.print function causes long delays between calls to the ADC converter. The "gaps" in the chart represent the changes in the sine wave signal between successive calls to the ADC read function.


Garbled serial from GPS device I'm using an Arduino Uno. "Regular" serial is plugged into my computer, and I can receive just fine.

I'm using AltSoftSerial (tried SoftwareSerial, same results) with RX and TX on pins 8 and 9 to interface with a BR-355S4 GPS module. According to the data sheet on that module, the RX and TX are at 5v, which I believe is what the Arduino expects.

I combined the Serial and SoftwareSerial examples to test the connectivity from the Arduino to my PC and from the GPS to the arduino.

#include <AltSoftSerial.h>
AltSoftSerial altSerial;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(19200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  printAsciiTable();

  altSerial.begin(4800);
}

void printAsciiTable(){
  Serial.println("ASCII Table ~ Character Map");
  int thisByte;
  for(thisByte = 33; thisByte < 127; thisByte++){
    Serial.write(thisByte);
    Serial.print(", dec: ");
    Serial.print(thisByte);
    Serial.print(", hex: ");
    Serial.print(thisByte, HEX);
    Serial.print(", oct: ");
    Serial.print(thisByte, OCT);
    Serial.print(", bin: ");
    Serial.println(thisByte, BIN);
  }
  Serial.println("~~Done with ASCII Table~~");
}

void loop() {
  char c;
  if(altSerial.available()){
    c = altSerial.read();
    Serial.print(c);
  }
}

The data coming into the Serial Monitor tool looks fine until it starts pulling from the GPS serial stream (ellipses added by me):

  ...
  |, dec: 124, hex: 7C, oct: 174, bin: 1111100
  }, dec: 125, hex: 7D, oct: 175, bin: 1111101
  ~, dec: 126, hex: 7E, oct: 176, bin: 1111110
  ~~Done with ASCII Table~~
  4™5f3y=›ùÙ)É9Ó¦Ì™¦ ...

I would like to receive the correct NMEA strings from the GPS module on altSerial and push them out to Serial. The garbled nature of the serial data looks like a baud rate issue, but I've tried a handful of combinations for Serial and altSerial speed with no success. Any ideas?

I looked up the datasheet and product specs for the GPS device. It says that the output is RS-232.
Note that RS-232 is NOT compatible with the Arduino levels. Arduino "talks and listens" at 5V or 3.3V depending on which board you're using.
So what you need is a RS-232-to-TTL converter. Now, TTL speaks Arduino. So Arduino will be able to understand that. So try using a MAX232 IC or a shield, whichever you're comfortable with.


How to analogRead() 2 separate pins simultanously? I am trying to create a simple piano playback using a flex sensor, a proximity sensor and a piezo buzzer.

I want to have it so that when the flex sensor is triggered, a sound is played on the piezo buzzer. The tone it makes is dependent on the values received from the proximity sensor.

Here is my code:

int psrAnalogPin = 6;
int fsrAnalogPin = 10;
int speaker = 9;
int fsrReading;
int psrReading;

void setup(void) {
  Serial.begin(9600);
  // We'll send debugging information via the Serial monitor
  pinMode(speaker, OUTPUT);
}

void loop(void) {
  psrReading = analogRead(6);
  delay(10);
  psrReading = analogRead(6);
  delay(10);
  Serial.print("\n psr reading = ");
  Serial.println(psrReading);
  fsrReading = analogRead(10);
  delay(10);
  fsrReading = analogRead(10);
  delay(10);
  Serial.print("\n fsr reading : ");
  Serial.println(fsrReading);
  if(fsrReading < 980 && psrReading > 599){
    tone(9, 400, 1000);
  } else if (fsrReading < 980 && psrReading > 500){
    tone(9, 500, 1000);
  } else if (fsrReading < 980 && psrReading < 392){
    tone(9, 600, 1000);
  }
}

When I look at the serial monitor's output, the values output seem to be only reading from my flex sensor(fsrReading) and not my proximity sensor. If I only read the proximity sensor's value it works, but not both at the same time.

How can I get it so that it reads both values instead of just one?

This is not a full code but more of an explanation of the logic of your program.

  when the flex sensor is triggered, a sound is played on the piezzo buzzer. The tone it makes is dependent the values received from the proximity sensor.

Follow this logic and try to code it:

1- read the flex sensor values

int val = analogRead(flexPin);

2- if it is triggered, THEN read the proximity sensor.

if(val > minimum) {
  int distance = analogRead(proximityPin); //this line depends on which proximity sensor you are using

3- play the sound accordingly to the proximity sensor (still in the if loop).

analogWrite(distance);

This logic should work fine. If you could include more info like board, flex sensor and proximity sensor, that could help.


Scan IP address of ESP8266 I am working on a project in which, the mobile app/browser sends HTTP command to ESP8266 in AP mode. The default IP address of ESP is 192.168.4.1. Therefore in order to connect the ESP to WiFi, the command goes like this :- 192.168.4.1/SSID=XYZ/Pass=XYZ.

On connecting to router, the ESP goes into STA mode and Doesn't create AP until WiFi is not found to which it was connected earlier. Now when ESP is connected to router, the router assigns the IP to ESP through which HTTP command will be sent. On Serial monitor, it does show the IP address to which it is assigned, but what if app controls the ESP, there is no serial communication. How will app know the IP address assigned to particular ESP8266? Is there any way app can scan the router? Or any other way to do this? If there are multiple ESP connected to router, how can I identify the IP of particular ESP.

The de-facto standard way for devices to broadcast their IP address to clients is through the Multicast DNS system (mDNS). In this system the server sends a UDP message to a specific multicast group address and clients listen for it so they can work out what is where.

mDNS is also known as Zeroconf or Bonjour depending on who you talk to.

The ESP8266 Arduino core (if you are programming the ESP8266 directly) has mDNS examples with it. If you are using the AT command interface instead, then you will need to read the manual to find how to send UDP packets to multicast addresses.


LCD shows wrong value from MQ-135 sensor and the txt is stuck on screen i am using a MQ-135 gas sensor and 20x4 LCD screen and it shows different values on the serial
monitor it shows 756 PPM and on the LCD screen it is stuck below 320PPM the text BAD is also stuck on the screen and doesn't update on the
lowering of PPM value of CO2

this is my code
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define sensor A0
int gas, co2lvl;
#define updateDisplay();

void setup()
{
pinMode(sensor,INPUT);
Serial.begin(9600);
lcd.begin(20,4);
  lcd.clear();
}

void loop()
{
co2lvl=gas-255;
co2lvl=map(co2lvl, 0,1024,400,5000);
Serial.print(co2lvl);
Serial.print("ppm");
Serial.println();
delay(200);
if(co2lvl>=699){
updateDisplay();
lcd.setCursor(0,0);
lcd.print("CO2 IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(6,1);
lcd.print("EXCELLENT");
}
else if(co2lvl<=700){
updateDisplay();
lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(4,1);
lcd.print("GOOD");}
else if(co2lvl<=900){
  updateDisplay();
  lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(5,1);
lcd.print("FAIR");}
else if(co2lvl<=1100){
  updateDisplay();
  lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(5,1);
lcd.print("MEDIOCRE");
}
else(co2lvl<=1600);{
  updateDisplay();
  lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(5,1);
lcd.print("BAD");}
}

You made a mistake in the line:
else(co2lvl<=1600);

Because of the semicolon (;) it will not do anything for that condition. But instead the following lines will be executed always.
The following is a slight refactoring making your code more clear, removing also duplicated code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define sensor A0
int gas, co2lvl;

void setup()
{
  pinMode(sensor,INPUT);
  Serial.begin(9600);
  lcd.begin(20,4);
  lcd.clear();
}

void loop()
{
  co2lvl=gas-255;
  co2lvl=map(co2lvl, 0,1024,400,5000);
  Serial.print(co2lvl);
  Serial.print("ppm");
  Serial.println();
  delay(200);

  lcd.setCursor(0,0);
  lcd.print("CO2 PRESENT IN THE AIR");
  lcd.setCursor(0,1);
  lcd.print(analogRead(co2lvl));

  if      (co2lvl <=  300) { show(6, "EXCELLENT"); }
  else if (co2lvl <=  700) { show(4, "GOOD"     ); }
  else if (co2lvl <=  900) { show(5, "FAIR"     ); }
  else if (co2lvl <= 1100) { show(5, "MEDIOCRE" ); }
  else if (co2lvl <= 1600) { show(5, "BAD"      ); }
}

void show(int position, char* text)
{
  lcd.setCursor(position, 1);
  lcd.print(text);
}


Send RF 433MHz data to Domoticz RfxCom with protocol X10 from Arduino Nano I have installed Domoticz on Raspberry Pi and bought an RfxCom 433MHz emitter/receiver.
It works well for example with Chacon DiO 54781 door sensor.
I want to create my own sensor with Arduino that would be recognized by Domoticz as a native RF 433MHz device.
In first place, I want to make a flooding sensor, I also need an On/Off information.
I would like to implement X10 protocol because it seems to be the simplest one.

I finally found a documentation about RF X10 protocol:
X10 RF Receiver.pdf

With following Hardware :

Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
RF 433MHz emitter/receiver  (3€) (Note: only the emitter is used)       https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
3 wires : VCC, GND, Signal (on Arduino pin 2)

I've created the following working code for Arduino Nano :

/*
* Custom sensor (base code)
*
* Emission in RF 433MHz with the X10 protocol for Domoticz
*
* Hardware :
*   Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
*   RF 433MHz emitter/receiver  (3€)        https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
*       Note: only the emitter is used
*   3 wires : VCC, GND, Signal (on Arduino pin 2)
*
* Documentation found for RF X10: http://www.printcapture.com/files/X10_RF_Receiver.pdf
*
* Example of malformed data received in RfxMngr in mode "nodec" (before this code was correctly debugged) :
*
*       Packettype        = UNDECODED RF Message
*       UNDECODED NEC:1C515C86F0
*
*
* Correct data that is now receveived by RfxMngr with this program :
*
*------------------------------------------------
*       Packettype    = Lighting1
*       subtype       = X10
*       Sequence nbr  = 13
*       housecode     = D
*       unitcode      = 1
*       Command       = On
*       Signal level  = 7  -64dBm
*------------------------------------------------
*       Packettype    = Lighting1
*       subtype       = X10
*       Sequence nbr  = 14
*       housecode     = D
*       unitcode      = 1
*       Command       = Off
*       Signal level  = 7  -64dBm
*------------------------------------------------
*/

const int pin_emit = 2;         // Signal pin for RF433 emitter
const int pin_led = 13;         // Internal LED : it will be ON when the "On" command is sent in RF, and OFF the the "Off" command is sent (changed each 60s)

const unsigned int X10_A1_ON = 0x00;
const unsigned int X10_A1_OFF = 0x20;

const unsigned int X10_address = 5;     // this is Housecode. In my case 5 results in "D" house code
unsigned int X10_data = X10_A1_ON;      // command. I have implemented only On/Off for unit code 1

void setup() {
  pinMode(pin_led, OUTPUT);
  pinMode(pin_emit, OUTPUT);
  digitalWrite(pin_emit, LOW);
}

/**
* Bit to 0 : 1.125ms between rising edges, so before next bit
*/
void X10_sendBit_zero()
{
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
  digitalWrite(pin_emit, LOW);
  delayMicroseconds(570);       // Total 555+570 : 1125µs = 1.125ms
}

/**
* Bit à 1 : 2.25ms entre les "rising edges"
*/
void X10_sendBit_one()
{
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
  digitalWrite(pin_emit, LOW);
  delayMicroseconds(1695);      // Total 555+1695 : 2250µs = 2.250ms
}

void X10_send8bits(unsigned int data)
{
  // - Send the 8 bits, and then the complementary of the 8 bits.
  // from documentation: "Within each byte, bit7 is received first and bit0 last"
  int mask = 0x80;
  for(int i = 0; i < 8; i++)
  {
    int bit = mask & data;
    if (bit == 0)
      X10_sendBit_zero();
    else
      X10_sendBit_one();

    mask = mask >> 1;
  }
}

/**
* Sending a byte consists of sending this byte, and then sending the opposite of the same byte.
* As we send the opposite as well as the data, the total duration is always the same : 8 * (1.125ms+2.250ms) = 8 * 3.375 = total of 27ms
*/
void X10_sendByte(unsigned int data)
{
  X10_send8bits(data);
  X10_send8bits(~data);
}

/**
* Send a complete X10 packet
*
* Total duration :
* (9ms + 4.5ms) + (27ms + 27ms) + 0.555ms + 40ms = 108.055 ms
*  from doc: "It appears, from articles on the 'net, that other people have seen a range from 95 msec to 116 msec for various transmitters and that standard X-10 transceivers can tolerate timing variations of 30-35% from nominal."
*/
void X10_sendState_once(unsigned int data)
{

  // - Header
  digitalWrite(pin_emit, HIGH); // "Burst" de 9ms
  delayMicroseconds(9000);
  digitalWrite(pin_emit, LOW); // Silence de 4.5ms
  delayMicroseconds(4500);

  // - Data
  X10_sendByte(0x50); // - Address
  X10_sendByte(data); // - Data

  // - Send a last rising edge to validate last bit
  digitalWrite(pin_emit, HIGH);
  delayMicroseconds(555);       // Arbitraty value (but always the same), for "VCC" state.

  // - Footer
  digitalWrite(pin_emit, LOW); // Silence de 40ms pour signifier la fin de l'émission
  delayMicroseconds(40000);

}

/**
* Send a complete packet multiple times (this X10 protocol has not ACK))
* From doc: "Most X-10 RF transmitters send a minimum of five copies of the code separated by 40 msec silences although some can send single bursts."
*
*  5 times 108.055ms = 540.275 ms, half a second
*/
void X10_sendState(unsigned int data)
{
  // - "clean" to be sure to have a zero for the first rising edge on init
  digitalWrite(pin_emit, LOW);
  delay(1);

  // - Send 5 time complete packet
  for(int repeat=0 ; repeat<5 ; repeat++)
    X10_sendState_once(data);

}

void loop() {

  if(X10_data == X10_A1_ON)
    digitalWrite(pin_led, HIGH);
  else
    digitalWrite(pin_led, LOW);
  X10_sendState(X10_data);
  delay(60000);              // 1 minute

  // - I change state each 60 seconds to see changes in Domoticz
  if(X10_data == X10_A1_ON)
    X10_data = X10_A1_OFF;
  else
    X10_data = X10_A1_ON;
}

By changing House code and data, it is now possible to create our own RF sensors.


How to generate two pulses one with 60 and other 66 duty cycle at same instant in 2 pins? I have to drive two switches one at a duty cycle of 60% and the other at a duty cycle of 66% simultaneously at 50khz frequency. I am using an Arduino Uno ATmega 328.

I proposed a few approaches in generating 100kha pwm pulse trains here in response to someone's ask a couple of days ago. The identical code would work for your purpose as well.

It should come up quickly if you do a scan of topics here.

edit: to make it a little bit easier, here is the code I used to generate 50Khz pulse train with 60% and 66% duty cycles.

void setup() {
  // put your setup code here, to run once:
  //pinMode(led1, OUTPUT);                      //led1 as output
  //pinMode(led2, OUTPUT);                      //led2 as output
  pwm1topr(F_CPU / F_PWM);                      //set tmr1/pwm frequency to F_PWM
  analogWrite(led1, F_CPU / F_PWM * 60 / 100);  //led1 @ 60% duty cycle
  analogWrite(led2, F_CPU / F_PWM * 66 / 100);  //led2 @ 66% duty cycle
}

void loop() {
  // put your main code here, to run repeatedly:
    //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
    //delay(100);               // wait for a second
    //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
    //delay(100);               // wait for a second
}

and a quick sim confirms its functionality.

enjoy.


lilypad works with wrong baudrate I wrote a simple code on lillypad with fdti module as below:

void setup(){
Serial.begin(57600);
}
void loop(){
 Serial.println("ddd");
 delay(500);
}

but it gives wrong characters at serial port window of arduino ide at 57600 baudrate. But I changed baudrate to 115200 at same window it gives right string as "ddd". Other baudrates do the same thing. What is the solution or where is the problem. I couldnt understand why baudrate shift occurs

The baud rate shift occurs because of a mismatch between the speed your program thinks the chip is running at and the speed the chip is actually running at.

You may also have noticed that delay(500) is too fast and actually lasts as long as delay(250) would.

By the numbers involved it looks like the board is running twice as fast (115200 / 57600 = 2) as your board definition says it is - maybe you're using an 8MHz definition for a 16MHz board, or a 1MHz definition for a 2MHz board, etc.

Make sure you have the right board definition selected in the IDE for your board.


Random characters transmitted from ESP8266 to Arduino Below is  the code for getting a value from Firebase and sending the received data to arduino for performing necessary action.
The code here here sends a string "o" to arduino once

//uploaded to ESP8266
.
.
.
if (cu_st == "c")
  {
    sent = 0;
  }
  cu_st = Firebase.getString("feeder");
   if (cu_st == "o")
   {
    Serial.println("\t\trecd req to feed");
    if(sent == 0)
    {
      esp.print("o");
      sent =1;
      cu_st = "c";
      Serial.println("setting feeder to close in firebase");
      Firebase.setString("feeder" ,"c");

   }
.
.
.

Below is the code that gets the value, carries out necessary actions.

//uploaded to arduino
.
.
.
void feed_cmd()
{
  while(ArduinoUno.available())
  {
    char valve = ArduinoUno.read();
    Serial.print("feeder cmd recd ");
    Serial.println(valve);
    if(valve=='o')
    {
       digitalWrite(led, HIGH);
       //feeder.write(0); //open position
       open_time = millis();
       feeder = 1 ;
       Serial.println("I am opening feeder");
    }
  }
}

void close_feed()
{

  if(feeder == 1)
  {
   close_time = millis();
   if(close_time - open_time > 5000)
  {
    feeder = 0;
    digitalWrite(led , LOW);
    Serial.println("I am closing feeder") ;
  }
  }
}
.
.
.

My expectation/understanding is that:

feed_cmd() continually checks for any data
As soon as it receives data LED turns ON and after 5 sec close_feed() turns OFF the LED.

But what happens is that the while() in feed_cmd() continually executes showing some random data and also all of what I said above is also being carried out! (pic attached)

Why is there random serial data, even after sending only once and even after reading the sent data?

Is it bad coding / hardware?

Thanks for reading through and would really appreciate it if you can help me sort it out!!

Edit I found this link smthg abt pin voltages  when I was looking for possible explanation for my code's behaviour, If somebody can simplify it and explain it, it'd be better !!

The baud rates, voltages, and timing all have to match up for serial communication to work right.

So, set both of your devices to the same baudrate (you specify the number in Serial.begin()), and ensure they're connected properly. (voltages match, TX to RX, and ground is connected)

You can just read/print the serial input to the arduino with something like Serial.print(softSerial.read()) in your code if you think you don't have serial wired up right.

Also in an unrelated issue; the esp32 spits out data on its main serial line at 115200 when it boots up which you can not disable. you can use the serial port afterwards though.

Here's a copy of what gets printed out on one of mine;

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac


How to prevent inclusion of unnecessary libraries? How do you save space by preventing the inclusion of unnecessary binaries?

When I compiled the ROS Blink example, I received the warning:

Global variables use 1,951 bytes (76%) of dynamic memory,
leaving 609 bytes for local variables. Maxiumum is 2,560 bytes.
Low memory available, stability problems may occur.

Considering the example uses almost no libraries, I was surprised by this, but sure enough, the compiler pulls in a ton of libraries that are never used:

Scanning dependencies of src
Scanning dependencies of arduino
Scanning dependencies of ros_lib
src/main.cpp
arduino/wiring.c
arduino/wiring_shift.c
arduino/wiring_digital.c
arduino/wiring_pulse.c
arduino/WInterrupts.c
arduino/hooks.c
arduino/wiring_analog.c
arduino/USBCore.cpp
arduino/new.cpp
arduino/Tone.cpp
arduino/WString.cpp
arduino/HardwareSerial1.cpp
arduino/Stream.cpp
arduino/HardwareSerial3.cpp
arduino/HardwareSerial0.cpp
arduino/CDC.cpp
arduino/HardwareSerial2.cpp
arduino/main.cpp
arduino/HID.cpp
arduino/HardwareSerial.cpp
arduino/IPAddress.cpp
arduino/Print.cpp
arduino/WMath.cpp
arduino/abi.cpp
Linking libarduino.a
ros_lib/duration.cpp
ros_lib/time.cpp
Linking libros_lib.a
Linking firmware.elf
Converting to firmware.hex

Why are so many files being included in the compilation, and how do I filter them out?

The Arduino IDE build script will actually copy all core source code file to the tmp directory, compile and generate an archive file. The sketch is compiled and linked with this library. Only the referenced (used) functions and data are linked in the binary.

The size (both program and data) of this blink is somewhat larger than the "standard" blink example but this is due to the publisher-subscriber run-time.

Cheers!

PS: If you google you can find commands to listing what is actually in the generated binary. Here is a starting point.


I want to control a single DC motor with an Arduino. Why would I use an Arduino motor shield as opposed to an H-circuit and a MOSFET? I'm new to electronics. I'm trying to build something that will involve controlling the direction of rotation of a DC motor. A lot of online resources seem to recommend using an Arduino motor shield. But why shouldn't I just use some combination of an H-circuit (to control the direction of rotation) and a MOSFET (to switch power to the motor on and off)?

The major benefit to using a shield vs building the same circuit yourself is convenience. Assuming that your circuit is identical to the circuit on the shield then they should both work in an identical manner (barring any minor variations due to the quality of solder joints or circuit paths). The nice thing about the shield is it is almost plug and play. It has the same footprint as the Arduino and you don't have to design and assemble the circuit on a perf board. Generally, you will end up with fewer wire leads running around making for a cleaner assembly and easier prototyping.


Can't assign elements to index in array I'm trying to create an array of strings. I'm building each individual string by parsing a json file and getting the strings between '{'s and '}'s. However, for some reason, my array is only assigning one index with the string i want. This is my code:

  String day = "";
  String Combo[] = {"0","0","0","0","0","0","0","0"};
  int x = 2;
  int number = 0;

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    /* Reads one character at a time*/
    while (www.available()) {
      char sym = www.read();

      if (sym == '{') {
        x = 1;
      }
      if (x==1){
        if (!day.concat(sym)) {
          //Serial.println("concat() error!");
        }
      }
      if (x==1 && sym == '}'){
        x=0;
        Serial.println(number);
      }

      if ((number > 0) && (number < 9) && (x==0)) {
        Combo[number-1] = day;
        Serial.print(day);
        Combo[number-1] = day;

        Serial.println(F("-------------------------------------"));
        Serial.println(Combo[number-1]);

        Serial.println(F("-------------------------------------"));
        Serial.println(F("-------------------------------------"));
        day = "";
        number +=1;
        x = 2;
      } else if (number ==0 && x ==0){
        day = "";
        number +=1;
        x = 2;
      }
      lastRead = millis();

    }

  }

Which returns this:

{
    "firstString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "secondString"
    }-------------------------------------
{
    "secondString"
    }
-------------------------------------
-------------------------------------
{
    "thirdString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "fourthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "fifthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "sixthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "seventhString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "eighthString"
    }-------------------------------------

-------------------------------------
-------------------------------------
{
    "secondString"
    }-------------------------------------

Based on this output I know that day is being constructed correctly but for some reason isn't assigned to an index in Combo (except "secondString")
Does anyone know what's going on?

Ideally Combo would equal: {"secondString", "thirdString", ... "eighthString"}

I'm trying to understand your code.

It looks like x is a state variable, with the following values:

2 = "Looking for start brace (`{`)"
1 = "Found! Now accumulating `day` until stop brace (`}`)"
0 = "Finished!"

If so, you may instead want to use the following:

enum States { Looking, Adding, Done };

// int x = 2;
States state = Looking;

// x = 1
state = Adding;

// if (x==1){
if (state==Adding) {

If you follow the flow of code, when number is still 0 and x finally becomes 0, you:

Print out number - the first line of your output;
You then miss the main if (number is not greater than 0);
And enter the else (which is satisfied);
And then you immediately clear your hard-earned day.

The second time through, after x becomes 0 again, this time you:

Print out number - the second line of your ouptut;
You do enter the main if:

You assign day to Combo[1]
You print out only the first seven entries in the the array (you want <=7, not <7)

This should print out 0{?}000000 (I don't know what day should be).
The fact that it doesn't seems to imply that your concat() failed. Can you please change it to

// day.concat(sym);
if (!day.concat(sym)) {
    Serial.println("concat() error!");
} // if

You then print out the row of dashes - and start a new line.

The third time through, it seems to work - you get your {$ "first string" $} (where $ represents \n and/or \r - can you strip those out?)

      // if (x==1){
      //    day.concat(sym);
      if (x==1 && sym>=' '){ // Don't concat new line characters!
          day.concat(sym);

And the final few times concat() seems to have failed again.

The reason I say "concat() has failed" is that it looks like day is still "" when it is assigned to Combo

Edit

You've changed the code so that the main if now does the following:

Assigns day to Combo[number-1];
Prints out day - this seems to work;
Assigns day to Combo[number-1] again;
Prints out a line of hyphens - this works;
Prints out Combo[number-1] - this does NOT seem to work;
Prints out two lines of hyphens - this works.

Since 5 is printing out nothing, it implies that 3 failed. This really does look like you're in a low-memory condition, and the system is failing to allocate memory from the heap.

You don't say what Arduino you're working on - note that most don't have much memory, and if you're already parsing a JSON file you've probably used a lot of it. You also don't say which version of the Arduino IDE you're using. There was a String bug in the earlier versions.

Rather than trying to use the String class (a renowned heap hogger), you should try to use normal char arrays and work the buffer management yourself.


Can I connect this LED Matrix to a ESP8266 Huzzah directly? This tutorial for the 16x32 LED Matrix makes it sound like you have to use an Arduino Uno or Mega, but the tutorial was also written a few years ago.  I have a Huzzah ESP8266 (my project is about displaying information from the internet on the LED matrix) but I can't seem to get the  library to work with the Huzzah.

I am wondering if it would be possible to somehow hook up the LED matrix directly to the Huzzah. Can anyone make suggestions on this front?

Or do I have to basically make the Uno a slave to the Huzzah ESP8266? Need to figure out how to do that.

Thank you.

The Huzzah is a great board but I don't think it is capable of driving a large led matrix by itself.  Adafruit also makes a led matrix feather wing which could enable the huzzah : https://www.adafruit.com/product/3090


New Arduino Motor Shield Short Circuiting my board? I just got this today, plugged it in my arduino, and the arduino light starts dimming until you cannot see it any more over the course of 5 seconds. The Computer disconnects the arduino when the light is off (Ding Dong Sound). I found pulling the VIN Connector Jumper/Power Jumper will stop the short circuit and work, but that defeats the purpose, as the board wouldn't even powered.

Here is the video:
YouTube

Is the motor board broken? If so in what way? are the wires on the board simply broken? Is it due to bad soldering?(I checked solder, looks fine).

Arduino Model: Arduino UNO by Elegoo
Motor Driver Model: L293D Driver Board
Ebay Listing For Item
(I tried using this with a MEGA also, would short it as well).

Thanks to @jwpat7, I have discovered that the reason it is not working is that the seller has messed up and sent me 3 of the same chip, 74HC595N. After doing some research, I have purchased the LM293D Chips.


How to program pressure sensor and motor with motor shield I was working on controlling a high power motor with a heavy duty motor controller, and I was able to make my motor spin, but I wasn't able to incorporate a program for my pressure sensor and make it determine the speed of the motor.  I'm pretty sure I connected the parts correctly on my circuit board, so I figure my code must have some mistake, or something missing.
The pressure sensor I'm using:
The motor controller I'm using: http://www.robotshop.com/en/arduino-compatible-mega-motor-shield-1a-5-28v.html#Useful
The code I have:

int motorValue=0;
int sensorValue=0;
int sensorPin=A0;
int EnablePin=8;
int PWMPin2=3;

void setup() {
  // put your setup code here, to run once:
pinMode(EnablePin, OUTPUT);
//pinMode(sensorPin, OUTPUT);
Serial.begin(9600);
pinMode(PWMPin2, OUTPUT);
pinMode(sensorPin, INPUT);
}

void loop() {
// put your main code here, to run repeatedly:
sensorValue = analogRead(sensorPin);

//float voltage = sensorValue * (5.0 / 1023.0);

//Serial.println(voltage);

delay(50);

motorValue=map(sensorValue,0,1023,0,255);
//motorValue=sensorValue / 4;
//analogWrite(motorPin,motorValue);
digitalWrite(EnablePin, HIGH);
analogWrite(PWMPin2, motorValue);
}

Edit: The sensor works by reading the voltage.  Here's an actual picture of how I wired it:  I used this wiring to print out the voltage with just the Arduino and it worked, and I'm using it with the same wiring but while having the motor shield on top, so that's why I'm guessing that I must not be programming the sensor right with the motor controller.  I couldn't get the voltage readings when I used this setup with the motor driver shield.

Depending on the jumper settings, the MegaMoto shield will drive current sense voltages onto one or two of the Arduino analog inputs.

Your picture shows the shunt installed to drive A0, which is of course going to conflict with your attempt to use the same pin for the force sensor.

If you are not using current feedback, it seems like you may be able to just remove that jumper, otherwise you will need to pick distinct pins for the current sense and your force sensor.  Consult the manual to be certain.

(The other placement of the other jumper in that block looks a bit suspicious too, almost seems it may be shorting the two current sense channels together, but not certain about that)


MAX7219 library that can compensate for poorly designed/miswired 8x32 panel? I have this sample code:

#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

#define MAX_DEVICES 4
#define CLK_PIN   11
#define DATA_PIN  12
#define CS_PIN    10

MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

void setup(void) {
  P.begin();
  P.print("PPPPPPPP");
}

void loop(void) {
}

And this is how it lights up the display:

I presume that the code displays text incorrectly, because the display manufacturer has connected individual 8x8 displays "differently than any library expects" (i.e. in red I have annotated the column addresses for my display, while with green I have annotated what they would have to be for this library to show text correctly).

I have two questions:

Is there any good Arduino graphics library that would allow me to fix from software the addressing issue specific to my display?
Since in the future I plan to make a 16x64 display out of 4 of these, then is there a library capable of doing that as well (i.e. have vertical font size of 12-16 pixels)?

The issue is minor. It looks like the library was designed for a slightly different matrix display / wiring.

Take a look at the library and it likely maps the input buffer to segment / dot-matrix information. Play with that.

The author did 99% of the work for you. You just need to finish the last 1%.


Arduino Hardware Issue I have two Arduino Uno R3 boards and both of them now seem to have an issue. There's a micro sized 8 Pin chip near the dc power port. This seems to get incredibly hot (i managed to get a blister from touching it) and the "L" Led seems to stay dimly lit even when the reset button is pressed.

The Arduino Uno was working fine during operation and only started giving me this problem recently, i cant seem to find any visible short or loose terminal on the board.

I can see that the reset function is being used as my LCD does reset.
Would anyone have a reason for this mysterious issue?

There are two issues here:

The "L" LED lighting. On the R3 Uno this is driven by an op-amp and if pin 13 is "floating" the op-amp may, or may not, turn the LED on. So this is normal.
The 8-pin chip near the power plug getting very hot. This is definitely not normal. You must be consuming a lot of current to do that. You could try measuring it. A Uno running an "empty" sketch should be consuming around 50 mA. Note that this chip is the op-amp mentioned in my first point. Possibly you have damaged it. Did you connect an LED (or motor) or similar to pin D13? If so, what current-limiting precautions did you take?

Try running an empty sketch (or the Blink sketch) with no hardware connected to the board, to see if it still happens.
Try measuring the power consumption, if possible, with a meter measuring the input through the 5V pin, if you have a 5V power supply you could use for this.
Are these genuine boards, or cheap clones from eBay?


Options for measuring position of garage door I'd like to be able to measure the position of my garage door. Determining if the garage door is fully open or fully closed should be fairly simple with some magnetic reed switches but I'd like to know the position of the door when it's partially open/closed.

A couple of possibilities occur to me. One would be to mount a rotary encoder on a rotating part of the door. Another would be to attach a reed switch to the track and a series of magnets to the door. I suppose you could do something with a proximity sensor as well.

How much precision do you need in the position of the door? What do you know that is deterministic? For example is the door transit time predictable? Is it a positive drive? Do you get to know when the door starts moving? That might be enough right there.

If you can say more about what you're trying to do it would make it easier to provide suggestions and insight.