How to optimise TX power for ESP8266? I have multiple ESP8266 units programmed using Arduino SDK and I would like each one of them to adjust the transmission power to lower the power requirements.

Arduino allows setting the TX power of the ESP8266 using the function WiFi.setOutputPower(), however it is not clear to me how to choose that value.

I know that RFM69 using the LowPower library has automatic gain control using the ACK packet sent by another RFM69 module. However, with ESP8266 there is a standard AP and a similar approach would not be obvious.

How can I perform optimal gain control?

This question is independent from the choice of the WiFi mode b/g/n using WiFi.setPhyMode().

Edit

An idea could be to detect AP station signal strength and transmit at a power level offset by a fixed amount, decreasing that delta by one tick at every wake up, until no connection is achievable. At that point the delta should be increased by an amount corresponding to a sort of hysteresis, to jump above the no-connection threshold, and kept.

After a predefined amount of successful wake ups, for example 100, the process of decreasing the calculated delta would be tried again.

For example: AP strength -60 dB, transmission +12 dB: success -> delta 48 dB is good.

Next wake up, delta 48.25 dB: is AP is at -55 dB, transmission would be 55-48.25 dB = 6.75 dB. If success, delta increased to 48.50 dB.

I would like ... to adjust the transmission power to lower the power requirements.

Is your goal to reduce overall/average power consumption, or peak current draw? If the former, then because of the high-level nature of the wifi API exposed by the ESP system, you may get a greater level of success by optimizing the time you are connected, rather than the power consumption.

That is, make sure WiFi radio is disabled while you are preparing whatever data you may wish to send over WiFi, then turn the radio on, connect+send, go back to sleep.

This blog post gives experimental details, but the gist is

In Setup():

WiFi.mode( WIFI_OFF );
WiFi.forceSleepBegin();
delay( 1 );

Just before you choose to connect:

WiFi.forceSleepWake();
delay( 1 );

// Bring up the WiFi connection
WiFi.mode( WIFI_STA );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

And, when you go to sleep, tell the system to keep the radio off by default:

WiFi.disconnect( true );
delay( 1 );

// WAKE_RF_DISABLED to keep the WiFi radio disabled when we wake up
ESP.deepSleep( SLEEPTIME, WAKE_RF_DISABLED );

Part 3 of this blog also notes that if you will continually be connecting to the same WiFi network, you can tell the ESP8266 to not spend the time loading the previous connection's details from flash memory, but requiring you to provide them in the connection call:

WiFi.forceSleepWake();
delay( 1 );

// Disable the WiFi persistence.  The ESP8266 will not load and save WiFi settings in the flash memory.
WiFi.persistent( false );

WiFi.mode( WIFI_STA );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );


Can I avoid having a bootloader if I use ISP to flash to an arduino? My Trinket Pro waits about 10 seconds upon booting before starting the program that I have loaded on it.

Can I avoid this delay and the bootloader taking up space if I flash my program directly to the Arduino with ArduinoISP?

It looks like the Trinket Pro has an Atmega328P processor. You can change the fuses to not run the bootloader, in which case you don't need the space taken by it.

I have a hex uploader sketch which will upload a .hex file from an SD file directly to the chip, removing the need for a bootloader. Using ArduinoISP is another approach which will probably work. I'm not sure whether that fixes up the fuses for you.

If you just want to avoid the time (and not the space - the bootloader is probably only 512 bytes) you can use the sketch I linked to (without needing an SD card) to make fuse changes.

See Engbedded Atmel AVR® Fuse Calculator for fuse calculations. Basically you need to toggle the BOOTRST fuse (the low-order bit of the High fuse).


Arduino nano digital I/O overload Is it possible to kill arduino nano with overload?
I wanted to drive a relay with arduino, and I used a BC547 to switch 12V for the relay.
But in the relay there was a diode, which sorted out the circuit (thats why I drawed in the wrong orientation)
I know it was a mistake to not use current limiting resistor on Base of the transistor.
Is it possible that this shorted circuit made too much current on the transistor base which killed my arduino?
I made this circuit:

Short answer is probably.  There is a voltage drop from base to emitter that is about .7 volts.  But something still has to contend with the rest of the energy.  You might try a different Arduino digital output on the chance that the balance of the processor is working as expected.
I say probably because several things might have happened if the transistor actually turned on.  For instance the forward biased (backwards) diode may have allowed so much current to flow through the relay and transistor that the transistor failed first.  Or, if the power supply had a low current rating, it may not have had the capacity to burn anything out.  As you can see, it is difficult to say what exactly happened with out testing each part individually.


problem with bitwise OR I have this code, in which I try to "glue" four bytes in order to construct an unsigned int. I shift left the bytes and "add" them using the OR operator.

unsigned long number1;
unsigned long number2;
unsigned long number3=0;

byte byte0 = 1;
byte byte1 = 40;
byte byte2 = 107;
byte byte3 = 238;

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

void loop(){
  number1 = byte1 <<8 | byte0 ;  //(=10.241 O.K.)

  //(should be 4.000.000.001, it produces 10.241)
  number2 = byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0;

  //(should be 4.000.000.001, it produces 4.016.777.217)
  number3 = number3 | byte3;
  number3 = number3<<8;
  number3 = number3 | byte2;
  number3 = number3<<8;
  number3 = number3 | byte1;
  number3 = number3<<8;
  number3 = number3 | byte0;

  Serial.print("number1 = ");Serial.println(number1);
  Serial.print("number2 = ");Serial.println(number2);
  Serial.print("number3 = ");Serial.println(number3);
  Serial.println(" ");
}

The problem is that the OR operator applies only to byte1 <<8 | byte0 and ignores the rest. That is number1 and number2 appear to have the same value (10241).

I also tried "adding" them up separately, as shown with number3, but it also produces a wrong result as well.

I tried the same code in python, and it works fine.

byte3, byte2, byte1, byte0 = 238, 107, 40, 1
print byte1 <<8 | byte0
print byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0

number3 = 0;
number3 = number3 | byte3;
number3 = number3<<8;
number3 = number3 | byte2;
number3 = number3<<8;
number3 = number3 | byte1;
number3 = number3<<8;
number3 = number3 | byte0;
print number3

So, the question is:

Why both number2 and number3 produce a false result?

Correction from another answer for number2:

number2 = (unsigned long)byte3 <<24 | (unsigned long)byte2 <<16 | byte1 <<8 | byte0; // = 4.000.000.001

And in the first round of loop number3 is correct, all others are wrong as number3 holds a result from previous loop.

  number3 = byte3; // all magic lays here
  number3 <<= 8;
  number3 |= byte2;
  number3 <<= 8;
  number3 |= byte1;
  number3 <<= 8;
  number3 |= byte0;


Help Led matix isn't lighting up correctly Is it a Hardware or software issue? I am trying to reverse engineer the project from this video: https://youtu.be/zc1zbwheyE0?t=50s.

From the video a visible 10 wires are going from the LEDs to the Arduino mega, i am assuming that they are wired in a 5x5 matrix (5 rows, 5 columns) given that there are 25 keys on the Midi controller so there most be 25 LEDs.
I reconstructed the project the best a could from observing the video, but my issue is when i press 3 keys 5 LEDs light up unlike in the original video where 3 keys are pressed and 3 LEDs light up(as seen @ 0:50 of the video).
This is the issue i am having : http://imgur.com/a/9SOEJ.
I am thinking the issue is related to how i have my LEDs wired, but my LEDs are wired exactly the same as in the video. isn't it ? is there something i might have missed? How is the project in the video able to light up 3 LEDs without having an issue with extra LEDs lighting up in their matrix? how can i fix my circuit to replicate the video?

Here is some of my coed for turning on an LED when a key is pressed:

<include MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

byte anodes[5] = {30, 32, 34, 36,38};

byte cathodes[5] = {31, 33, 35, 37,39};

byte data1 = 0;

void setPinTo5V(byte pin) //set a pin given to this function to a 5V voltage source

{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);
}

void setPinToGND(byte pin) //set a pin given to this function to a GROUND (GND pin)
{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
}

void loop() {
    MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    data1 = MIDI.getData1();

    if (data1==48){//C3
        setPinTo5V(anodes[0]);//set pin 30 to 5V
        setPinToGND(cathodes[0]);//set pin 31 to GND

        delay(1); //do nothing for 1 ms
    } //this is done for all 25 keys

}

any help would be appreciated Thanks.

This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.

include

MIDI_CREATE_DEFAULT_INSTANCE();

define LedR 3   //

define LedC 4 //pin for each led

byte data1 = 0;

unsigned long previousMillisR[2]; //[x] = number of leds

unsigned long previousMillisC[2]; //[x] = number of leds

int Status [25];

void setup() {

MIDI.begin(MIDI_CHANNEL_OMNI);

MIDI.setHandleNoteOn(MyHandleNoteOn);

MIDI.setHandleNoteOff(MyHandleNoteOff);

pinMode(LedR, OUTPUT);

pinMode(LedC, OUTPUT);

}

void loop() {

MIDI.read();

//BlinkLedR(LedR,2000, 0);   //BlinkLed( which led, interval, one of the
stored prevMillis

//BlinkLedC(LedC, 10, 0);  //last parameters must be different for each
led

}

void BlinkLedR (int led, int interval, int array){

//(long) can be omitted if you dont plan to blink led for very long time I think

if (((long)millis() - previousMillisR[array]) >= interval){

previousMillisR[array]= millis(); //stores the millis value in the

selected array

digitalWrite(led, !digitalRead(led)); //changes led state

}

}

void BlinkLedC (int led, int interval, int array){

//(long) can be omitted if you dont plan to blink led for very long
time I think

if (((long)millis() - previousMillisC[array]) >= interval){

previousMillisC[array]= millis(); //stores the millis value in the

selected array

digitalWrite(led, !digitalRead(led)); //changes led state

}

}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

data1 = MIDI.getData1();

if (data1==48){//C3

Status[0]=1;

while(Status[0]==1) {

BlinkLedR(LedR, 10, 0);   //BlinkLed( which led, interval, one of the

stored prevMillis

BlinkLedC(LedC, 1, 0);  //last parameters must be different for each led

if (Status==!1){

break;

}

}

}

}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {

data1 = MIDI.getData1();

if (data1==48){//C3

Status[0]=0;

}

}


Scroll LCD display connected to an Arduino Uno I want to make some characters scroll left without affecting the first positions in each row of my LCD 16x2 screen. I have this code inside the loop so far:

lcd .clear();
lcd.setCursor(17, 0);
for (int i = 15; i > 0; i--) {
  lcd.print("x");
  lcd.scrollDisplayLeft();
  if (digitalRead(switchPin) == HIGH) {
    lcd.setCursor(0, 0);
    lcd.write(5);
  } else {
    lcd.setCursor(0, 1);
    lcd.write(5);
  };
  lcd.setCursor(17, 0);
  delay(500);
}
lcd.noAutoscroll();

I think it should work, but the character x just moves left by one position, whereas the character in the first position, either in the first or second row doesn't appear at all.

I would do the following (beware - not tested):

lcd.clear();
lcd.setCursor(15, 0);
lcd.print("x");
for (int i = 0; i < 15; i++) {
    lcd.setCursor(0, digitalRead(switchPin) == LOW);
    lcd.print("5");
    delay(500);
    lcd.scrollDisplayLeft();
}


Detecting Ultrasonic sensor malfunction within the arduino sketch Is it possible to write code in the sketch that checks the functioning of the ultrasonic sensor? Say if the sensor stopped working then the arduino will alert the user in the serial monitor.

First of all, this question is hard to answer because you don't provided a name of ultrasonic sensor that you are using. Also as @Majenko pointed out, the key here is to determine the state that you think sensor is not working correctly.

But if assume that you're using standard trig/echo ultrasonic sensor (HC-SR04 or similar) interface - the only possible solution here is to monitor the output(echo) signal of the sensor. Broken sensor will not respond on trigger pulses, so you'll not get the echo pulses. However, these sensors also do not send a signal if the object is out of range of the sensor.

Thus, it is possible to determine the breakdown by monitoring the output signal from the sensor only if you know that the object will always be in range. Otherwise - you can not determine for certain because of what you did not receive a signal, whether it is a sensor failure, or the object is too far from the sensor.


"char inChar = (char)Serial.read();" why is the "char" in brackets? and what is it called I am sure this is a very simple answer, but I don't know to look it up on google

In the example "SerialEvent" in the arduino IDE (v1.8.7), there is the following function

    void serialEvent() {
        while (Serial.available()) {
           // get the new byte:
           char inChar = (char)Serial.read();
           // add it to the inputString:
           inputString += inChar;
           // if the incoming character is a newline, set a flag so the main loop can
           // do something about it:
           if (inChar == '\n') {
               stringComplete = true;
           }
        }
     }

On the third line "char inChar = (char)Serial.read();" the (char) is given in brackets before the serial read.
Why is this? and more specifically how is called ?

It is called type casting and will convert one type to another. The return type of Serial.read() is int, because it will return -1, when you try to read without any bytes being available. The casting with (char) will drop the high byte of the (2-byte long) integer, leaving only the lower byte. This byte will contain the actual read data, in which you are interested here.

Casting is a complex thing, because there can be different ways to convert different types (for example maintaining the bit-content vs. maintaining the decimal value). The casting, that you are seeing here, should only be done, if you really know, what you are doing. The bits will not be changed to maintain the correct value, but the bit-content will be preserved, unless the new type is smaller than the former. In this case the rest is lost. Also, if you try to cast a float value to an int value with this, you will get a totally different decimal value out of it, because the numbers are encoded in the bits in a totally different way. Here it is known to be OK, especially, if you are checking for available bytes before reading with Serial.available(), because the library puts the ASCII data in the lower byte.

For further explanations you should consult C/C++ guides.


Send out a short signal every 10 seconds to an arduino In order to reduce power consumption, I want to resume my Arduino from standby mode every 10 seconds. For this a hardware interrupt is necessary.

Is there such a device that can create a quick impulse to trigger that interrupt? It can be anything from 10ms to 2 seconds; doesn't matter. My first thought was to use a 555 timer, but this one can only be on for 10 seconds and off for the same amount of time.

The best solution for me would be an already assembled device that I just have to wire with my Arduino since my knowledge in electronics is very low. Or a detailed assembly plan, then I would be able to build it myself I guess?

UPDATE: I was now able to put the Arduino into standby-mode using the Low-Power library. At first it seemed like it didn't work, because I wanted to print out a text over the serial connection. Instead, I tried to let the internal LED blink every 8 seconds, and this works perfectly.

A 555 doesn't have to generate a 50% duty cycle. Even if you do want to use a 50% duty cycle, the edge can be RC coupled into the interrupt to reduce the pulse width.

An Arduino can use a slow clock like a 32kHz watch crystal, then it's very low power indeed. This slow one can be used to wake-up your more power-hungry Arduino.

The lowest power and tidiest external solution would be to use a CD4060. These are designed to be very low power, very long period timing devices.

The correct way to do it is to use the internal Watchdog Timer to wake itself up from sleep. This uses an independent internal hardware 128kHz low power oscillator. The longest this can be programmed to wait is 8s. However, if you program it to 5s, then the Arduino can choose to do work, or go straight back to sleep again, on each interrupt.


How do I use two PulseIn() functions simultaneously in Arduino? I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

You can't use pulseIn() if you want to use both ultrasonic sensors at the same time.

So either:

don't use pulseIn, and instead do that part yourself using
eg. digitalRead,
use the ultrasonic sensors sequentially, one then the other, or
use pin-change interrupts to sense the signal pulse return.

The easiest approach is to use the ultrasonic sensors sequentially. In that case use the form pulseIn(PIN, value, timeout);, where timeout, in microseconds sets the maximum time to wait for a pulse.

This is practical if you know the realistic range is within a couple of metres. The speed of sound is 343.2 metres per second, or 0.3432 metres per millisecond. So if timeout is set to 3000 microseconds (3 milliseconds), then it will wait for an echo up to (roughly) 0.5 metres away.

Edit:  The distance to the object, measured by timing the delay, is half the total distance travelled because the sound travels to the object, then bounces back to the sensor.
Ie. distance to object = total distance travelled by sound / 2

An alternative is to do what pulseIn does, but for more than one pin.
This is simpler than the real pulseIn code, but illustrates the idea:

int inPin1 = ...;
int inPin2 = ...;

void setup() {
  // ... other stuff, then set up the pins
  pinMode(inPin1, INPUT);
  pinMode(inPin2, INPUT);
}

void loop() {
  // start ultrasound 1
  // start ultrasound 2
  // wait for ultrasound 1 to send pulse
  // wait for ultrasound 1 to send pulse
  long startTime = micros();
  while (digitalRead(inPin1)==LOW && digitalRead(inPin1)==LOW) {
    ; // do nothing
  }

  long stop1st = micros();
  int firstBack = -1;
  while (digitalRead(inPin2)==LOW) { // wait for the other if it was 1 first
    firstBack = inPin1; // remember pin 1 returned first
  }
  while (digitalRead(inPin1)==LOW) { // wait for the other if it was 2 first
    firstBack = inPin2; // remember pin 2 returned first
  }
  long stop2nd = micros();

  // now have the two return times, and the pin which returned first
}

You could read the source of pulseIn() and write better code than this.

The third option, to use external or pin-change interrupts, depends on which Arduino you are using. A normal ATmega328 has a couple of pins, 2 and 3, which have their own 'external' interrupt service routines (ie. each pin has a 'function' which is called when the hardware detects a signal change on a pin). To see how to attach them, see attachInterrupt.

Other pins can also be used with a 'pin change' interrupt, but each interrupt has to figure out which of a port (up to 8 pins) has triggered it, so it isn't as quick and simple.

The idea here is to start the ultrasonic sensors exactly as before, save the time they are started, exactly as before, but let a short interrupt routine capture the time that the returning echo pulse triggers the pin.

There is a little bit of care in making sure the times are captured and the main loop signalled.

You might choose to dedicate a timer to measuring the ultrasounds round trip, if you want higher resolution and lower jitter than the normal 4 microsecond timer. A microsecond is about 0.34mm, so 4 microsecond is about 1.3mm error.


ESP8266 cannot read POST parameters I'm working on a simple REST server. I made method to handle http://<esp8266_IP>/test. The GET method works like a charm and I got the response. Then I tried to send a POST with a JSON data (I used PostMan) but I cannot read anything.

Searching online I read ESP8266 library cannot parse JSON and in that case I can found plain text into server.arg("plain"). I tried that but no success

How can I read the data into the POST method?

ESP8266WebServer server(80);
...

void handleTest()
{
    if (server.method() == HTTP_GET)
    {
        ...
    }
    else if (server.method() == HTTP_POST)
    {
        String message = "POST\nHeaders:\n";
        for (uint8_t i = 0; i < server.headers(); i++)
        {
            message += server.headerName(i) + ": " + server.header(i) + "\n";
        }
        message += "\nRequest params:\n";
        for (uint8_t i = 0; i < server.args(); i++){
            message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }
        server.send(202, "text/plain", message);
    }
}
...
void setup()
{
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    if (MDNS.begin("esp8266")) {
        Serial.println(F("[Server] MDNS responder started"));
    }

    server.on("/test", handleTest);
}

Instead of using below in handleTest()

else if (server.method() == HTTP_POST)

try using below in setup()

server.on("/test", POST, handleTest);


Why does an RGB LED between VCC and PWM work? I'm an Arduino beginner and I recently bought a cheap starter kit on eBay. One of the lessons in the starter kit is an RGB LED controlled by 3 PWM output pins. However, the arrangement of the connections seems a bit funny to me:

To my surprise, it worked. I could see the three LEDs inside the plastic change colors. Why does this work? Do the PWM pins accept current whilst low? Is this a common arrangement? See the above link for the code provided in the lesson.

This is a common arrangement and is known as Common Anode, and the I/O pin is said to be sinking current.

To better understand what is happening here it's best to think of an I/O pin as a two-position switch:

When the I/O pin is HIGH point 1 is connected to point 2. When the I/O pin is LOW point 1 is connected to point 3.

So when HIGH the circuit is Vcc -> D1 -> R1 -> Vcc (or the other way around - I have done it that way because of the polarity of the LED), and no current can flow since it has nowhere that isn't at a lower potential than Vcc to flow to.

But when the I/O pin is LOW the circuit is now Vcc -> D1 -> R1 -> GND and so current can flow through it all to ground.  As a result the LED now lights up.

One thing you may have noticed now is that the operation is backwards.  Set the IO pin to LOW to turn the LED ON. That has the effect, as well, that PWM duty cycles are reversed.  analogWrite(ledPin, 0) will be full brightness and analogWrite(ledPin, 255) will be off.


Connecting two arduinos using WiFi I have two arduinos (An UNO R3 and a Mega 2560), and I need to communicate them via two ESP8266 modules to exchange some values.

In one arduino I'll use a SW-420 vibrarion module, and I need to send a value wirelessly to the other board, which it'll have an LCD screen that will display a message when a value is recieved.

How can I do that with that specific WiFi modules? Thanks in advance

Step 1: I would load NodeMCU on you ESP8266: https://github.com/nodemcu/nodemcu-firmware

Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en over serial connection

Step 3: write a TCP server:

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
  conn:on("receive",function(conn,payload)
    print(payload) //This payload will be send to your arduino over soft serial
    conn:send("<h1> Hello, NodeMCU!!! </h1>")
  end)
  conn:on("sent",function(conn) conn:close() end)
end)

Step 4: write a TCP client:

suc = false;
function sendData( host, pathData )
    suc = false;
    print("GoSending!");
    -- A simple http client
    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload)
        if(string.find(payload, "200 OK")~=nil) then
            suc = true;
            print("AllDone")
        else
            suc = false;
        end
    end)
    conn:on("connection", function(c)
        print("connected");
        conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n"
            .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
        end)
    conn:on("disconnection", function()
        if(suc==false) then
            print("ErrorSending")
        end
    end)
    conn:on("reconnection", function() print("reconnection") end )
    conn:connect(80,host)
end

Step 5: Connect your esp boards with software serial to the arduino

Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData)

Step: 7 Parse the Data on sofserial read on the second arduino

Step 8: DONE!

EDIT:

Ok more infos on step 6.
If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection.
So, this is some example code for your ardoino if you got the script from above:

SoftwareSerial wifi(3, 2); // RX, TX

//at some time in your programm
//Build up your string that will be send over serial
String i1 = "sendData(\"ipFromTheServer\", \"send.php?d=";
String i2 = i1+dataToSend;
String i3 = i2 +"\");";
wifi.println(i3);

This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)

More infos on step 7.
the script on top will always print all incoming data. So you just have to read serial data on wifi:

if (wifi.available())
    Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data!

Info: I've build this on my own... dont know if this is best practice :)


Arduino Uno unable to detect usb port on Mac OS Sierra 10.12.5 Few weeks ago my Arduino Uno (IDE version 1.8.2) detected the USB port and I was able to do some small IOT projects. I updated my OS to Sierra 10.12.5 and now suddenly the usb serial option has disappeared.

I followed this link : https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac  where it tells us to download and install the FTDI drivers separately. I tried that but it did not help.

Then I came across this post: https://forum.arduino.cc/index.php?topic=427825.0 where the user is having this same problem with MacOS Sierra. He suggested we remove the FTDI drivers and rely on Apple's drivers. So I removed the FTDI drivers from my Mac so it will use Apple's drivers.

Now even after doing all this when I connect my Arduino Uno to my Mac via the USB it does not get detected.

I removed the kext and pkg files for the FTDI drivers and deleted them completely, still when I open the System Report I still see the FTDI USB Serial Driver entry.

When I go to System Report > Hardware > USB I see this:

What is happening? Did the FTDI drivers got removed? If they did then why wont the serial usb port get detected on Arduino? If they are not removed completely then what did I miss?

I installed the CH340 Driver and the board now shows the USB serial as port option: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver


Hex/Byte Reversing and Conversion I'm working on an RFID system using a MFRC522 with this Library : https://github.com/miguelbalboa/rfid
Here's the code I have right now:

int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);

This results in the following output:

UID is 35 C5 5A 59

My issue is - how do I first reverse that UID : from 35 C5 5A 59 to 59 5A C5 35
- and second convert and print the corresponding decimal value of that reversed UID. In this case, it would be 1499120949.

I should mention that I need it as a string at the end to add it to the end of a POST command.

Your UID has 4 bytes, which correspond to 32 bits. To get a decimal value from these bytes, you have to put them together in one variable. For this you can use an unsigned long. To put the bytes together, you can shift the values to the byte boundaries:

unsigned long dec_value = (D << 24) | (C << 16) | (B << 8) | A;

<< shifts the bits of the byte by the specified amount of bits to the left; The bitwise OR | puts the now not overlapping bytes together in one value. I have reversed the order of the bytes in this code, as you wrote, that this is necessary.

To convert this unsigned long to a string you can use the function ltoa():

char buf[50];
ltoa(dec_value, buf, 10);  // 10 is the base value not the size - look up ltoa for avr

If you want to use a String object (which should be avoided because of heap fragmentation), you can contruct the String directly from the long value:

String my_UID = String(dec_value);


Platform-independent functions for FastPWM? I learned from answers here that pinMode(0, OUTPUT) is a platform-independent equivalent of DDRB = 1<<DDB0, on the ATTiny85.

Are there platform-independent functions for the following?

TCCR0A = 2<<COM0A0 | 2<<COM0B0 | 3<<WGM00;
TCCR0B = 0<<WGM02 | 1<<CS00;
TCCR1 = 0<<PWM1A | 0<<COM1A0 | 1<<CS10;
GTCCR = 1<<PWM1B | 2<<COM1B0;

Explanation of above code here. These calls enable FastPWM.

I checked the Arduino API reference, but not sure which are the equivalent to above. How to determine?

It is highly unlikely there would be direct 1:1 functions that implement such discrete operations. Simply because such operations are pretty unique to a single family of microcontrollers. They are too low-level for an API to even consider wanting them.

Instead, there are higher level functions which may, if the chip requires it, include those operations.

The operations you list are all related to PWM, so the higher level function that would encompass them would be analogWrite().


How does serialEvent gets into main()? Ok, serialEvent "runs after loop()" and it is not an interrupt.
AS far as I know main() has two functions  - setup and "infinite" loop.
So where does serialEvent comes in?

And if I do not want loop()  to run and use only setup than  I cannot use serialEvent.

Yes you are correct, the event handlers will not do anything in setup. Main runs "setup()", then loops infinity through "loop()", but gives the serial event handlers a chance to run in between. The actual main that runs on the arduino is this:

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

this is found (on linux at least) in arduino/hardware/arduino/avr/cores/arduino/main.cpp

"serialEventRun()" is in HardwareSerial.cpp, but is not very interesting.

To be clear, Serial itself will still work fine in setup(). If you want to use the same event handler function, all you have to do is call "serialEventRun()" yourself periodically.


Arduino Serial Monitor works but not on PySerial and PuTTY I made simple custom arduino board using an atmega328p and the PL2303 serial to USB chip.

In my arduino program, I am in a loop that sends out a string continuously. I can read this in the Arduino serial monitor with a baudrate of 9600. However, in my python program using the pySerial library, the readline function doesn't return anything. I checked using PuTTY but it still doesn't do anything.

Now I tried messing with the serial settings and found out that these lines of code work (the readline returns the string) if I call it in the exact same order.

ser = serial.Serial(comm_port)
ser.xonxoff = True
ser.rtscts = True
ser.dsrdtr = True
ser.readline()

However, the code below doesn't work

ser = serial.Serial(comm_port, xonxoff=True, rtscts=True, dsrdtr=True)
ser.readline()

What could be causing this? My guess is somehow I've switched the datalines in my USB cable and that the arduino serial monitor handles this somehow.

Another thing to note is that I couldn't program the Arduino the normal way via USB. I always have to program it using the ICSP port and a USBasp programmer.

I wrote a python application which communicated with an arduino and for some reason I had to insert a delay after opening the serial for it to work correctly, if I didn't the first data I sent would always get dropped. Perhaps that's what's occuring here? Setting the attributes of the serial connection like that is probably slower than doing it in initialisation.

For myself I found that a delay of 3 seconds was what I needed for it to work 100% correctly on all computers (on some a second was enough). You only had to wait after opening it once open it worked fine.

To do a delay import the time module and use the sleep function which takes an argument of seconds.

import time

time.sleep(3)

Also worth noting depending on your application it's worth setting a timeout value for the serial that's appropriate or just keeping it open with the timeout paramter.

 ser = serial.Serial(com, 115200, timeout=0)

If you do this make sure to close it when you finished with it though (I personally used a try finally block which makes sure its always closed).

try:
  ser = serial.Serial(com, 115200, timeout=0)
  #go nuts with whatever communicating your doing
finally:
  ser.close()

I'm afraid I can't really tell you what caused the issue though. I also realise that this question is quite old so I hope my answer is still helpful, if not to you then to someone else who stumbles across it. To note for future the people on the official Arduino forum may be of more help for arduino related questions in general.


Stop at the end of a track I would like to create a camera dolly for capturing timelapse movies.

i.e. something like this:
http://youtu.be/Qce1f6SKEMU

Whats a reliable way to detect the end of the track and stop the stepper motor moving the camera? In other words how is it possible to get the current position of the camera and stop the motor before the track ends to prevent crashing into the bumpers?

The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.

Printers have been doing it that way with their print heads for decades.

http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/


Analog INPUT_PULLUP for resistive sensors? Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between Ax and GND. Software is the same, except declaring Ax as INPUT_PULLUP instead of INPUT.

Can you use the internal pull-up on an ADC pin?

Yes.

  Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.

Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the DIDR0 and DIDR1 registers appropriately.


Uploading sketch to ESP8266 I'm managing to upload a sketch to the ESP8266 01. I have been researching on internet but I'm not able to get it.

I have installed the libraries for Arduino IDE and my circuit is the ESP powered by 9V converted to 3.3V using a LD 3.3 converter. I tested the voltages and works fine. Also the led in ESP is on (red).
To connect to the computer I'm using a TTL USB cable without vcc connected only for tx and rx.

The commands for the ESP works fine (AT commands), but when I try to upload a sketch it shown the following error:

  espcomm_open failed

I also have connected to GP0 (ESP) a button to ground. The circuit is:

9V battery --> 3.3V converter --> ESP---> TTL

Anyone knows about that error and why could be? Because the AT commands works fine. Maybe I need to provide more information but not sure.

My goal is to do this tutorial:
https://learn.adafruit.com/downloads/pdf/esp8266-temperature-slash-humidity-webserver.pdf

Another problem that I have following that tutorial is that in Arduino IDE, I cannot setup esptool as programmer, because isn't there. I loaded the same library for esp

Following on from user1637451 the following sequence has always worked for me:

Before download, pull both GPIO0 and RST to ground.
Release the pull down on RST, but keep GPIO0 low.
When the IDE has finished downloading, release GPIO0 from low.

I usually have pull-up resistors (10K) on both RST and GPIO0.

As to the IDE problem. I used the tutorial from Sparkfun entitled "ESP8266 Thing Hookup Guide" and then the section "Installing the ESP8266 Arduino Addon". Because I used a different ESP8266 board to them I set the IDE to use the "generic ESP8266 board". This worked for me.


ESP32 Dimmable LED Panel with MOSFET I want to use ESP32 to control and use a dimmer for 6 LED panels in my bedroom. The specification of each panel is mentioned in the diagram. Although in the diagram it shows ONLY 1 MOSFET and 1 LED Panel but in reality there are 6 LED Panels therefore I am guessing that each of the 6 LED Panel will need a separate MOSFET.

I would like to know:

What MOSFET (Part number or model number, company name,  etc) should I use for the above LED panel connected with ESP32 (I guess voltage of ESP32 is 3.3 v) ?
Will each LED panel need separate MOSFET (6 LED Panels will need 6 seperate MOSFET) or can 1 MOSFET be connected to all 6 LED Panel ?
If I am using 6 LED Panels what should be the specification of Power Supply (Voltage & Amps) ?
If I use 6 set of MOSFET & LED Panels, can all MOSFETs be connected to a single PWM pin in ESP32 or does each MOSFET needs to be connected to separate PWM pins in ESP32 ?
Is the above circuit okay, or would you suggest some other components to be added apart from MOSFET?
What will be connection between power supply, LED and MOSFET.
I am guessing that 'Positive of Power Supply --> Positive of LED Panel', 'Negative of LED Panel -->  Source of MOSFET' and 'Drain of MOSFET --> Negative of Power Supply'. Kindly correct me if I am wrong.

Thanks.

To add more information regarding the LED panel:

It is 15W LED Panel (note it is not LED Bulb or LED Strip).
Link to LED panel is 15W LED Panel

Below is the picture of Driver that came with the LED Panel, note the below driver is non-dimmable.

Kindly help.

Your plan has more flaws. First as Juraj wrote in a comment, you can't dim a switching power supply of the LED bulb. But this would not work as you plan even if you use a classic incandescent light bulb with AC. You can't control it with PWM. AC is dimmed with phase control, which requires a zero crossing detection to turn off power for part of the AC wave.


Sending Strings from NRF24L01 to app I want to send pushbutton status from the nrf24l01 module to the app named nrfConnect. I could only find libraries that allow me to send float values. How could I send String values to the app? Thank You!

nRF Connect is for Bluetooth LE devices, the nRF24L01+ is really not a Bluetooth Low Energy transceiver.
The best the nRF24L01+ can do is make a few Bluetooth LE advertisements but that's very finicky. Here's a long description how: https://dmitry.gr/index.php?r=05.Projects&proj=15&proj=11.%20Bluetooth%20LE%20fakery


Unable to connect Ethernet shield W5100 to localhost I have an Arduino Uno and a W5100 Ethernet Shield. I am trying to post some data from the Arduino board to the WAMP server running on my computer. I do not have a router so I have directly connected my Ethernet shield stacked onto the Arduino Uno to the laptop's Ethernet port via an Ethernet cable. I have also assigned the Ethernet connection a static IP address 192.168.0.1 and my localhost page opens when I put this address in my browser.

In my Arduino sketch I have assigned the Arduino shield an IP address 192.168.0.4, i.e. on the same IP segment. When I try to do client.connect to the server (192.168.0.1), i.e. localhost, I get "Connection failed".

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x6F, 0xED };
IPAddress ip(192,168,0,4);
byte server[]={192,168,0,1};

int value=9;
EthernetClient client;

void setup() {
  // Serial.begin starts the serial connection between computer and Arduino
  Serial.begin(9600);
  // start the Ethernet connection
  Ethernet.begin(mac,ip);
}

void loop() {
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    client.print("GET /Ethernet/getData.php?"); // This
    client.print("value="); // This
    client.print(value); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.1");
    client.println("Connection: close");
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server
  }

  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  delay(10000);
}

Now when I upload the sketch onto the board and run the serial monitor, I get this output:

My Ethernet connection detail screenshot is as follows:

Please tell me any changes that I must make and also are there any WAMP settings which I should change to allow the connection to get established?

Please consider the fact that I don't have a router anywhere in this connection - just my laptop and Ethernet shield connection.

After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.

Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.


Do they make 2.54mm 2P Crimpable Micro JST Female connectors? This may be a dumb question but I need some (preferably with wires already attached) and I'm unable to find any like this. Everything I find has male crimps and female surface mount. That doesn't work for very well with my project because I do not have room in my project box for another board. I'm already cramped just adding the headers that I was planning to solder these wires to.

Here is what I'm looking for in the 1.25mm variety:

I've found this product listing on Amazon:

2.54mm spacing JST extension cable.

It resembles the connector you've shown only slightly, but may be the only option out there.

And to contest the above statement, one that looks more like your objective:

Another 2.54mm spacing JST cable

There may be others. I used "jst 2.54 mm 2 pin female cable" as the search terms specifically in Amazon, other sources may have similar results.

Firing up the old Google again, using the last set of search terms, I've found an eBay listing:

eBay product listing

with the source in china. The photo appears correct, although the listing is for two cables, one male, one female, there is a third photo with the circuit board mount type connector.

This particular listing calls them a 2.5 mm connector, close enough? Perhaps a translation error.


Arduino Wire communication with MCP23008 GPIO pin expander to turn on an LED with a button press I am using an Arduino Uno and an MCP23008 GPIO pin expander, I have a momentary button connected to GPIO 2 on the MCP23008 and an LED light connected to GPIO 1 on the MCP23008. What I want is for the LED to turn on when the button is pressed down, and off otherwise. The code I currently have is this:

   #include "Wire.h"       //import Wire library
   byte inVal;             //declare byte variable

   void setup() {

      Serial.begin(9600);
      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x00);               //MCP23008 internal register addr for I.O.dir
      Wire.write(00000010);           //set all pins as output, except for #2 as input
      Wire.endTransmission();
    }

    void loop() {

      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x09);               //MCP23008 internal register addr for GPIO access
      //Wire.write(0xFF);             //set all output pins to HIGH, commented out for now.
      Wire.endTransmission();
      Wire.requestFrom(0x20,1);       //get one byte of input input from MCP23008
      inVal=Wire.read();              //set pyte as variable

      //Serial.println(inVal,BIN);    //output byte to serial monitor, commented out for now

      Serial.println(bitRead(inVal, 1)); //output second bit from byte(1 or 0, for HIGH or LOW, depending on the press of the momentary button.
      if((bitRead(inVal, 1)==1))      //if the bit from the button is high,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0xFF);             //then set all output pins as HIGH
        Wire.endTransmission();
      }

      else if((bitRead(inVal, 1)==0))  //if the bit from the button is low,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0x00);             //then set all output pins as LOW
        Wire.endTransmission();
      }
    }

I don't know as much Arduino as I do Python, and I have even less experience with i2c connections and the Wire library, but this looks to me like it should be working.

The bit printed on the serial monitor is HIGH, until I press the button once, then it stays LOW forever until I modify and re-upload the code to the Arduino.
Not sure what's going wrong here. Anything helps, thanks.

I see one major thing wrong at first glance:

  Wire.write(00000010);           //set all pins as output, except for #2 as input

That doesn't set GPIO 1 (which you call number 2 - counting starts at 0 not 1) to be an input, that sets GPIO 3 (number 4) as an input.  Numbers starting with 0 are octal, not binary. For binary the prefix is 0b:

  Wire.write(0b00000010);           //set all pins as output, except for #2 as input

And then you read using:

bitRead(inVal, 1)

which would have read GPIO 1 which is configured as an output.

So you have a switch on GPIO 1 which is an output, which you then drive high (causing a short internally which can damage the pin), and as a result you drive the pin HIGH internally. Now it's always high, so a read of the pin sees the HIGH you are driving from it. Hence it gets stuck at 1.

Fixing your IODIR write should help solve that problem.


(ultrasonic sensor code : No such file or directory) I'm beginning in Arduino I do not understand what the error means. Please tell me where I can find the resources to understand it and allow the code to compile.

#include <RCSwitch.h>
#include <Ultrasonic.h>

Ultrasonic ultrasonic(11,10);
RCSwitch mySwitch = RCSwitch();

int i;

void setup() {
    mySwitch.enableTransmit(4);
}

void loop() {
    i = ultrasonic.Ranging(CM);
    mySwitch.send(i, 24);
    delay(100);
}

  Arduino: 1.8.7 (Windows 7), Board: "Arduino/Genuino Uno"

  433mhz-lcd-water-level-transmitter:2:24: error: Ultrasonic.h: No such
  file or directory

  compilation terminated.

  exit status 1 Ultrasonic.h: No such file or directory

  This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

It means what it says:

  Ultrasonic.h: No such file or directory

The file Ultrasonic.h can't be found.

Anything in your code that starts #include... is usually a library. These are third party pieces of software that you have to obtain and install into the relevant location (See Installing Additional Arduino Libraries).

Some libraries are bundled with the IDE, and some are available through the "library manager" in the IDE. However most aren't, and you will have to get used to finding those libraries and installing them.

The location you got your example code from will most likely link you to where to find the relevant libraries to get the code working.


Conditional compilation depending on sizeof(double) Is there a macro (#define ...) somewhere in the bowels of Arduino IDE or core header files which tells me at compile time(!), if the double data type for a given platform/board is a true double precision floating point number (64 bit width) or "only" an alias for a single precision float (32 bit width)?
With Arduino, both can be the case. 8-bit AVR boards have double equal to float, ARM-based boards (like Arduino Zero) support "true" double precision.
I am working on a library which implements some bit-banging of floating point numbers (both single and double precision). Due to the low-level nature of the problem, there must be separate functions for float and double. I would like to do somthing like that:
uint32_t function_for_float(float f) {
    // function body here...
}

#if defined(HAS_64_BIT_DOUBLE)
uint64_t function_for_double(double d) {
    // function body here...
}
#endif

That way, a compile time error would be generated if somebody tried to use the "double" version on platforms which do not support the "true" double data type. I want the compiler error to be generated, because function_for_double() will do silently "the wrong thing" when fed a single precision float, leading potentially to difficult-to-debug problems.
Right now, I am defining a macro constant for every relevant board I own, like this:
#if defined(ARDUINO_SAMD_ZERO) \
 || defined(SAMD_FEATHER_M0_EXPRESS) \
 || defined(ADAFRUIT_FEATHER_M4_EXPRESS)
    #define HAS_64_BIT_DOUBLE
#endif

But this is ugly and not future-proof (new boards can/will become available...).
Any suggestions?

The double data type is almost universally 8-bytes long, so you could
simply
#if !__AVR__
# define HAS_64_BIT_DOUBLE
#endif

Gcc provides a more specific macro though: __SIZEOF_DOUBLE__, which
has the same value as sizeof(double). But I do not know whether it is
provided by other compilers.


Selected board depends on 'arduino' core (not installed) When I load the Arduino IDE with Board: Pololu A-Star 32U4 selected, I see:

The current selected board needs the core 'arduino:arduino' that is not installed.

I installed the board manually via these instructions.

When verifying the initial empty sketch, I see:

Arduino: 1.8.8 (Linux), Board: "Pololu A-Star 32U4"

The current selected board needs the core 'arduino:arduino' that is not installed.
/usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/ravi/Arduino/hardware -tools /usr/share/arduino/tools-builder -libraries /home/ravi/Arduino/libraries -fqbn=pololu:avr:a-star32U4 -ide-version=10808 -build-path /tmp/arduino_build_299010 -warnings=none -build-cache /tmp/arduino_cache_842714 -prefs=build.warn_data_percentage=75 -verbose /tmp/untitled689103723.tmp/sketch_feb05a/sketch_feb05a.ino

Selected board depends on 'arduino' core (not installed).

Error compiling for board Pololu A-Star 32U4.

How do I prevent this error and compile a sketch?

I needed to install the boards package for:

Arduino AVR Boards

Under Tools -> Board -> Board Manager


Push Button to Drive Power to Servo I am currently doing a project for a class which uses a few other components such as an LCD, a servo, and such. I want to use a button which acts as a circuit breaker on the Vin of the servo in which the servo will only be powered when the switch is pressed. I wanted to implement something like this because I wanted to minimize the power consumption and also acts as a mechanical counter-measure in case the servo keeps on spinning in unwanted situations, such as having the servo entangled by hair or something like that.

I know that I can just connect the button to the I/O pins but I wanted to rely on a hardware solution for power minimization and safety reason.

The servo draws 170mA when idle and can draw a maximum of 1.2A, but I believe it will only draw about 500-600mA with the intended load. It can run between 4.8-6V.

So my question is, would my circuit configuration work for my application? Would it be safe? Do I need any other additional components? Thanks for anyone that can help!

There is a chance that this arrangement could damage the servo and possibly the Arduino.  The problem is that, depending on the internals of the servo, it could try and draw power for the servo through the data pin when the button is not pressed.  This would both over-stress the internals of the servo and the internals of the Arduino's GPIO pin.

What you could do to mitigate that is to connect the servo's switched power to another GPIO pin of the Arduino, which is set as INPUT.  That will then tell the Arduino when the button is pressed and when it's not pressed. Then you use that information to attach and detach the servo in your code so it is only being actively driven when the button is pressed.


Brushless motor + ESC with Arduino question Sorry in advance as I'm still a rookie with Arduino projects. My goal is to use an Arduino Uno 3 to create an inexpensive drone/plane project.

Here are my materials and my set up:

A2212 1000kv Brushless Motor
HW30A Brushless Motor Speed Controller (ESC)
Arduino Uno R3
bunch of cables
9 V battery

Upon compiling the code I found here and connecting the 9 V battery to the ESC, all I hear is constant beep sounds from the motor (about once every 1.5 seconds). Can anyone help me figure out what's going on? Is it the 9 V battery that's not giving the motor enough juice? Or am I just too silly hoping to create something that works under $10?

#include <Servo.h>
Servo ESC1;

int pos = 0; //Sets position variable

void arm() {
  setSpeed(0); //Sets speed variable delay(1000);
}

void setSpeed(int speed){
  int angle = map(speed, 0, 100, 0, 180);
  //Sets servo positions to different speeds ESC1.write(angle);
}

void setup() {
  ESC1.attach(9); //Adds ESC to certain pin. arm();
}

void loop() {
  int speed; //Implements speed variable
  for(speed = 0; speed <= 70; speed += 5) {
    //Cycles speed up to 70% power for 1 second
    setSpeed(speed);
    //Creates variable for speed to be used in in for loop
    delay(1000);
  }
  delay(4000); //Stays on for 4 seconds
  for(speed = 70; speed > 0; speed -= 5) {
    // Cycles speed down to 0% power for 1 second
    setSpeed(speed); delay(1000);
  }
  setSpeed(0);
  //Sets speed variable to zero no matter what
  delay(1000);
  //Turns off for 1 second
}

Like the previous answer stated, you should be using a 20-25c battery (can discharge up to 25A). I don't know exactly how much a 9V draws, but it definitely can't supply more than an AMP. Your motor pulls much more than 1 amp. Get yourself a nice LiPo from hobbyking.com, maybe an 8.4v or 11.1v

The ESC beeping could be telling you it can't draw enough Amps from the battery?


ESP8266 seems to be bricked , how to recover? In a part of my sketch I put by mistake
pinMode(7,INPUT_PULLUP);
Which is dedicated pin for external flash chip (gpio7/SDIO_DATA_0/SPI_MISO) that not supposed to use for sketch. after uploading sketch now ESP is not responding to any further programming.

Could be Flash chip got corrupted due to the above mistakes?. Is it possible to recover?
I already bricked two of my modules with same sketch before identifying above mistake.
Sketch where working normal on Modules without above code.

When I connect to module with boad-rate 74880 chip returns
 ets Jan  8 2013,rst cause:2, boot mode:(3,7)
please check what happens when I try to upload the code upload error

No, you have not bricked your ESP8266 by turning on GPIO7's pullup.  All that will do is provide a weak pullup on the MISO line of the flash chip, which itself will have no effect - the flash chip's SPI Data Out pin will be able to easily override that weak pullup.

You can remove the flash chip and replace it with a completely blank brand new flash chip with nothing on it and still upload new code. There is nothing in the flash chip that the ESP8266 relies on to operate.

The boot sequence of the ESP8266 is as follows:

- Start executing the bootloader from the built-in ROM
  - Read the GPIO pins to determine code execution source
  - If flash is selected then initialize flash chip and read from address 0
    - Code on flash examines partition table to find code entry point
    - Jump to code entry point
  - If UART is selected then initialize UART
    - Wait for commands over the UART and respond accordingly

The startup code (boot stage 0) is in ROM. It's impossible to "brick" that.  All that is in the flash is the code that tells the ESP8266 how to find the user's code, and that gets flashed to the chip every time you reprogram it.

You can think of it like BIOS boot on a PC.  In the ROM is the BIOS that tells the CPU how to read from the hard drive. Then at the start of the hard drive is the code that tells the CPU how to load the operating system.  The hard drive doesn't come with that code on it - you install that along with the operating system. But the motherboard has the BIOS built into ROM which tells it how to get going and read that boot sector.

However it is possible to destroy an ESP8266 by connecting the wrong things up to it in the wrong way.  It is also possible to destroy some USB chips (the CH340G in particular) by wiring things up wrong.

So chances are that if you have bricked your ESP8266 it has nothing to do with your program and everything to do with what you have wired to it.


PWM using timer3 for servo control won't generate any output I'm making a program for a small robot arm controlled by four servos.
Problem: I need for PWM outputs, timer1 has three so i need to use timer3 for the last one

The main program and the timer1 outputs work great, the robot arm is functional. My problem is in the initialization of the PWM's. The PWM for timer1 is set to phase-correct, 64 pre-scaling and using WGM1[0-3] to 1010 so that i can use ICR1 as the top value, leaving OCR1[0-2] for counting up so output is on OCR[0-2].

According to the ATMEGA 2560 data book I should be able to initialize an identical PWM with timer3 with just one output in just the same way, but it just won't give me any output at all on OC3A.

Any help is greatly appreciated! :)

PS this is for a class project, so no servo libraries, and no major changes to the program (the current code is already approved by my professor, also the due date is in 24 hours so i don't have the time. Yes I know that sounds like trouble, but the project is technically done, I'd just really really like to get a full range of motion on my little Plexiglas robot)

PWM.c:

// INITIALIZE PHASE CORRECT PWM ------------------------------------------------------------------------------
void initPWM()
{
    DDRB |= (1<<DDB7);      // Output pin 5 OC3A
    DDRB |= (1<<DDB5);      // Output pin 11 OC1A
    DDRB |= (1<<DDB6);      // Output pin 12 OC1B
    DDRB |= (1<<DDB7);      // Output pin 13 OC1C

    // Initialize TIMER1 for OC1A, OC1B, OC1C:
    TCCR1A |= (1<<COM1A1)|(1<<COM1B1)|(1<<COM1C1)|(1<<WGM11);     // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
    TCCR1B |= (1<<WGM13)|(1<<CS11)|(1<<CS10);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal
    // Initialize TIMER3 for OC3A
    TCCR3A |= (1<<COM3A1)|(1<<WGM31);                            // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
    TCCR3B |= (1<<WGM33)|(1<<CS31)|(1<<CS30);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal

    // TIMER1 Top and bottom value:
    ICR1 = 5000;
    TCNT1 = 0;
    // TIMER3 Top and bottom value:
    ICR3 = 5000;
    TCNT3 = 0;

    // Start PWM in OCR = 200 (mid value for servo)
    OCR3A = 200;
    OCR1A = 200;
    OCR1B = 200;
    OCR1C = 200;

}

I can see nothing wrong in your program except this:

DDRB |= (1<<DDB7);      // Output pin 5 OC3A

This is setting pin PB7 as an output, whereas
digital pin 5 (OC3A) is PE3.


Is there a way to detect if Arduino, Stino or another IDE/toolchain is in use? I've noticed some irritating differences between the Arduino IDE and Stino (mainly around including certain header files). These are likely bugs that need following up with one or both of the parties, but in the meantime, I would like my code to compile with both of them without editing. This is because I do not want to lock any users out of using my code.

Are there any macros or similar that are readily available (as in, require no modification of the toolchain or IDE) that would allow me to detect which is in use?

For example, in many libraries, there is this snippet:

#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

However both Stino and Arduino define this.

As Stino claims to use the installed Arduino IDE you already have, which means you can not differentiate at compile time.


GSM GPRS for sending an sms I want to know if it is possible to send an SMS from a SIM900 using Arduinos to another SIM900.

Problem: When the gsm is connected to the network, it does not send an sms; my airtime balance remains the same.

Here is the code I used:

#include <SoftwareSerial.h>
SoftwareSerial SIM900 (9,10);

void setup()
{
   serial.begin(9600);
   SIM900.begin(9600);
   delay(5000);
}

void loop()
{
   sendSMS();

   while(SIM900.available()!=0)
     {
        Serial.println(SIM900.read());
     }
}

void sendSMS()
{
    SIM900.println("AT+CMGF=1\r");
    delay(100);
    SIM900.println("AT+CMGS=\"+27769384488"\r");
    delay(100);
    SIM900.println("Hello");
    delay(100);
    SIM900.println((char)26);
    delay(100);
    SIM900.println();
    delay(5000);

}

Yes, it is possible.

Your code doesn't show any sign of board powering on and initialization.

SIM900 has some LED that show status - make sure you are connected to GSM network.

Please check this tutorial: https://www.youtube.com/watch?v=RUGV_64lQX8


How does Yun identify itself to Windows? When I plug in my Yun, Windows pops up a box saying Windows needs to install driver software for your Arduino Yun.

What does Windows use to identify my device as an Arduino Yun? Is it written in a file somewhere, so I could for example, remove that driver prompt, or change it to Windows needs to install driver software for your Foo Bar?

It is written in what is called the USB String Descriptor.  I don't have my Yun to hand right now (it's acting as a wireless bridge temporarily), but all USB devices have these USB String Descriptors.  Here's an example for the Leonardo (which you can easily inspect on Linux):

$ sudo lsusb -v -d 2341:0036

Bus 001 Device 015: ID 2341:0036 Arduino SA
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass            2 Communications
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x2341 Arduino SA
  idProduct          0x0036
  bcdDevice            0.01
  iManufacturer           2 Arduino LLC      <<== String descriptor ID 2
  iProduct                1 Arduino Leonardo <<== String descriptor ID 1
  iSerial                 0
  ... etc ...

Internally the strings are stored as an indexed table - there's two there, ID 1 and ID 2.  The Device Descriptor then has a couple of bytes in it that says "The manufacturer is string ID 2, and the product name is string ID 1".  The operating system then requests those string descriptors so it can display the friendly message for you.

If you want to change that name you basically have to both re-program the bootloader (which has the USB descriptors when in program upload mode) and the Arduino core (that has the string descriptors programmed into it).


How to connect MPU9250 with NodeMCU using SPI or I2C Slave? I want to connect 3 MPU9250 sensors, but since there is just one I2C bus, so there are another 2 sensors I want to connect through SPI.

Library used - https://github.com/bolderflight/MPU9250/blob/master/examples/Basic_SPI/Basic_SPI.ino

There is an SPI example code written, but I don't know about the connections. There are no MISO and other pins on the sensor which i use but its SPI compatible. How do I connect 2 MPU9250 to NodeMCU with SPI?

If SPI connection is not possible then please post about I2C slave connection.

If you want to use SPI-
The homepage of the library you mentioned, clearly explains the circuit connections.-
The MPU-9250 pins should be connected as:

VDD: this should be a 2.4V to 3.6V power source.
GND: ground.
VDDI: digital I/O supply voltage. This should be between 1.71V and
VDD.
FSYNC: not used, should be grounded.
INT: (optional) used for the interrupt output setup in
enableDataReadyInterrupt and enableWakeOnMotion. Connect to
interruptable pin on microcontroller.
SDA / SDI: connect to MOSI.
SCL / SCLK: connect to SCK.
AD0 / SDO: connect to MISO.
nCS: connect to chip select pin. Pin 10 was used in the code snippets
in this document  and the included examples, but any digital I/O pin
can be used.
AUXDA: not used.
AUXCL: not used.

Each sensor's nCS (chip select pin) needs to be connected to a slave select pin (any digital pin) on the NodeMCU. This allows the NodeMCU toselect which sensor it wants to talk to.
Another easy way of connecting multiple sensors with the same I2C address is by using an I2C multiplexer like the Adafruit TCA9548A

This would allow you to connect up to 8 sensors having the same I2C address. Here's a youtube video explaining how to do so.
However, if you just want connect two MPU9250s, you dont need to do any of this, as the board offers two unique addresses via the AD0 pin-

0x68 if AD0 is grounded
0x69 if AD0 is pulled high


Recognition of the signal duration from the sensor Good afternoon!
I create a human movement alarm.
I am signaling atmega328. I receive a signal from the sensor and if there is a signal, then using the "tone" I generate a sound.

I am using a motion sensor. I want that if one movement was noticed for a short time, then turn on a short melody, and if the movement continues longer than a certain time, then play a long melody.
I wrote the code to play a short melody. How can you track that the input from the sensor is at a high logical level for a long time and play a long melody in this case?
unsigned long timing; // Variable to store the starting point
int T = 15; // Signal playback time!
int S0 = PIND0; // With Doppler Probe

int S1 = PIND1; // Food
int S2 = PIND2; // Audio

void setup ()
{

  // Port control via registers:
  DDRD = B00000110; // Set the output pin (the first and second pins of register D as output pins, the rest (0.3-7) are set as input pins)
  // 76543210
  pinMode (PIND0, INPUT);
  pinMode (PIND1, OUTPUT); // Power for the audio amplifier
  pinMode (PIND2, OUTPUT); // Audio
}
void loop ()
{
  if (digitalRead (PIND0))
  {
    sendSignal ();
  }

  if (digitalRead (PIND0) == 0)
  {
    digitalWrite (PIND1, LOW); // Food
    digitalWrite (PIND2, LOW); // Sound
  }
}

void sendSignal ()
{
  digitalWrite (PIND1, HIGH); // Food
  for (int n = 0; n <4; n ++)
  {
    for (int i = 4800; i <5800; i ++)
    {
      tone (PIND2, i, 10); // tone (port, frequency in Hz, duration in ms) 600 - 6 sec.
    }
  }
}

And yes, if my code can be optimized, tell me how!

I don't see where you are even attempting to detect the long condition in your code.
First of all you need determine what constitutes a long vs. a short detection.  My recommendation is to write your code to do the following:

Initial detection.
Wait for your "short" interval.  If the detection is gone, then you know it was a "short" one and you can play your short music.
If the detection is still there, wait for the remainder of the time for your "long" detection.
If the detection is gone you know it was a "short" one since it didn't make it to the "long" state.  So play your "short" song.
Play your "long" music since the detection lasted for the duration of the long interval.

I'll leave the actual coding of that to you.  I'll also add that doing it this way, that is using the built-in delay() function is probably not the best approach overall.  The issue is that delay() blocks your loop() function and prevents you from doing anything else while it's delaying.
A better approach is to implement this as a state-machine coupled with an timer-driven interrupt.  That will give you much better control over your detections and also allow you do handle other inputs or set other outputs while you are waiting for detections to occur.
There are many resources online that discuss how to configure and handle AVR timers and their interrupts and there are also many resources discussing state machines and programming them in C.


How to insert a power button on Arduino Nano I've an Arduino Nano to which a Micro Servo 9g is connected. The Arduino board and consequently the servo are powered by a USB powerbank connected to the board with a USB mini cable.

My question is: Is there a way to insert a power switch so I can turn on/off the board without plug/unplug the USB (that now is the way I use) ?
I was thinking to cut the USB cable and work with the positive of it but if someone has an alternative or any tips I'd really appreciate it. Thanks!

EDIT: If is needed I could make a wiring diagram.

Cutting a usb wire would be the easiest. Otherwise you'd have to cut traces in the pcb and attach wires. Not recommend for beginners. You can actually buy usb cable with a switch.

Another alternative would be to put the microcontroler in sleep mode and have it use very little power.


Estimating CPU load of a task scheduler First off, I should note that I'm not sure what tags best apply here, and I can't seem to find any that relate to schedulers, etc. Please inform me if they are not the right ones.
I have a simple, portable task scheduler (it only relies on millis(), and runs on different Arduino-supported systems) that is called via a function in loop() and that picks and then runs a function pointer (the "task") from a list of tasks with status, sleep, and priority information.
I would like to have a way to determine and to tell the user how much CPU time is being spent on running tasks vs. being idle.
The problem is that there can be other functions being called from loop(), not just my scheduler. It would thus be a bad idea to track total time vs. time spent in a task. If I did, the CPU use would always read low, since the actual task time cannot use all of the CPU time since the other tasks in loop() would be quietly using some of it.
However, if I specifically track time in the scheduler vs. time spent in task, I run into a new issue. I would use more memory (a few more bytes, but I'm using a lot already...) and more CPU*, since I'd have to keep track of the total so far and also the current runtime for that iteration of the scheduler. That's on top of the similar construct determining the runtime of the task. Mainly, though, the issue is that the loop() function and scheduler run fast enough that the millis() timer can tick slower than the changeover between my scheduler and the loop() function. This causes the timing to also be off, since it would be counted if it ticks in the scheduler even if it was mainly loop()'s fault.
Is there a general methodology for computing the CPU time? It would be difficult to time-slice the scheduler, and that would run slower anyway. I could count the proportion of scheduler calls that run/don't run tasks, but that won't work because tasks take longer than the no-op that happens if a task doesn't run, and it makes no accounting for task length.
*On an AVR system, the 8-bit CPU uses a surprising aggregate time on all those 32-bit operations, between the sleep time calculations (on sleeping tasks only, to be fair) and the elapsed time calculations that fed into my prior CPU use attempt. It wasn't the only cause, but I saw quite a bit of timing slip on one attempt of coding the scheduler because of a similar issue.

The only metric you have is time. The only thing you can do is compare that time over iterations / task calls. The typical approach is to note the time at the start of a task "tick", and note it at the end. Then add the difference to the total for that task.
When you want to then look at usage percentages you can compare those totals to the total time the system has been running.
The total runtime is already done for you, in the form of millis(), so you don't need to worry about that.
Recording each task's total runtime in microseconds is simple enough, but of course will entail an overhead. That is unavoidable no matter what strategy you take. It's kind of quantum: the act of measuring changes the results.
If you treat your "idle" task the same as any other task (which is the normal way of doing things - the idle task is just a task that does nothing) then the sum of all the time counts for all the tasks = (within a certain granularity) the total amount of time your task scheduler has been running. The difference between that and the system runtime (millis()) is the proportion of the time your scheduler has been running compared to other things happening in loop().
Whether you compare to millis() or micros() for the system runtime is up to you. By storing micros() per task you're getting a reasonable resolution for each tasks's runtime (but with a limit to how long before it wraps - but you can handle that in software by carrying over to another lower resolution counter if you want), but you can then discard some of that resolution when doing your calculations if you don't need it at the time.
Estimating runtime in a co-operative multitasking system like this is never good, and often not bothered with because of that. It's always a guestimate with the results being skewed by the measuring, since the measuring is synchronous with the execution of the tasks.
In a proper context-switching multitasking system you would normally operate on the number of "ticks" of the system rather on time. That is, simply count 1 each time a task is switched in by the context switcher. Since each task has a fixed runtime controlled by the granularity of the scheduler it's then trivial to know that task X has been running for X/TOTAL_TICKS % of the time. Any calculations will be themselves done in a task - maybe the idle task, or a system accounting task.


WifiManager and WiFi functionally I’m considering using wifiManager mostly to have the ability not to hard code WiFi creditntials.
But In my current code I use WiFi’s functions as WiFi.setAutoReconnect(true) and WiFi.status() != WL_CONNECTED

How can it be done using WifiManager?

You don't. WifiManager does all that for you. You don't need anything like that in your code. Just follow the examples and read the documentation.

But if you do want to then you just need to remember that WifiManager is merely a library that configures the WiFi for you. If you want to query or alter the WiFi settings you can - exactly as you are right now. The two aren't mutually exclusive.


How to send the MFRC522 RFID module into sleep mode? I'm trying to get the power consumption of a MFRC522 RFID module down, currently while running it consumes about 4mA. There should be a way to put it into sleep mode, I just can't find any documentation on it. I'm using the module with a arduino currently if that helps; and this is the module itself : MFRC522

http://www.nxp.com/documents/data_sheet/MFRC522.pdf

Look at section 8.6.2   Soft power-down mode.


Generate single pulse from timer 1 in arduino nano i have a code that shot a single pulse from pin D5 timer 0 (based on josh levine code), it works fine. the code is below

#define OSP_SET_WIDTH(cycles) (OCR0B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR0B =  0;
    TCNT0 = 0x00;
    OCR0A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR0A = _BV(COM0B0) | _BV(COM0B1) | _BV(WGM00) | _BV(WGM01);
    TCCR0B = _BV(WGM02) | _BV(CS00);
    DDRD |= _BV(5);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT0 = OCR0B - 1)
#define OSP_INPROGRESS() (TCNT0>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR0B=m;TCNT0 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

however, i want to generate the same pulse in pin 10 or 9 which is timer 1, so a change the code a bit just like this

#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1B =  0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(CS10);
    DDRD |= _BV(10);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

but it doesn't work, and i am stuck, any help? i use arduino nano

Thank you

Timer1 has a few extra features, so you need to set the registers slightly differently from timer0 (or timer2). You need to also set the WGM13 bit in the TCCR1B register.

Since timer1 is a 16 bit timer, you need to change OSP_SET_AND_FIRE to also use 16 bits.

Lastly; Arduino pin 10 is port B, not port D.

#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10);
    DDRB |= _BV(DDB2);//pin 10; PB2
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}


How to get current WiFi signal strength? I have a LCD display where in I'm displaying a WiFi signal logo. I want to reduce the number of bars on the logo, indicating that the signal strength is dropping. I got the reducing bars on the LCD completed, I still have to find out the actual signal strength.
How do I find the signal strength of the connected network with ESP8266 based NodeMCU?

You use WiFi.RSSI():

RSSI
Return the signal strength of Wi-Fi network, that is formally called Received Signal Strength Indication (RSSI).
WiFi.RSSI()

Signal strength value is provided in dBm. The type of returned value is int32_t.
Example code:
Serial.printf("RSSI: %d dBm\n", WiFi.RSSI());

Example output:
RSSI: -68 dBm


Toggle a led with a switch My code:

const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool buttonState = 0;         // variable for reading the pushbutton status
bool ledState = 0;
void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
  buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
 {
  ledState = !ledState;
 }
  if (ledState == HIGH)
 {
   digitalWrite(ledPin, HIGH); // turn LED on:
 }
   else
 {
    digitalWrite(ledPin, LOW); // turn LED off:
 }
}

So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?

If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:

pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

Also, you need to debounce the button.


Significant drop in speed between Arduino IDE and Visual Studio? So, I'm not sure what is causing this, but maybe I'm overlooking something simple. I have a simple program designed to read the analog input at 640 Hz, it looks like this:

int Ch0 = 0;
int count = 0;
unsigned long startTime;
unsigned long currentTime;
bool startedReading = false;

void setup() {
  //set up pin(s)
   pinMode(Ch0, INPUT);

  //begin serial at 115200bps
  Serial.begin(115200);
}

...

//if the current time exceeds the start time by one second, set the start time equal to current time, print the count, set count equal to zero
if (currentTime - startTime >= 1000) {
  startTime = currentTime;
  Serial.println("time");
  count = 0;
}

//read input, delay some microseconds as a means of controlling sampling rate, bring count up by one
//should read somewhere along the lines of 640-ish Hz
analogRead(Ch0);
delayMicroseconds(1230);
Serial.println(count);
count++;

And this all works fine and dandy in the Arduino IDE, I pull up the Serial Monitor, and it prints every number 1-640 and then says time, with good consistency. Yet, when I open up a Visual Studio program and call the command:

EDIT: Added entire data received event method

private: System::Void serialPort1_DataReceived(System::Object^  sender, System::IO::Ports::SerialDataReceivedEventArgs^  e) {
    if (!this->reading) return;
    else
    {
         try
         {
            //get incoming port and read
            SerialPort^ sp = (SerialPort^)sender;
            String^ sInData = sp->ReadLine();
            //parse read data
            double inData = double::Parse(sInData);

            //write data to debugger for testing
            Debug::WriteLine(inData);

            //start populating the "in" array
            AppendIn(inData);
          }
          catch (Exception^ e)
          {
            Debug::WriteLine(e->Message);
          }
    }
}

Aside from the obvious error that occurs when I try to parse the string "time" to indicate when 1 second has elapsed, everything works fine. Except for the fact that the numbers feed into the debugger very slowly. As in, it'll take roughly 4-5 seconds to read through all 640 reads of the count integer and then it throws the time at me. Thus, this leads me to conclude that Arduino is indeed calculating that 1 second has elapsed and then sending that over, but the output is essentially the same, the only difference being that the message takes exactly 1 second to read on the Arduino IDE and over 4 seconds to read in real time in Visual Studio.

Maybe it has something to do with the way I'm reading the data in VS? I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial. No data at all is being lost, it's just very slow...and only in VS. Thanks in advance for any help you can give, but I'm at a bit of a loss.

I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial.

I suspect that is the issue. Waiting for an incoming "serial data available" event and then processing it, is likely to be slow. I would rework how you get serial data. You haven't shown that bit but maybe you can use a larger buffer.


object with multiple instances with internal data store separate for each instance I'm trying to keep track of a timer, and the internal variables seem to be overrun by one another.

I just want two instances of the Output class, which can keep track of the _elapsed_time so I can check if the time elapsed. It's a poor-man's real-time for a game. I know there are libraries available and I'm planning to use them, but I would really appreciate knowing what's going on here: I want a buzzer pin, and status led pin to 'blink' at different intervals. They both work individually, but when I have them both uncommented they work somewhat serially...

#include "Arduino.h"

#include "MTC.h"

#include <SoftwareSerial.h>   //Software Serial Port

//HARDWARE SETTINGS
#define PIN_STATUS                  13
#define PIN_BUZZER                  A2

Output *STATUS(0);
Output *BUZZER;

void setup()
{
    Serial.begin(9600);
    STATUS = new Output();
    STATUS->Begin(PIN_STATUS, STATE_OFF);
    BUZZER = new (Output) Output(3);
    BUZZER->Begin(PIN_BUZZER, STATE_OFF);
}

void loop()
{
    static bool run_once = true;

    if (run_once == true)
    {
        run_once = false;
        Serial.print("Running");
        Serial.flush();
    }
    delay(250);

    //Serial.println("still running");

    STATUS->SetStrobe(3000);

    //BUZZER->SetStrobe(4000);

}

and class:

#ifndef MTC_h
#define MTC_H

typedef int OUTPUT_STATE;
OUTPUT_STATE STATE_OFF = 0;
OUTPUT_STATE STATE_ON = 1;
OUTPUT_STATE STATE_STROBE = 2;

class Output
{
private:
    int _pin;
    OUTPUT_STATE _last_state;
    unsigned long _cycle_duration;
        unsigned long _last_elapsed;

public:
    Output();                                           //constructor: set pin data store
    void Begin(int pin, OUTPUT_STATE state);                                //set hardware to output and defaul state
    void Set(OUTPUT_STATE state);                               //toggle operability
    void SetStrobe(unsigned long duration);                     //strobe operability
};

Output::Output()                                    //constructor: set pin data store
{

}

void Output::Begin(int pin, OUTPUT_STATE state)
{
    _pin = pin;
        _last_elapsed = millis();
    pinMode(_pin, OUTPUT);
    digitalWrite(_pin, state);
    _last_state = state;
}

void Output::Set(OUTPUT_STATE state)
{
    if (_last_state != state)
    {
        digitalWrite(_pin, state);
        _last_state = state;
    }
}

void Output::SetStrobe(unsigned long duration)
{
    static OUTPUT_STATE _last_strobe_state = STATE_OFF;

    unsigned long elapsed = millis() - _last_elapsed;
    if (elapsed >= duration)
    {
        if (_last_strobe_state == STATE_OFF)
        {
            digitalWrite(_pin, STATE_ON);
            _last_strobe_state = STATE_ON;
        }
        else
        {
            digitalWrite(_pin, STATE_OFF);
            _last_strobe_state = STATE_OFF;
        }
        _last_state = STATE_STROBE;
        _last_elapsed = millis();
    }
}
#endif

Your Output::SetStrobe() is wrong, it uses a static variable (_lasr_strobe_state) that is thus shared between all instances of OUTPUT, which is NOT what you want.

You have to change it into a non-static member of class Output instead:

class Output
{
private:
    int _pin;
    OUTPUT_STATE _last_state;
    // NEW member here!!!
    OUTPUT_STATE _last_strobe_state;
    unsigned long _cycle_duration;
        unsigned long _last_elapsed;

public:
    Output();     //constructor: set pin data store
    void Begin(int pin, OUTPUT_STATE state);//set hardware to output and defaul state
    void Set(OUTPUT_STATE state);            //toggle operability
    void SetStrobe(unsigned long duration);  //strobe operability
};

Then you initialize it in the constructor:

Output::Output():_last_strobe_state(STATE_OFF)
{

}

And you remove it (static declaration) from method SetProbe (the rest of the method does not change):

void Output::SetStrobe(unsigned long duration)
{
    unsigned long elapsed = millis() - _last_elapsed;
    if (elapsed >= duration)
    {
        if (_last_strobe_state == STATE_OFF)
        {
            digitalWrite(_pin, STATE_ON);
            _last_strobe_state = STATE_ON;
        }
        else
        {
            digitalWrite(_pin, STATE_OFF);
            _last_strobe_state = STATE_OFF;
        }
        _last_state = STATE_STROBE;
        _last_elapsed = millis();
    }
}


Initializing Array of structs I defined myself a struct:
typedef struct {
  unsigned char current;
  unsigned char start;
  unsigned char target;
  unsigned long startTime;
  unsigned int duration;
} led;

I was able to initialize an instance of that like this:
led h_red = {0,0,255,0,300};

However, when I try to have them in an array:
led leds[LEDS];
leds[0] = {0,0,0,0,0};
leds[1] = {0,0,0,0,0};
leds[2] = {0,0,255,0,300};

I get this error
signal:28:1: error: 'leds' does not name a type
 leds[0] = {0,0,0,0,0};
 ^~~~
signal:29:1: error: 'leds' does not name a type
 leds[1] = {0,0,0,0,0};
 ^~~~
signal:30:1: error: 'leds' does not name a type
 leds[2] = {0,0,255,0,300};
 ^~~~

And I have no idea what I'm doing wrong here. You can see the full change here on GitHub

led h_red = {0,0,255,0,300};

Here, you are defining a variable, and at the same time giving it an
initial value. This is called an initialization.

led leds[LEDS];

Here you are defining an array. Since it is in global scope, and not
explicitly initialized, it is implicitly initialized to all bytes zero.

leds[0] = {0,0,0,0,0};

Here, you are trying to give a value to an element of the array that has
already been defined previously. This is thus not an initialization,
but an assignment. Unlike initializations, assignments cannot exist
outside a function. If you want to assign initial values, you can do it
in setup().
Alternatively, you can initialize the array while you define it:
led leds[LEDS] = {
    {0, 0,   0, 0,   0},
    {0, 0,   0, 0,   0},
    {0, 0, 255, 0, 300}
};


changing bitrate of audio recording and taking samples from audio in arduino I am looking to make a baby cry detection module that is a part of a bigger project i.e. IOT based baby monitoring system. Using AI, i have a dataset (of baby crying and not crying) to train model using binary classification through logistic regression. The problem is that the dataset has a 10kbps sample rate. and arduino records audio on 192kbps probably. so i need the arduino recorded audio to be 10kbps. secondly i need 100 weights or samples from the arduino recorded audio. so lets say the audio is of 5 seconds, so i need a sample after every 50ms so that the total samples would be 100. the main problem is i don't know how to take samples from an audio being recorded or a prerecorded audio using arduino. The 100 samples would then be multiplied by the 100 samples from the trained model and then added and then sigmoid function will be used so that at the end we can know whether the baby is crying or not. All the deployment of the model will be done in arduino. Any help regarding taking the samples or bitrate, would be much appreciated. Thanks in advance! :)

First of all, I am pretty sure your idea of using discrete ADC samples
as predictors for your model is hopelessly naive. As explained by
Majenko, you cannot expect anything meaningful from a sound recording
taken at 20 samples per second. You may have more luck using
spectral intensities as predictors. I suggest you start by doing some
time–frequency analysis on your training data, just to get some ideas on
what predictors may be worth trying. In any case, I strongly suggest you
train and test your model on your computer, before committing any
code to the Arduino.
That being said, sampling a signal at 20 Hz is quite easy: wait for
50 ms (or 50,000 µs for better accuracy), take one sample,
repeat. The only caveat is that you have to use millis() or micros()
rather than delay() or delayMicroseconds(), otherwise the sampling
period will be longer than expected because of the time needed to
execute the code.
Applying the sigmoid function just to compare the result to 0.5 makes
little sense. You know the sigmoid is larger than 0.5 only when its
argument is positive, so you can trivially save yourself expensive
floating point operations.
Here is a tentative implementation of (my understanding of) the idea you
suggest:
const uint8_t mic_pin = A0;
const size_t sample_count = 100;
const uint32_t sample_period = 50000;  // 50,000 us = 50 ms
const int weights[sample_count] = { 12, -42, 23 /* etc... */};

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

void loop() {
    // Record the samples.
    int samples[sample_count];
    uint32_t last_sample = micros();
    for (size_t i = 0; i < sample_count; i++) {
        while (micros() - last_sample < sample_period) { /* wait */ }
        samples[i] = analogRead(mic_pin);
        last_sample += sample_period;
    }

    // Compute the weighted sum.
    long sum = 0;
    for (size_t i = 0; i < sample_count; i++) {
        sum += (long) samples[i] * weights[i];
    }

    // Predict.
    if (sum >= 0) {
        Serial.println("The baby is crying!");
    }
}


What is difference between NodeMCU and esp8266? Since I have no previous experience in electronics I'm getting quite confused while coming across these two terms ..I'd like to know whether they're the same or different.

From https://forum.arduino.cc/index.php?topic=616324.0:

  NodeMcu is the name of the firmware originally for the ESP8266
  microcontroller, with support for the ESP32 microcontroller added more
  recently, that allows you to program these microcontrollers using the
  Lua programming language.

  NodeMCU firmware was developed so that AT commands can be replaced
  with Lua scripting making the life of developers easier. So it would
  be redundant to use AT commands again in NodeMCU.

And ESP8266 is one of the microcontrollers supported by the NodeMcu firmware.

From NodeMcu vs Esp32 vs esp8266

  In the early days of the hobbyist community's adoption of the ESP8266,
  ESP8266 development boards were marketed with the name NodeMcu and the
  term "NodeMcu" started to be associated more with the hardware than
  the firmware. It is common for people with no interest in the Lua
  programming language to buy "NodeMcu" boards and program them with the
  Arduino IDE, which erases the NodeMcu firmware from the board. To make
  things more confusing, multiple companies marketed boards with the
  name "NodeMcu", but with small hardware differences. Over time, the
  NodeMcu boards became less popular in the Arduino world because the
  similarly priced WeMos D1 Mini came out with the same functionality,
  but in a smaller form factor. Now, the "NodeMcu" name is being used to
  market ESP32 boards as well.


Using bitRead to toggle between LEDs How can I use bitRead() to toggle between 3 LEDs?
I have 3 LEDs - red, green, blue - and I have these 4 stages:

Red ON and green, blue OFF
Green ON and red, blue OFF
Blue ON and red, green OFF
All OFF

and repeat.

To toggle LED you can do:

uint8_t BITval=1; //initialization B00000001

void toggle()
{
 digitalWrite(RED_pin,BITval&1);    //Bxxxxxxx1
 digitalWrite(BLUE_pin,BITval&2);   //Bxxxxxx1x
 digitalWrite(GREEN_pin,BITval&4); //Bxxxxx1xx

 BITval=BITval<<1;
 if (BITval== B00010000) //reset BIT value
    BITval=1;
}

And assuming you want to do bitRead() to read input from active-low push button which is connected to PORT-x, PIN-y

you can do:

if (bitRead(PORTx,PINy))==0)
toggle();


State machine sketch to drive a DC motor with limit switches I have a DC motor that will need to use two limit switches to detect end of travel in two directions.

I've read that coding a state machine to do this task is the best method, however I have no idea where to even begin.

Below you'll find a fritzing sketch of my experimental configuration for the code once implemented, and a flow chart.

You have created a flow chart.  When discussing state machines it is better to use a state diagram.

In this state diagram of a turnstile (from the state machine wikipedia page linked to above) it is observed that the nodes (bubbles) contain the state of the turnstile and on the edges (arrows) is written the condition required to travel in the direction of the arrow to a new state.

For the question asked here, at least 2 nodes are needed to state the direction of the motor.  The edges likely will state which arrow is to be used to travel to a new state based on which switch is open or closed.  Later, consider adding a new state to stop the motor once an end switch is closed. (Hint: Likely, you will need 2 stop nodes.  One for each end-stop switch.  The reason being you will need to know which direction the motor is to turn when restarted.)

For certain cases, adding a momentary contact switch is complex due to the need to mitigate the contact bounce.  This is true when the meaning of activating the switch changes.  The end-stop switch meaning does not change so there is no need to mitigate the contact bounce or "debounce" the end-stop switches.  However, it is assumed the "Cycle Switch" can start the motor spinning in different directions depending on the history of the motor movement.  Therefor the "Cycle Switch" can benefit from a 4 node state machine where there is clearly nodes which output switch-closed and switch-open.  But to get to either of these 2 nodes there needs to be 2 other nodes where the switch "debouncing" is handled.

When handling multiple state machines in one program it is important not to block the flow.  All state machines need to be continuously checked for state chances (testing the edge conditions for traveling from the current node to a new node).

When writing for an Arduino (in C / C++), the code pattern most often used is a "case" statement (switch / case) where a variable is assigned numbers associated with different nodes.  In such a code pattern, each "case" is a node which contains the edge test(s) and can assign a new value to the variable to switch to a new node ("case") if any of the edge tests are true.

Simplifying the design:  If you do not plan on stopping the motor then you do not need to "debounce" the "Cycle Switch".

Here is why: The meaning of the "Cycle Switch" changes from push-to-start to push-to-stop should you want to stop the motor between the 2 stop-switches.  If all you need is to start the motor after either of the stop-switches are closed, then the number of times the "Cycle Switch" bounces is irrelevant as long as the bounces do not continue for longer then it takes for the motor to reach the opposite stop-switch.