After studying the datasheet differences between MCP41100 (digital pot used in the tutorial) and MCP4131 (the one you get), I found two major differences between both:

Difference in resolution:

MCP41100 has 257 steps resolution (8 bits + 1): you can see that at the beginning of its datasheet
MCP4131 has only 129 steps resolution (7 bits + 1): you can get this information on page 2 of its datasheet

Difference in commands formats sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:

MCP41100 command byte is X X C1 C0 X X P1 P0 where X is unused, C1 C0 is one of 4 possible commands,  only 2 being valid commands actually: 01 (Write data), 10 (Shutdown), finally P1 P0 should be always 01 for an MCP41100
MCP4131 command byte is AD3 AD2 AD1 AD0 C1 C0 D9 D8, where AD3-AD0 is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is 00 which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), C1 C0 is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be 00 (write data); finally D9 D8 are the high order bits of the value to write to the register, but D9 is unused and should always be 0. For 257-steps pots, D8is used to have the full resistance scale, otherwise it should be 0

Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:

00010001 value

The first byte can be broken down as such:

0001 address of the pot wiper register 1 (not 0): this wiper does not exist on MCP4131 hecne writing to it will have no impact...
00 command bits meaning "Write to register specified in previous address"
01 high order bits (D9-D8) of the value to write to the wiper register.

Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:

byte address = 0x00;

And that should be fine! Indeed, now your program passes:

00000000 value

Which means "write value (between 0 and 128 which matches exactly the 129 steps resolution) to the wiper register 0 of the port".

Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.

void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotIncrement();
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotDecrement();
      delay(10);
    }
}

void digitalPotIncrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x04);
  digitalWrite(CS, HIGH);
}

void digitalPotDecrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x08);
  digitalWrite(CS, HIGH);
}


SIM808 module: GSM location command (AT+CIPGSMLOC=1,1) giving wrong value after execution of sending message command (AT+CMGS=+91xxxxxxxx)

It might be due to the command giving the nearest cell tower location. And for sending SMS it might be shifting to a different cell tower depending on your network. This could maybe be easily checked using a different cell provider or as you said its working at your home so I believe I am correct in assuming this is the answer


How can I use a variable to choose which Serial port to interact with?

You may use an array of pointers to the actual serial ports. For
example, on an Arduino Mega:

const size_t PORTS_COUNT = 4;
const HardwareSerial *ports[PORTS_COUNT] = {
    &Serial, &Serial1, &Serial2, &Serial3
};

void setup() {
    for (size_t i = 0; i < PORTS_COUNT; i++)
        ports[i]->begin(9600);
}


How to display tilt sensor data on an LCD?

The serial monitor cannot relay data from different peripheral unit in an arduino system.

I think you have certain misconception of the hard and software. Your USB connection to the microcontroller on the arduino is just a trunk for a asynchronous serial transmission. In the past this was done via a RS-232 interface.

So, what is it, that you see in your serial monitor? That's just a bunch of characters sent by the microcontroller on your arduino. This data is sent from the microcontroller, because some piece of software fills the fifo of its serial interface. In fact, such commands are executed, when you call the method "Serial.print()". Data gets then sent to your PC, Mac or whatever you are running your IDE on.

Now on the very same microcontroller the software for your tilt sensor is being executed. How could the serial monitor (which resides on your PC) route data from your tilt sensor to your LCD display? I'll tell you: It can't.

(In fact you could write a terminal script on your PC which reads data from serial and writes it back to the same interface, but it may cross your mind, that this might be a very big indirection)

So what do you wanna accomplish? You want to put data read from a device connected to your Arduino to another device connected to your Arduino. So you better tell it the Arduino. The serial monitor will not be involved, hence you won't need any calls of Serial.print() to accomplish that.

To help you with that task, we need to see the code you have written so far.

Ok. first thing you need to know: You can't have two arduino sketches running simultaneously on your arduino. This is, because there is nothing like an operating system on your arduino which might provide a scheduler to run both programs. (If you want, look up scheduler on wiki, as it is very useful to know what you can't have)

So you need two pieces of code to run on the same microcontroller (the big black thing on your arduino) one doing the tilt sensor readings and the other printing data on your display. Hence you have to make one program out of two. To accomplish this, you have two problems to solve.

you have to execute both code fragments alterantely, which, because the controller is fast enough, boils down to do both task nearly simultaneously
you have to bring the data which is acquired by code part 1 from the tilt sensor to code part 2 writing to the display. This is (for people into programming) rather simple as it simply has to be stored in a variable.

I recommend you to look up some programming basics at the arduino home page concerning the "setup" function and the "loop" function. But for now: You can have only one of each running on your arduino. Everything which is inside "setup" is executed only once after powerup. Everything which is inside "loop" is going to be executed over and over again consecutively (if nothing breaks).

Your program might look like this:

#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

char gl_senstr1[15];
char gl_senstr2[15];

void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}

void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");

      sprintf(gl_senstr1, "%d", digitalRead(6);
      sprintf(gl_senstr2, "%d", digitalRead(7);

  sprintf(gl_senstr1, "%d", digitalRead(6));
  sprintf(gl_senstr2, "%d", digitalRead(7));

  mySerial.write("sensor1: ");
  mySerial.write(gl_senstr1);
  mySerial.write(" sensor2: ");
  mySerial.write(gl_senstr2);

   delay(250); // Wiat 1/4 second

}

I did not test it, because I neither own your display nor that sensor. But you can give it a try. You eventually have to dive into the art of programming if you want to accomlish little more than this. This is where the rubber meets the road.


Arduino Serial Communication with Python: sending an array

If I use >BBB instead of >iii... That's because "B" is a byte. So you end up sending 3 bytes:

struct.pack("BBB", 1, 2, 3)
\x01\x02\x03

"i" is an int and has a size of 4, so you send 4*3 = 12 bytes:

struct.pack("iii", 1, 2, 3)
\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00

Serial.read() reads 1 byte at a time, so you need to read 4 bytes for each value.

Here's a function to read a 32-bit int. The drawbacks of this method are that a) it will block until 4 bytes have been read. And b) there's no way to tell if some data has been lost. There are more robust ways to send data with Start-of-Message, End-of-Message, and Check-sum chars. Also, the function assumes the data is sent with the LSB first. But I'll just put this here as an example.

// Helper macro to merge 4 bytes
#define TO_INT32(a,b,c,d) (((d)<<24)|((c)<<16)|((b)<<8)|(a))
int32_t read_int()
{
  uint32_t result[4];
  for (int i = 0; i < 4; i++) {
    // Wait for data at the port
    while (!Serial.available());
    result[i] = Serial.read();
  }
  return TO_INT32(result[0], result[1], result[2], result[3]);
}


USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader

Once the bootloader transfers control to the main code (sketch) it may as well not exist any more. It does not affect the way the sketch runs.

  I've written a simple echo program using RXC interrupt vector ...

Please post this code. For you to print "READY" you are (presumably) using the Serial port, in which case the HardwareSerial interrupt vectors are being used. I don't know how you managed to take over those vectors. Seeing your code might answer that.


How does Arduino UNO deal with bit shifting?

There are two types of right-shift in C - logical and arithmetic.

GCC (which is the compiler the Arduino IDE uses) selects which one to use depending on whether the type you are shifting is signed or not:

If it's signed then use an arithmetic shift
If it's unsigned then use a logical shift

In a logical shift, the value is literally shifted to the right padding the left side with zeros. An arithmetic shift, however, shifts and extends the sign. I.e., it performs an arithmetical "divide by 2".  That means if you right shift a negative value to still have a negative value (Note: this behaviour is implementation specific, so is only applicable to GCC. For other compilers in other situations you will have to check the documentation of that compiler).

So if you store the results of analogRead() in an unsigned integer variable >> N will right shift the value N times. If you store it in a signed integer it will divide the value by 2 N times.

For a positive value, which the results of analogRead() will be, the end result is the same - divide by 2 N times.

So if you right-shift 6 times you reduce a 10-bit value down to (10-6) 4 bits. 24 is 16, so you get 16 possible values.  24-1 is 15, so you get values 0-15 in your final value.


The RF networks of the RFM95 board are ideally configured for the general range of frequencies, but the difference between your 865.7 MHz and the 868 MHz tuning of a European (vs US) version of the board is likely smaller than the error with which the RF networks can be tuned to begin with, so that is unlikely to be a problem unless there is some hard lockout of your desired frequency in the SX1272 chip.  I've even heard claims that some people have managed to at least somehwat use US vs European tuned versions on the opposite bands, which is far more drastic than what you are trying to accomplish.

So assuming there is no hard lockout of your desired frequencies in the hardware, basically what you will need to do is to change the frequency list in the source of the software you are using to operate the module.

Basically you would edit src/lmic/lorabase.h and make a modified version of the EU configuration.  Ideally you'd add that as an additional option and select it, but for an initial test you could just edit the European version to fit your needs.

Do keep in mind the code will probably want to use multiple frequencies - if you have a gateway that receives only on a single frequency, you'll need to modify the code to always use that, after determining if doing so fits with usage-rate rules in your jurisdiction.

It's probably worth doing some online research to see if anyone has already put thoughts into operating LoRa in India - if so, there may already be a modified branch of the LMiC code you can use.


USB-host is hard if not impossible to implement on an UNO.

Though I believe most USB keyboards support PS2 as well (normally done with a USB-to-PS2 plug). So you should be able to talk to the keyboard using the PS2 protocol, which is a lot easier. There are libraries to do this for you.

Next you could use V-USB to emulate a keyboard to the PC. For that USB connection you need to add some resistors and zener diodes, to stay withing the usb specification. This is all explained on the V-USB website.

Using a different Arduino that has real USB support might be a better option. Also the UNO is rather large, so not that easy to hide.


why of 2 identical micro-controllers, only one can connect to a given device?

Other than a software issue, there is no reason it shouldn't work. Only thing may be identical Bluetooth names or ids. Clear the device from windows and try again.

I have some cheap Bluetooth obd 2 readers that all use the same Bluetooth mac address and name. I have to delete one from my android phone before adding the new one to connect to it.


An Arduino UNO has a max current of 20 mA per IO Pin and a max current of 200 mA of all Pins together. If you intent to drive the senders with the pins then this is impossible.

If you power the Arduino with USB, the VCC current is limited to 500 mA (thermo fuses). If you power it externally, it depends on the power supply. Using the voltage from the Vcc Pin is risky (IMHO), because the Arduino needs power too.

So with 100 mA per sensor I would definitively use an external power supply.


How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive]

This is most likely not what you want to be doing

//declaring variables of functions
FM = FindMax(new long);
FA = FindAvg(new long);

And it is entirely incompatible with these definitions

//list functions here
long ForceInPounds(long);
long FindMax(long);
long FindAvg(long);

With the result that you pass a pointer to a long (ie, its address in memory), to a function which is instead expecting the value of a long.

However, it's going to be hard to propose a solution until you edit the body of the functions into your question.

There's probably no reason to use new here at all - let the functions allocate their own temporary variables on the stack, since they seem to return a value rather than a pointer.  Most likely even if this worked, the new long you create would be abandoned - ie, a memory leak.


Talking to ADS8698 (18-bit ADC) over SPI

Per the Datasheet PG47

During power-up or reset, the default content of the command register is all 0's and the device waits for a command to
be written before being placed into any mode of operation.

If your still working with this I'm going to be tackling this same thing very soon, hopefully I can get it to work with DMA.
https://forum.pjrc.com/threads/34863-Teensy-CC-Dummy-Load-300W/page4


How to install a library for a single project

I ended up switching to ano, which supports a local lib directory.


Ubuntu class string has no member remove

The remove method was added to the String class in 1.0.6.

Installing Arduino IDE from the Ubuntu repository gets you a really old package (1.0.5).

You should download and install the newest version from the official Arduino page.


Determine difference between 3.3V and 5V shields

You read the schematics and datasheets. The former will tell you what power supplies are connected and how, and the latter will tell you what voltages are acceptable to the devices.


Can someone help me figure out why my menu gets stuck?

Problem One (Menu not moving past Main Garden to Currants):
MainOld is used to increment MenuState but MainOld never gets incremented, which means it will never have a value greater than 0. Accordingly MenuState can
never be greater than 0 + 1.
Problem Two (Sub Menu looping back to main):
'Checking' the state of LEDPower like in Water1() is not the best way to accomplish what you want to accomplish. It may work but is not technically correct as LEDPower is a pin state and you never actually read the state.
The other issue in Water1 is that previousWaterMillis doesn't get updated anywhere in your code, which means that anytime Water1 is called more than 10 seconds after boot your solenoid will activate and then immediately deactivate. I would recommend a while loop inside your Water1 function. ex.
void Water1(){
  digitalWrite(Relay1, HIGH);
  unsigned long currentMillis = millis();
  previousWaterMillis = millis();
  int LEDPowerState = digitalRead(LEDPower);

  while(currentMillis - previousWaterMillis <= WateringInterval){
    digitalWrite(LEDPower, HIGH);
    Serial.println("Watering Garden with LED Lit");
    currentMillis = millis();
  }

  digitalWrite(Relay1, LOW);
  digitalWrite(LEDPower, LOW);
  SubMenuState = 0;
  SubMenuOld = 0;
}

^^ This will illuminate your LED and activate the solenoid for the 10 secs you wish to water.


Try this amazing breakout board. Its all you need. SparkFun Voice Recorder Breakout - ISD1932

Moreover, If you thinking on letting that device talk back, try this: VoiceShield

Well, there is also an instructable for this, HERE. This Instructable will show you how audio input can be repeatedly added to a 512 byte buffer and then transferred to a SD card in real time. The audio file can be played back on a standard audio application or analysed byte by byte.


seperate ATmega 2560 - turn on a single LED - troubleshooting

You are saying that the LED lights if you write LOW to it.

  I need to pull the output pin to LOW to make the LED work

That's exactly what you expect.

Since the other end of the LED is wired to +5 V, then you need to drive the pin low to have a voltage difference over the LED, and for it to light.

  I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock?

Yes, I suggest you do that.

Look at Engbedded Atmel AVR® Fuse Calculator to see what to set them to. I suggest the internal 8 MHz oscillator.


What should be the delay to be given for reading accelerometer

A delay is not needed.

What can be more beneficial, though, is making a dummy reading between each real reading.  This gives the ADC more of a chance to settle on the right reading without the Sample and Hold capacitor being influenced by the previous reading.

The simplest way is just to duplicate your analogRead line so it's done twice.


Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board?

Actually, this is dependent on the datasheet. Assuming it's 7 segment + dot, it will require 8 independent pins to control each of the segment. All of segments are connected to a common anode/cathode which can be connected to a pullup/pulldown.

If we have 4 digit, that means we need 4*8=32 pins, which is a lot for any microcontroller. However, if you map out the internal circuit, you'll find that the segments are multiplexed. (You can do this by touching the pins with a wire connected to a pullup resistor, and another wire connected to ground.

Generally, you'll find that all the segment pins are multiplexed together in such a way that if all anodes/cathodes are enabled, all of the digits show the same display.

So how then can we make use of this information? Here's an idea:

How about turning on each of the digits one at a time (by controlling the common anode/cathode), but doing it quickly?

An example sequence would be as follows:
Set the segments for digit 1, enable the corresponding common anode/cathode for 5ms. Turn off.
Set the segments for digit 2, enable the corresponding common anode/cathode for 5ms. Turn off.
Do the same for digit 3 and then 4.
Repeat.

Controlling in this manner means you only need 8+4 pins=12 which is available on an arduino uno. Refreshing at 4*5=20ms will hardly be visible to our human perception, thanks to persistence of vision.

My answer is really just a starting point. If you spend some time, you can try to put in other smarts which are suited for your application, using even less pins. You should try this as an exercise. ;-)

Edit:
As a precaution, it's important to limit the current running through each of the LED segments so that they can live a long and happy life.

Assuming a forward voltage of 2V, adding a 1k resistor at the common anode limits the current to 3mA. This means adding resistors for all 4 anodes.

The same could work for common cathode displays, as long as the reverse breakdown voltage is not exceeded.

As with all things you find on the net, don't take my word for it. You should do the maths to check.


RF24 tranceivers: trouble with two way communication

The main thing that I can see wrong with your sketch is that the logic of your methodology is backwards.

You are spending most of your time either with the radio asleep, or not in listening mode, so it can not receive anything.

Instead you need to spend all your time in listening mode waiting for messages to arrive, and only when the button changes state do you want to switch off listening mode and send a packet to the other end. As soon as you have done that you then go back to listening.

You can't listen while the radio is powered down, so using powerDown() and powerUp() is just nonsense.


rfm69 on M0 Express... init() doesn't work

The "init failed" do not appear. Everything stops at "//******".
I have compared to another RFM69 program.
I have added a line " digitalWrite(RFM69_RST, LOW);" at the begining of the "//manual reset" and it works now.
the sequence
digitalWrite(RFM69_RST, LOW);
digitalWrite(RFM69_RST, HIGH);
delay(10);
digitalWrite(RFM69_RST, LOW);
seems to be more efficient.
... it remains a few mysteriuos for me.
Thank you


Serial.read() is going to give you ASCII codes.  So when you send 1 from the serial monitor the Arduino receives 49.  Note that the ASCII code for a digit is the same as the digit plus 48, so that sets bits 4 and 5 high.

You can use Serial.read() - '0' to get the actual number from the ascii code.


The IPAddress class has a member function bool fromString(const char *address).


How to access the member of union in loop?

I don't think you can.

The structures are defined within a function so the loop() won't have access to them.

Further the parameter returned from the function xbee_rx() is of type SENSOR_DATA which is a sibling in the frame structure to the data you want to read.


Do ISRs have to be defined in top level Arduino program?

Why don't you try it and see?

  is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++ namespace?

Yes. Example here:

const byte LED = 13;
const byte BUTTON = 2;

namespace foo
  {
  // Interrupt Service Routine (ISR)
  void switchPressed ()
    {
    if (digitalRead (BUTTON) == HIGH)
      digitalWrite (LED, HIGH);
    else
      digitalWrite (LED, LOW);
    }  // end of switchPressed
  }  // end of namespace foo

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  digitalWrite (BUTTON, HIGH);  // internal pull-up resistor
  attachInterrupt (0, foo::switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

I put the ISR in the namespace "foo" and it compiled OK.


Obtaining angular velocity from quaternion data (BNO055)

I do not know how to interpret the data given by that sensor, but from
reading the code, the meaning of dt is pretty clear.
The function you show assumes that the sensor started in the reference
orientation (quaternion one), then rotated at a constant angular
velocity until it reached the current orientation (quaternion *this),
and this rotation happened over a time dt.
Then dt is the time required for moving from the reference orientation
to the orientation described by the quaternion *this. You should
probably check out the sensor's datasheet for more details on how the
orientations are provided.


The compiler error is due to that the compiler does not know what Thread is.

  tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. A good practice is to include all header files that are needed to read the header file. As Thread is defined in mthread.h the tcan.h file should be:

#ifndef tcan_h
#define tcan_h

#include <mthread.h>

class tcan : public Thread {
public: tcan();
protected: bool loop();
private:
};
#endif

Cheers!


Your code sets it high, delays for 1000ms, sets it low, and then... turns around and sets it high almost immediately after. Try delaying in between.


If you can configure the PWM to run at 111 Hz (I don't know how
this is done on the Teensy), then “gating” it is as simple as turning
the PWM on and off at the desired frequency:

uint32_t half_period;  // half the gating period in microseconds

void set_gate_frequency(float freq_in_hz)
{
    half_period = (1e6 / 2) / freq_in_hz;
}

void loop()
{
    static uint32_t last_toggle = 0;
    static bool pwm_is_on = false;
    if (micros() - last_toggle >= half_period) {
        if (pwm_is_on) {
            digitalWrite(PWM_PIN, LOW);
            pwm_is_on = false;
        } else {
            analogWrite(PWM_PIN, 128);  // PWM with 50% duty cycle
            pwm_is_on = true;
        }
        last_toggle += half_period;
    }
}


Why is my Analog Input channel adding voltage to my signal?

Wow, you guys are gonna get a KICK out of this!

The analog input channel was not adding millivolts to my Analog Input signal. I stupidly was not supplying my Arduino Mega with 9V!! I had it running off of the USB port, which was affecting my 5V reference (thank you @majenko for pointing that out!).

I measured the 5V pin and it was fluctuating between 4.41-4.21 volts. My colleague made a comment and I reviewed the Arduino Mega datasheet. It must be supplied with 7-12 volts in order for the 5V to output correctly.

Once I hooked my Power Vin + GND to my power supply, set that at 9V/.08amps my analog input readings were accurate.

Thank you everyone for your help!


I think it might be a problem with the code you are using, prior to version 2.2.0 of the "ESP Core" the first block of code worked, since only the second version works.

It seems that you can get around it by rather than doing this:

 WiFi.begin(ssid, password); // connect to the network
 while (WiFi.status() != WL_CONNECTED)
 {
     delay(500);
 }

You should do this:

if (WiFi.status() != WL_CONNECTED)
{
     WiFi.begin(ssid, password); // connect to the network
     delay (500);
}

Does that look it might be a likely cause?

Sources
 1  2


Send serial commands through IDE while RX pin is in use

Regarding “I have connected my LED strip (WS2812B LEDs) to the RX port”:  If you connect an LED strip to the RX pin, there's a good chance you won't be able to read serial data reliably on that pin, and may have trouble loading new sketches.  It makes sense to connect the LEDs to some pin other than RX.

Regarding “If I open up the serial monitor, how do I send something to it”:  Ordinarily, one uses the serial monitor to receive data from an attached MCU or to send data to the MCU. (An MCU is a microcontroller – eg an Arduino or ESP8266.)  In the sketch on the MCU, use Serial.write() to send binary data to the monitor, and Serial.print() to send text and formatted numbers to the monitor.

If you want to send serial data rapidly from your host computer to the MCU, write a C or Python (etc) program that opens a serial port, marshals the data, and sends it.  In the  sketch on the MCU, use Serial.available to test if characters are available to read, and Serial.read to read a character.  For faster transmission, you can send binary data instead of ASCII, but would need to read up on that before attempting it.

For fast data transmission, aim for either high data rates or strong data compression.  For example, you might make up a protocol that only sends colors for pixels that are going to change; or might have high-level commands that tell the MCU how to generate a set of data, via color end points, step rates, and numbers of steps.

In general, wifi data rates are somewhat higher than serial data rates.  If that is not what you are experiencing, perhaps review the article Found a way to upload data VERY fast by wifi from github.com/esp8266.

Edit 1:
Regarding “Nothing is displayed in the serial monitor” [from code like if (Serial.available()) { Serial.write(Serial.read()); }]:  I'm assuming that the sketch in use has a setup() routine containing a Serial.begin(somedatarate) statement, with the same data rate selected in the serial monitor as in the Serial.begin() statement.   I'm also assuming the sketch has a loop() routine containing the if (Serial.available()) { Serial.write(Serial.read()); } code.

I'm also assuming the sketch was properly downloaded, and then the serial monitor was opened, using the USB-serial port the ESP8266 is attached to, and then you typed some text into the text entry box of the serial monitor and pressed or clicked Enter to send the text to the ESP8266, with a proper setting for the end-of-line character.

If all those assumptions are correct, but nothing shows up in reply to the text you send, then it seems likely some hardware or software issue is occurring.  For example, when the Serial data structure is set up (when the sketch begins running) it might be selecting an incorrect Rx pin.  Or something may be loading down the Rx pin.  To find out if either of those is the case, use an oscilloscope (if you have one) to look at what's arriving at different ESP8266 pins when you send text from the  serial monitor.  If no scope, connect a 5K-10KΩ resistor to an LED and use that as a logic probe.  One end of the resistor connects to a probe; the other end goes to the LED anode; and the LED cathode is grounded.  Test if that's working by touching the probe to +3.3V.  When the probe appears to be working ok, use it to check for brief flashes of data at different Rx pins on the ESP8266 when you send data from the serial monitor.  If no data gets to the ESP8266, it can't echo it.  (Note, I'm not sure how your NodeMCU ESP8266 handles serial-via-USB data; my notion that serial data should be visible on some Rx pin might be wrong.)

If it appears data is getting to some pin but isn't showing up as available, you might try opening software serial on that pin.  Some examples appear in code in a serial monitor note at github.com/esp8266.  I don't know enough about NodeMCU / ESP8266 to say what to do if probing and software serial don't help.


Two floating point values do not get added and printed on ESP-WROOM-32

Try doubles instead of floats.

Your initial value, 34567891.234 needs 35 bits of precision to keep track of the decimals, but floats only have 24 bits pf precision. So to have enough precision to keep track of the difference between 34567891.234 and 34567891.234+1, you need higher precision storage.

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

void loop() {
  // put your main code here, to run repeatedly:
  double a=34567891.234;
  double b=2.3456;
  a++;
  Serial.print(a+b, 4);
  Serial.println("");
  delay(1000);
}


Strange power comsuption into sleep mode

SOLUTION [by OP]

My problem was that the SD card module was consuming when it was controlled by a transistor and my Arduino board was into the sleep mode. So I wrote into the void setup() the digitalWrite(PIN, HIGH) statements where PIN represents all pins connected to the board that belong to the SD card module (DI, DO, CS, and CK pins), to enable the internal resistor of that pins. Then, I checked the power consumption and I reached less than 100 uA.


Assigning an empty array row to reference

If you're using a pointer then there's no limit to what that pointer can point to.

The way I see it you have two sensible choices:

Point to a default value

This doesn't have to be in your array. It can be anything that is an int[3], since that is what your array consists of.

int[3] nothing = {0, 0, 0};

EXCLUSIVE_COLOR = nothing;

This means that it's actually pointing to something valid, in this case it's actually (I assume) the colour black.  That can make it easy to deal with, since EXCLUSIVE_COLOR[0] will be a valid value.

Point to nothing

You can point your pointer to NULL and it will be pointing to "nothing". This means that EXCLUSIVE_COLOR[0] is no longer valid, which can make handling it somewhat harder. However it does allow you to distinguish between "nothing" and "black", unlike option 1.

For example:

EXCLUSIVE_COLOR = colors[2]; // {0, 0, 255}
...
EXCLUSIVE_COLOR = NULL; // Not pointing anywhere

To test if it's pointing somewhere you can simply use if:

if (EXCLUSIVE_COLOR) {
   // you have a valid entry
}


H-Bridge vs Motor shield for the arduino

If I were a beginner, I'd go with the Motor shield.

I'm even personaly using the one from DfRobot, which as @Gerben said, is just plug and play.

It also allows you to select the input power for the motors, which can be either from the 5V Arduino pin or from an external battery. This is pretty convenient if you need more than 5V to power up your motors. It can also support 2A of current draw, which is more than enough for small arduino toy cards.

Here is the shield: https://www.dfrobot.com/index.php?route=product/product&product_id=1180&search=2A&description=true


The difference for different voltage boards lies in the parts, that are soldered on it. Often microcontrollers support more than one supply voltage, but impose different performance limits on the system. Take for example the Arduino Uno: It uses the Atmega328p, which can run both on 3.3V and 5V. But on the UNO there is a 16MHz quartz, which generates the controllers clock signal. The Atmega328p cannot run 16MHz with only 3.3 volts. To run a board on a voltage, for which it wasn't directly build, mostly requires you to resolder it with the correct parts.

  whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v

There are special chips, called voltage regulators/converters. They come with various working principles, but basically they are converting one voltage to another. The Arduino Uno has one connected to Vin, so that you can apply between 7V and 12V to Vin and the Arduino itself will only see the 5V it get's from the regulator. Some modules also have a voltage regulator, but not all. Be careful not to provide more than the specified voltage to any board or you may destroy it.

  the arduino I bought looks like it has both! is that even possible?

First, as Juraj wrote, this is not an Arduino. It is an ESP8266, a totally different chip and board. But you can also program it through the Arduino IDE, without it being an Arduino. Second: When they write, that you can provide it with either 3.3V or 5V, they mean, that you can provide 5V through the USB jack and a voltage regulator will convert it to 3.3V for the ESP, which runs completely on 3.3V. You should not connect 5V to any other pin.

  since this arduino says vin is 5-12v the two should connect and work properly, right?

As stated above the 12V is only, what you can at maximum provide at Vin. The ESP8266 runs on 3.3V, so you will have to provide 3.3V (or more over the Vin pin). The LED matrix runs at 5V, as you stated. So you need a 5V source and a level shifter for the 2 lines between the ESP8266 and the matrix. If you connect them directly, you would damage the ESP8266. So: No, you cannot use it directly. It is up to you, if you want to use a level shifter or buy another matrix display, which can be controlled by a 3.3V signal.


The Nano cannot power the ESP8266. It has an absolute maximum limit of about 50mA from the 3.3V pin, since it is provided by the USB interface chip. By drawing too much current (the ESP8266 needs hundreds of mA) the USB chip stops functioning.

You need an external 3.3V regulator to power the ESP8266.


How to read code from Arduino Uno to Arduino IDE?

Can we read and get C codes from compiled codes from Arduino hardwares?

While it is possible, even trivial, to disassemble machine code, it is very difficult to convert the assembly code into a higher-level language, and essentially impossible to turn it back into an exact copy of the source code it came from. There simply isn't enough information in the machine code to do so.

  My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

The debug port will work in tandem with appropriate software that will already have access to the source code, so this is not a method for conversion either.


It won't pair directly you will need other apps for pairing the modules. Try using this app. It will solve your issue for sure


I see from eBay that you can get the DS1307 for around 10 cents. Is that really too much to pay? You also need a crystal and a backup battery (eg. CR2032). Without a battery the device cannot possibly remember the time if it is powered off.

If your device is battery powered then you could conceivably just use millis(), however you would need to have a way of setting the time. The resonator used on a Uno is not as accurate as a crystal, however that might be good enough depending on your project.

If you are trying to save money I wouldn't use a Uno or Micro, but the bare chip, with a few extra components (eg. decoupling capacitors, a couple of resistors, and a crystal).


Arduino will not read three successive packets in the serial connection

The problem is that your code works but you substract 48 from what you received.
Which if python sends a char with values: '0' '1' '2' it will result in the serially outputted values of NUL SOH STX which are invisible.

If python transmits the raw byte value (aka 0x00 0x01 0x02) this would result in 0x00 - 48 = undefined behaviour with a underflow (same goes for 0x01 and 0x02)


Using delay(1000); without influence on analogWrite?

The PWM started by analogWrite will not be influenced be the delay, because the analogWrite function only sets the registers and starts the PWM. The PWM generator is independent from the CPU on AVR microcontrollers. On esp8266 for example the PWM is generated with use of interrupt and it is too not influenced by the delay function. To stop the PWM you must call analogWrite with 0 or change the pin mode.


Need help to send serial data from arduino to XBee and to another XBee wirelessly?

You are using it as in non-API mode when data are passed to Xbee wireless transparently. To use Xbee in API mode use e.g. Xbee-Arduino library.


In the first case, the first time, that the outer if statement becomes true, the code will go into the while(1) loop and will be stuck there forever.

The second code is different, since the while loop will check at each start of it's iteration, if the condition is still met. If not, it will exit, so not necessarily an infinite loop.

Going into an infinite loop, if something fails to initialize is often done in the microcontroller world, especially when initializing external hardware. A reset loop (restarting until it works) is mostly not fitting there, because often it is not just waiting for a resource to become free. Often this is used for serious problems, for example external hardware not being there or functioning. Imagine trying to use an external GPS chip, but the chip is not there. It should be there, since the device is build this way. Why should a reset loop be better here? The problem won't get away with time. Or imagine, that the initialization fails, because the GPS chip is broken. Trying to interface such a broken chip repeatedly might break even more things. Either way, someone has to look at this, to fix the problem. It will not go away by itself.

I would say, that the failed initialization in the library above is such a situation.


Arduino Ground Current and DC power jack

Going by the schematic here there is an M7 diode (D1) between the power jack and the VIN pin on a Uno (you don't actually say which board you're using, I'm guessing based on the first link).
The datasheet here indicates that the maximum forward current for a M7 diode is 1.0 A. However different manufacturers datasheets seem to disagree as to whether that is a sustained DC current or only rectified current (so 50% load implying ~500mA constant load).
Either way you are looking at a potential 1.1 V drop across the diode so your VIN will be below the supply voltage by up to that much.

If you want to live dangerously you can always replace D1 with a piece of wire (or put the wire across it). You will lose reverse voltage protection on the DC jack, using a supply with it backwards will blow things up, but your current will then be limited by how much current the connector pins and PCB trace can cope with before they melt.


How do I start a function with serial input?

Okay, as Majenko and Nick Gammon have suggested. The \n had not arrived in the serial buffer. That way the if clause was not fulfilled and nothing was printed. This code has worked for me now:

if (Serial.available() > 0) {
 if (Serial.read() == 'A'){
  char inte1 = Serial.read();
  int inte2 = Serial.parseInt();
  int inte3 = Serial.parseInt();
  int inte4 = Serial.parseInt();
  int inte5 = Serial.parseInt();
  Serial.print(inte1);
  Serial.print(inte2);
  Serial.print(inte3);
  Serial.print(inte4);
  Serial.println(inte5);
 }
}

Although i read quite a bit now, serial input is still a mystery to me.


Sending data over TCP connection in one piece

The problem is, that "char" is just one character. So you have to build your return out of the chars... if you want to use the "client.read()" function.

String res = ""; //this will be the resived msg after the loop
do {
   char c = client.read(); //c will be -1 if no byte is left
   if(c!=-1)
       strcat(res, String(c)); //Append the char to the result string
} while(c!=-1);

//Code is not tested!!!

To your java problem... just put your code parts into try catchs not whole functions (remove it for the function and add it on the points eclipse tell you to). So you can react to each error individually. Then put client stuff in a own thread so it not blocks any other stuff. Every disconnect or faild connection will throw an exception if you dont catch it with an if. So you have to handel it their (try to reconnect or something)

EDIT:

static void close() {
    try {
        client.close();
    } catch (IOException e) {
        system.out.println(e.toString()); //Print the error or do something else

    }
}


how to ignore a sensor being tripped the first time and start recording millis on the 2nd time it is tripped

The start time will default to zero, so you could change it to:
if (digitalRead(2) == LOW && start == 0)
  {

    start = millis();

  }


I'm not sure if the concept of an "actual baud rate" is really meaningful in a pure USB connection.

In my experience, the 32u4 is faster than the 328p at serial-heavy tasks. There is no intermediate chip, and USB has much larger hardware buffers than the serial port does. I don't know how much processing you're planning to do on your data, but I would expect that a 32u4 can process serial data pretty much as fast as you can generate/process it.

On the host side, it seems to me that there is very little difference in whether the "virtual COM port" has an FTDI or a 32u4 on the other end, so I don't see why one should be faster than the other (though admittedly they go through different device drivers).


Wireless doesn't necessarily mean it's WiFi.
You should get an XBee module that explicitly states that it's a WiFi module.

For a cheaper alternative you can check ESP8266 WiFi modules, which you can get for $5.


Outputs/inputs to Multiple Arduinos in Arduino IDE at once

Arduino IDE is editor and builder. Your sketch runs on microcontroller and the microcotroller doesn't need the IDE to run it. The Serial prints from microcontroller go to com port from which any Terminal app can show them, not only the Serial Monitor build-in in IDE.

Connect both arduinos of same type to computer. They will have different ports. Upload your sketch to the first one, then change the port setting in IDE and upload to second arduino.

Serial Monitor can show you the output of arduino connected to the selected port. Switch port in Tools menu and reopen Serial Monitor to see the output of the second arduino.

To display booth at once, there are some options with different difficulty level:

use two instances of a terminal program like PuTTY Terminal Emulator to show the output
connect the TX pins of arduinos together
send data from one arduino to the second and let the second process them


How to add Ultrasonic Sensor to the board?

1) Not really. You have so little space and you have to selder them. Try using wires

2) If you want it to be flexible use a sandard solderless breadoard on the center of the car and then with male-female jumperwires try connecting them.

3) The board has traces. That means some holes have a very specific purpose.

Updated:

On every breadboard the holes are connected verticaly. For example, in the image from your breadboard you posted 1A, 1B, 1C, 1D and 1E are connected together.
If you would like to have all of the 3 sensors better use wires and then atach them on to your breadboard.

Here is a picture:
https://www.dropbox.com/s/3ij4w6eytio8p08/Screen%2016-25-31.png?dl=0


Issue with Serial PINs (RX/TX) on Arduino

RS232 is not TTL. You need a level converter. For more details see https://www.sparkfun.com/tutorials/215.


ESP32 Hardware Serial Flow control and full espressif/arduino-esp32 support

your example was of great help solving the problem of driving RTS properly, thanks a lot!
I found a small bug in the code example, the data buffer is allocated in the loop() function instead of setup() and as a result, eventually the memory leak will fill-up all available memory.
Ciao!
Alessandro


Compare the new sample in a high sampling rate datalogger

In the function

ISR(ADC_vect) {

the variable d contains the current sample:

  // Read ADC data.
#if RECORD_EIGHT_BITS
  uint8_t d = ADCH;
#else  // RECORD_EIGHT_BITS
  // This will access ADCL first.
  uint16_t d = ADC;
#endif  // RECORD_EIGHT_BITS

So you can just "do something" depending on what is in d.  Of course, since this is a timer interrupt you have limited time to do anything, so you need to make sure that whatever you do is fast and efficient - so really you want to be using direct port access instead of digitalWrite().


There's such a solution, called 1Sheeld. It's pretty expensive though.


TBH the second version of the function is trash. The first version is (almost) the right way to do it.  There's stuff in the second version that really shouldn't be there. There is absolutely no reason why the creator of the library created that second function.

It "waits" for data to be available, when that data will be available the moment requestFrom() completes - so is completely redundant
It makes a spurious beginTransmission() call right before the requestFrom() call. beginTransmission() is only for writing, not for reading. It's pointless there.

However:

Both functions do an endTransmission() after the receiveFrom(), which makes no sense - the endTransmission() goes to balance a beginTransmission() only - not a receiveFrom().  receiveFrom() is a completely self-contained function that needs no other handling.

This library is probably not a good one to study for learning how to use the Wire library. It contains code that indicates the author themselves didn't have a proper grasp of the workings of the library.


I had a similar learning path  as yours and I also tried to use ADXL345 and ADXL355. The latter was a pain for the issues described in many posts like this.
I couldn't find any good tutorial on this topic and had to learn all by myself.
I also use a different approach because I program ESP32-wrover devices with MicroPython. Nevertheless the logic is the same for translating DataSheets -> code.

You have to decide which serial interface to use

I2C if you are constrained to limited wires
SPI for high frequency measures

in both cases you write/read to/from registers of the device which are identified by an address, indicated in the datasheet (look for the registers map section). In each address you read/write a byte, that is 8 bits (0 or 1), that are packed into an hexadecimal format (e.g. you can set power mode to 'measure' writing 0x01 in register with address 0x2d)

with both you normally have a library that implement 3 main methods:

init() for initializing the interface with the parameters you find in the datasheet:

SPI: polarity, phase, max_clock_frequency, first bit MSB or LSB
I2C: max_clock_frequency

read(register_address, nbytes) -> bytearray
write(register_address, bytearray)

before reading accelerations you must set range (e.g. ±2g), output data rate (e.g. 1000Hz), power mode (e.g. measure mode)

then you read acceleration data from corresponding registers. Consider that you can read multiple registers in one transaction reading multiple bytes starting from an address (e.g. you can read x,y,z measure in one transaction by starting from the first byte of x data and then reading 9 bytes = 3 axes * 3 bytes)

Then you have to convert from bytes to g units: in this accelerometer the value of one axis consist of 20 bits that are split in 3 bytes. You have to join the 3 bytes, shift away the trailing 4 bits, then apply two's components (that is for allowing negative numbers, look at this guide), then multiply by the scale factor indicated in the datasheet.


According to the last version of code for Arduino IDE, there are no limits of discovered Serial or Network devices since they are stored in a list (not limited as an array).

To discard problems, try with another operating system.


Yes, Arduino Servo library uses Timer1 (and other ones, depending on Arduino boards) to manage FastPWM via software interrupts. Timer2 is used by tone() function: be careful if you are using that function.

A good example using Timer2 to generate PWM is the Infrared remote library for Arduino. If IR_USE_TIMER2 is defined it will use Timer2. The key code is at IRremote.cpp where the ISR is managed.


What causes Serial.available() to become false after Serial.read() gets data?

It is an internal buffer and only the pointer gets increased. It it visible in the source code off the project, located on github:

// Read data from buffer
int SoftwareSerial::read()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

This third line from the bottom is the important part, it wraps back to the beginning if the buffer space has run out. If you call Serial.read(), the pointer is moved to the next position. So with the next Serial.read(), you'll get the next byte, if available. The byte itself gets overwritten only after the wrap (circular buffer).


You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line

serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use Invoke().

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort sp = (SerialPort)sender;
     //string indata = sp.ReadExisting();
     string indata = sp.ReadLine();
     //textBox1.Text = indata;
     Invoke(new Action<string>(
         (s) =>
         {
             textBox1.Text = s;
         }
     ), indata);
}


Can I connect my Arduino Uno to a power source and a battery at the same time?

Yes, to my knowledge this is done automatically, and there is no harm when connecting the Arduino to two power sources. When I power my Arduino I have it connected to my computer and the wall. So theoretically, if the electricity in the wall stopped coming, it would start taking power from the computer. Same works for battery.


No headers (.h) found in Documents\Arduino\libraries\arduino_144469 with demo code

If the folder is not needed then delete it.

The Arduino IDE uses the folders in the library folder to search for library header files (ie. .h files). It expects one library in each folder. When it see's a folder without any header files in it, it will count this as an invalid library.


PCINT with my arduino UNO says redefinition of 'void __vector_4()'

__vector_4() is just another name for PCINT1_vect(). The error
message simply means that you have defined that function twice. One
definition is explicit in the code you are showing to us. I cannot see
the other definition: obviously you are not showing all of your
code. Most likely that other definition lies inside some library you are
using in your program.

Since you cannot define an ISR twice, you will have to use another PCINT
which is not already in use. Or you could modify the library and try to
merge it's PCINT1_vect() with yours.

BTW, the error message does not come from avrdude, it comes from the
linker.


Implementing Quasi-Perpetual Battery on Arduino

You're overthinking it. Use one or more solar panels, a harvesting IC with sufficient storage, and the bare MCU and peripherals. Use enough panels and storage to run the MCU and peripherals 24/7, and to also charge the storage during the day.


Receiving two-byte int values over serial

void receiveData(int byteCount){

  // Looks like your number is sent in a 3 byte packet
  if (bytecount == 3)
  {

    // Discard first number as it is seemingly alway zero
    Wire.read();

    // Read low byte into rxnum
    int rxnum = Wire.read();

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    // Send back
    sendInt(rxnum);

  }

}

void sendInt(int num){

  // Uncomment below if you want so send back in same format
  // Wire.write(0);

  // Send low byte
  Wire.write((uint8_t)num);

  // Send high byte
  num >>= 8;
  Wire.write((uint8_t)num);
}


How to prevent optocoupler to activate when resetting the arduino?

The Fairchild datasheet for 4N25 shows this diagram:

describing the (or 'an') operation of the device. If this is how yours is operating, and if the input side is connected between an output pin and ground, then yes, on reset, the LED will go out and the switched output will go high. If you connect the device's input between the pin and +5v, the LED will light on reset, taking the switched output low. Plus, the switched output will now have the same sense as the Arduino output pin: i.e., digitalWrite(PIN, HIGH) will turn the switched output on, and vice-versa.


Turn off power to a moisture sensor except when reading values

If your sensor draws less than 40mA to operate, then you can safely "power" it from an GPIO pin.

The related question also asks how long the sensor must be powered in order to get a stable reading. For a sensor such as this one, it appears to be a simple resistive voltage divider, with the moisture sensor itself providing one leg of the divider circuit. The active component appears to be a comparator to provide a digital HIGH/LOW output as an alternative to the analog output.

Most schematics show a capacitor between ground and the voltage divider output, presumably to reduce noise. You need to allow for this capacitor to charge up and become stable before you take a reading. The time for this depends somewhat on the value of that capacitor and the supply voltage you are using.

Safe to assume, however, that a wait time of 1 second is more than enough.


It's probably not damaged, but you shouldn't do it again.

To get the 5V signal down to 400mV you need to create a voltage divider. As such you will need a:

5V / (400mV / 20kohm) − 20kohm = 230kohm

resistor between the pin and the input. 220kohm should be close enough.


Double click the reset button on the board. Then it will show in the Port list :-)


NodeMCU power consumption measurement and DeepSleep

An ammeter is basically a small resistor in series over which the voltage drop is measured. That resistance will play a part in the effective output impedance of your power source (battery).

This increased impedance will reduce the overall amount of current the battery can provide before the voltage drops to an unacceptable level.

For instance, I just did a crude measurement of the resistor used for the 200mA range of one of my DMMs and came up with a value of 1.2Ω. At 140mA that would give a voltage drop of (V=IR = 0.14 × 1.2) 0.168V. That's 0.168V that your NodeMCU won't be seeing. Add to that the fact that the WiFi will be creating peaks of current usage up to, say, 500mA (probably less, that's just a wild guestimate), the voltage drop will increase to (0.5 × 1.2) 0.6V. From a battery giving 3.7V nominal that would plummet to 3.1V as seen by the NodeMCU.

Depending on what kind of power regulation you are using that will most likely cause brown-outs of the power and the MCU will reset or crash.

When powered by 5V that 0.6V drop would not be as noticeable, since 4.1V is still well above what is needed to power the chip and the voltage regulation can still work properly.

So how can you measure the current with the battery? Well, there's two options:

Use a much smaller resistance (0.1Ω, for example) and measure the voltage across it - then use Ohm's Law to calculate the current.
Add a large electrolytic capacitor to the input of the NodeMCU after your current measurement to act as an energy source for sustaining the peaks of current required by the WiFi. By big I mean something like 3300µF:

simulate this circuit – Schematic created using CircuitLab


Waking up async the Arduino while it's sleeping periodically

This one works for me:

#include <PinChangeInterrupt.h>
#include <LowPower.h>

// I want to know when it was interrupted by PCINT:
volatile byte flag = 0;
void handler() {
    flag = 1;
}

void setup() {
  Serial.begin(115200);
  pinMode(A0, INPUT_PULLUP);
  attachPCINT(digitalPinToPCINT(A0), handler, CHANGE);
}

void loop() {
  Serial.println("entering powerDown sleep mode");
  Serial.flush(); // wait for sending all data

  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  if (flag == 1) {
    flag = 0;
    Serial.println("Pin change interrupt");
  } else {
    Serial.println("Timeout");
  }
}

However if you use RISING (or FALLING), it also wakes up from the sleep when pin changes back to the oposite state (and it'll be reported as Timeout).


Arduino Wifi Rev2, bug when reading PWM duty cycle value on pin 6

Arguable bug location
The problem appears to be here in the analogWrite() code:
    timer_B->CCMPH = val;

I suppose it could be argued that you're using the timer in an way unintended
by the Arduino megaavr core, but I think it's reasonable to consider this as
a bug that should be fixed in the core.
16-bit hardware register access and analogWrite() internals
According to the "Accessing 16-Bit Registers" of the ATMega4809 datasheet (among others no doubt):

The AVR data bus has a width of eight bits, and so accessing 16-bit registers requires atomic operations. These
registers must be byte accessed using two read or write operations. 16-bit registers are connected to the 8-bit bus
and a temporary register using a 16-bit bus.
For a write operation, the low byte of the 16-bit register must be written before the high byte. The low byte is then
written into the temporary register. When the high byte of the 16-bit register is written, the temporary register is
copied into the low byte of the 16-bit register in the same clock cycle.
For a read operation, the low byte of the 16-bit register must be read before the high byte. When the low byte register
is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as
the low byte is read. The high byte will now be read from the temporary register.
This ensures that the low and high bytes of 16-bit registers are always accessed simultaneously when reading or
writing the register.
Interrupts can corrupt the timed sequence if an interrupt is triggered and accesses the same 16-bit register during an
atomic 16-bit read/write operation. To prevent this, interrupts can be disabled when writing or reading 16-bit registers.
The temporary registers can be read and written directly from user software.

So in effect, timer_B->CCMPH = val; is not just writing the real CCMPH hardware register, it is also writing the real CCMPL register with whatever is in this anonymous temporary register that was filled by either the last read or write operation.
So here's what's happening in your code:

You execute byte l = TCB0_CCMPL; in printCompareChannelValues() which both reads TCB0_CCMPL and loads the temporary register with the real CCMPH register's value, which as you'll see is important.

You execute byte h = TCB0_CCMPH; which is reading the temporary register rather than the real CCMPH hardware register from which the temporary register was loaded in your read from TCB0_CCMPL above.  Note: technically this statement doesn't play a role in problem.  I'm mentioning it only to drive home the behaviour of the temporary register.

You exit printCompareChannelValues() and exit-and-reenter setPWMValueOnPin6() which calls analogWrite() which inside runs timer_B->CCMPH = val;,
which stores val in the real CCMPH with and stores the temporary register (containing the previous CCMPH value) into the real CCMPL.

So yeah, on each time through the previous CCMPH becomes the new CCMPL value.
Patching the core
Arguably what the core should contain, instead of  timer_B->CCMPH = val;, is something like:
{
    const uint8_t saved_SREG = SREG;
    cli();

    uint16_t temp  = timer_B->CCMP;
    temp          &= 0xFF;
    temp          |= (uint16_t)val << 8;
    timer_B->CCMP  = temp;

    SREG = saved_SREG;
}

Here we're doing full 16-bit register reads.  The load from CCMP reads the CCMPL first which primes the temporary register with the real CCMPH. Then the second half of the load from CCMP tries to read CCMPH, but is really  reading the temporary register correctly containing CCMPH's value.  And now there are no unpleasant surprises when this plays out in reverse.
The statement that assigns CCMP writes the CCMPL (really the temp register) then writes to the real CCMPH and simultaneously commits the temp register to the real CCMPL.
You can patch the above snipped over the timer_B->CCMPH = val; in your PATH-TO-ARDUINO15-DIRECTORY/packages/arduino/hardware/megaavr/CORE-VERSION/cores/arduino/wiring_analog.c
I have not spent a pile of time thinking about that patch, so use a bit of caution.  I may well have forgotten something important.
Priming the temporary register instead
If you don't want to mess with the core or you can't for some reason or another, a ugly hack would be to turn your simple analogWrite(6, value); call into something like the following:
{
  const uint8_t saved_SREG = SREG; cli();
  TCB0_CCMPL = TCB0_CCMPL;
  analogWrite(6, value);
  SREG = saved_SREG;
}

Besides turning off interrupt and then restoring them, the only thing happening here is this somewhat ridiculous looking statement:
TCB0_CCMPL = TCB0_CCMPL;
All this is doing is priming the temporary register for you.  On the right-hand side of the assignment we read the real CCMPL register.  This is also loading the temporary register with the real CCMPH, but we don't care about that.  Then on the left-hand side of the assignment, we attempt to write into CCMPL, but what we're in fact doing is writing to the temporary register.  And now your temporary register has the correct CCMPL value for when you run the timer_B->CCMPH = val; in the original analogWrite() code.
So, I suppose if you want to do this and you're unable/unwilling to modify your core, you could do this, potentially wrapping with an #if #else based on the Arduino megaavr core version, should they update the core in the future with patch given above or something equivalent.
Core patch using the same priming technique
The same priming technique could be applied inside the patch as follows.  This is maybe more confusing but slightly more efficient than the comparatively normal looking first patch.
{
    const uint8_t saved_SREG = SREG; cli();
    timer_B->CCMPL = timer_B->CCMPL; // Prime temporary register
    timer_B->CCMPH = val;
    SREG = saved_SREG;
}


To confirm that the serial communication is working, connect the ESP to the Arduino D10 and D11 that is used as SoftSerial pins.

+----+
| PC |
+--/-+
   |       +---------+
   \-------| Arduino |
     USB   +--.------+
              | SoftSerial
              |
           +--\----+
           | ESP01 |
           +-------+

And then upload this code to the Arduino. The code is from https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

/*
 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of ESP01)
 * TX is digital pin 11 (connect to RX of ESP01)

 Created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.
 */

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ;
  }

  Serial.println("Goodnight moon!");

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  mySerial.println("Hello, world?");
}

void loop() {

  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}


Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.

But in Pro mini 3.3 V level due to you need to Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module

using this you can easily convert the vlotage level.

if you have to make using simple component also using

SparkFun Logic Level Converter - Bi-Directional


What is this shield? (AST Space Arduino Kit)

My name is Bing Zhu. I the host of ASTSpace a community open lab sponsored by Zhejiang Association for Science and Technology(ZAST). AST is situated inside the Zhejiang Museum of Science and Technology. We are non-profit. The Kit you have gotten must be from someone got it free at one of ASTSpace's events. I remembered that we had brought some with us to the Manchester Science Festival where we did a tinkering activity for the public, 3 years ago.
This kit was designed by one of our members who is currently a Ph.D. student of automation at Zhejiang University. It was developed for the purpose to increase public experiences in a 90 minutes session. Therefore, in order to shorten the time of wiring while most times participants with no backgrounds or exposures to electronics make no sense anyway, we purposely had most of the functioning parts soldered on. In this way, we think it would be more manageable as well for teaching as most times one instructor has to manage more than a room full of over 25 participants. Making sure that parts are connected and in place can be a life-saver. We had it designed this way so the kit can be used in classes by schools in remote areas. These kits are given away and the introduction sessions are free to the public, and we intended to provide online help to those who decide to venture on with this kit at their own time. But, it never took off for time and resource restriction.  With this kit we have gone through two major cities in the Zhejiang Province and 4 remote rural areas.
All our expenses are supported by ZAST through two projects, one to make it and one to distribute it. When we did what we did, it was always for the public to know electronic control and coding was made easy by Arduino where it was first invented by an Italian who wanted to teach artists electronics.
This kit was used to demo how easily and readily everything can be controlled and through these electronics, we can take the parts of the physical world into our hands to follow our wills. We did use it to demo the on and off lighting system of the entire science center and controls of a remote camera inside the security room.
So, ASTSpace Arduino kit is a tailor-made kit for a specific purpose. We did not change anything but redesigned the wiring of the sensors for easy use for our events.


I can send on software serial, but not read?

Possibly the built-in UART (Hardware Serial) assigned to the same pins is interfering with SoftwareSerial? If you really want to us SoftwareSerial, try it on a pair of pins that has no hardware UART attached.

And/or try SoftwareSerial (again, on a non-UART pair of pins) to connect to your PC (after uploading; you can't upload with it), and use Serial1 to connect to your device. This isn't the recommended or easiest way but it might help debug the problems you're seeing.


Do you mean only accumulate during powered/driving, or also during standing still?

If the former, just get the start time in setup, then in loop continuously get the time and calculate the difference between it and the time read in setup. Since you don't know when power is lost you need to continually write the elapsed time to some form of non-volatile memory. You could use the Arduinos EEPROM, but that can wear out over time. It's better the use the DS1302s 31 byte of battery backed RAM. Next time the arduino starts up you need to read out this value and add this to the difference.

In case of the latter, you can halt the DS1302 so it stops incrementing time.


BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

You're writing sizeof(value) bytes to the Arduino. Since value is an int, which is typically 4 bytes in size for PC compilers/processors, when you send 20, what actually gets to the Arduino is 0x00000014. Your processor is apparently little-endian so the order of bytes sent is 0x14, 0x00, 0x00, 0x00.

You're reading a single byte in every loop() iteration. Your first sketch worked because you didn't provide any else clause for unrecognized bytes. The Arduino merely ignored those leading zeros. However, your second sketch handled unknown bytes (such as 0x00) by printing gggg. So what you get for every value you send to the Arduino is exactly what you'd expect and what you see in your shell -- the result you want (openn == 0x14), followed by 3 gibberish results (because of the leading zero bytes).

You can fix it by either declaring value as a uint8_t in your CPP code (after including stdint.h) or only reading chunks of 4 bytes on the Arduino and then parsing what you get. The former solution seems more reasonable/reliable.


Arduino Due analog output has 500mV offset

I don't know how old this thread is, anyway I thought it doesn't hurt to give some insight because I experienced the same problem. Look at:
http://www.atmel.com/Images/Atmel-42187-ATSAM3X-and-ATSAM3A-Series-Checklist_AP-Note_AT03462.pdf
page 13: DAC0 and 1 voltage lays between 1/6 ADVREF and 5/6 ADVREF which corresponds to approximately ADVREF=3.2v; Span is (4/6)*3.2 = 2.1v
for periodic signals, Offset can be removed by using a small decoupling capacitor which will act as a high pass filter.
Hope this helps


Connecting multiple TFT panels to Arduino Uno via SPI?

Yes, you can. All the SPI pins (MISO, MOSI and SCK) are all shared between the panels. You can even share the D/C and RST signals. The only signal that needs to be separate is the CS pin since this is the pin that identifies which panel is actively receiving commands and data at any one time. Also you don't need to connect up the MISO pin at all, since that is only connected to the SD card slot, not the TFT screen.

So each screen that you add just requires one more pin to be used. One screen uses 5 pins. Two screens use 6 pins. Three screens use 7 pins, etc.

And yes, for this the breakout version would be easier to work with than the shield version.


How to make a custom character on a TFT LCD display? (128x128)

Simple: you don't.

You only need to create a "custom character" on character-only displays (where you are actively programming a new character into the display's internal character set).

With a graphical display there is no "character" - only graphics.  The graphics library has fonts, which it then uses to convert text into graphics.

To display something that isn't in your currently selected font, just draw it. That could be from a bitmap graphic (there will be examples in your chosen graphics library) or using primitives, like circles and lines.


I imagine you want to use python because you are already familiar with it, know your way around the syntax, etc. But I would advice against this line of thinking, because microcontrollers need a little more of "low-level" thinking (given the limited resources they generally have) and because of that, it's probably best if you learn some C/C++.

The arduino programming framework provides some not-so-low-level libraries and tools (like the arduino IDE itself) to make it easy for non-C programmers to learn C-like programming.

However, if you want to use python as a proof of concept or anything else, sorry about the misunderstanding! :)


What you want to do is rather easy task, you just need to forget about delay() function. When writing some more complex programs using it is generally a bad idea, as it blocks code execution, so you won't get any sensor readings, communication, anything. Instead try something like this:

unsigned long delay1 = 100;
unsigned long delay2 = 1800000; //30 minutes in miliseconds
unsigned long t1, t2;

void setup() {
  t1 = t2 = millis();
}

void loop() {
  if(millis() - t1 > delay1) { //this will be executed every delay1 ms
    // do one part of code
    t1 = millis();
  }

  if(millis() - t2 > delay2) { //this will be executed every delay2 ms
    // do another part of code
    t2 = millis();
  }

  // here insert the code that should be executed as frequently as possible
  // (every loop passage)
}

There is also a nice Arduino library called TaskScheduler, that basically does the same thing: periodically executes different functions with different time intervals.


Using Li-Poly battery to run UNO + Adafruit data logger

You can't run the Arduino UNO directly from 3.7V.

You can use a boost regulator to step up to 5V and feed that into the 5V pin - in which case your question becomes null and void, since you are running at 5V, not 3.7V.

Or you can perform some hardware and/or fuse modifications and run the board directly from 3.7V into the 5V pin:

You will have to change the surface mount resonator to an 8MHz one instead of the normal 16MHz, or
Switch the clock to use the internal RC oscillator by reprogramming the fuses.

Either way you will then have to also modify the board configuration in the IDE to run at the new clock speed.

So given all that the simplest thing to do is to invest in a 5V boost regulator. Personally I'd suggest the LiPower Shield from Sparkfun. It also has a "fuel gauge" chip to monitor the batter charge.

Either that or scrap the Uno and invest in a development board that is designed to run from a Li-Poly / Li-Ion / LiFePO4 battery.


Why does timer1 not generate correct period on CTC mode with a resolution of 5us?

I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.

Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).

I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.

void setup()
{
    DDRD = B00001000; // pin 3 as output
    PORTD &= ~_BV(PORTD3);   // set 3 as LOW

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 9;

    // turn on CTC (Clear Timer on Compare Match) mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for clk/8 prescaler:
    TCCR1B |= _BV(CS11);

    // Output Compare A Match Interrupt Enable
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

ISR(TIMER1_COMPA_vect)
{
  PORTD = ~PORTD;
}


Trying to explain strange behavior when attempting to do a digitalWrite to A7 on a pro mini?

You are calling digitalWrite and digitalRead with argument A7.

According to the file pins_arduino.h, A7 is defined as 21.

Now, the two functions are defined in file wiring_digital.c, and the most important part is that both of them use this code to understand which register and bit to use:

uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);

Those two are not functions, but macros defined in the Arduino.h file:

#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This means that the positions are stored into two arrays, and each pin data is an offset from the beginning of the array itself. This means that the pin 0 is located on register digital_pin_to_port_PGM[0] (i.e. port D) and is in position digital_pin_to_bit_mask_PGM[0] (so bit 0).

Now, what about pin A7? It is in index 21. But look at the file pins_arduino.h:

const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PB, /* 8 */
    PB,
    PB,
    PB,
    PB,
    PB,
    PC, /* 14 */
    PC,
    PC,
    PC,
    PC,
    PC,
};

The array has only 20 entries! This means that A6 and A7 are NOT mapped. When you call the function with A7, you are going beyond the array limits.

This means that this leads to an unexpected behavior. In THIS particular case you are getting

PORT: _BV(1) = 2 which is equal to PB in Arduino.h
BIT: NOT_ON_TIMER = 0

So when you read from bit A7 you will check for

*portInputRegister(port) & bit
*portInputRegister(PB) & 0 => 0 for every value

so it always reads a LOW.

When you write any value to it, you will apply this code:

if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

bit is always 0, so if you write a LOW value you will write a HIGH on ALL bits connected to port B, otherwise you will write a LOW on all of them.

Different is the access to A6: the port will be mapped to 0, which is translated to NOT_A_PORT when detecting the register. This will try to read and write from/to register #0, which I admit I do not know what means. According to the ATMEGA328P register map it is reserved, so better not to use it.

Short answer: never try to use values which are not supposed to be used, otherwise you will incur in strange behaviors


L298N regulated output is greated than 5V

You are making an incorrect assumption, the L298N is an "H" bridge driver for small motors, not a 5V power supply. The 5 volt output is provided by a separate 78L05 regulator on the module.  This regulator cannot supply much power. Take a look at the schematic link given to you by ocrdu. Be sure all the grounds are connected.


Board and library updates required caused an error

This sounds very much like the problem I had when I updated my ARV version,I was also getting "no programmer has been specified error", I run Windows 7 32bit, the way i got out of it was to go back to the update screen when it pops up and in Arduino ARV Boards area....select versions....I went back to version 1.6.10...now it all works again.....at this point I am no longer updating my ARV, but I will after a few more version updates come out, there is obviously something that conflicts at this stage, if you google the problem you will find other of ways to fix this.


Arduino is freezing during Serial.Print() while passing a char array

Sorry, but there are quite a few issues with your code any of which may be contributing to your problem.

memset(&buffer,0,sizeof(buffer)); //0 out the buffer you are taking the address of a pointer and passing it to memset().  buffer is already a pointer of type char*.  Its working, because address of the pointer is the same address as buffer[0], but it is wrong and won't always work.
Serial3.print(F(cmd)); I have never used the F macro, but my understanding is it tells the compiler to store the string in flash memory.  cmd is a variable on the stack, a parameter to the function, so my guess would be the compiler is ignoring the F macro.
500 using a literal value in more than one place is opening you up to problems.  I think you should declare static const size_t BufferSize = 500;
void Response(char buffer[500]) It would be better to pass in a pointer to a char and the size as the parameter, (const char* pBuffer, const int& size) you can treat it the same within your function or you could pass a pointer to the next available item and then return the updated pointer.
1for(int i=0;i strlen(buffer))` then buffer can't contain RESP_OK (its quicker too).

Also the Response function won't compile, because you have too many closing braces (I assume its a copy and paste error).  This is the cause of you code hanging if(Serial3.available()) is inside a while(1) and there is no way of breaking out.  So if you just fix that you code will run.


VirtualWire `vw_get_message`: docs and examples on the PJRC site

The example with only vw_get_message is the common usage of the VirtualWire library. It returns true if something was received and the checksum was okay.
Yes, each message is seperated from the other messages. Each message gets extra bits (intro bits) and extra bytes (checksum and length).
I don't know, I have never tested that. Looking at the source code, there is no problem with zero length messages.

The VirtualWire library is outdated, although it is still used with Arduino boards with little memory (Arduino Uno, Nano, Leonardo, Pro Mini, and so on).
The RadioHead library (www.airspayce.com/mikem/arduino/RadioHead) has included the VirtualWire protocol with the RH_ASK mode. The examples for the RH_ASK mode shows that the usage is almost the same. The RadioHead library should be used when there is more memory (Arduino MKR, Zero, Due, and so on).


Modifying serial message for Adafruit NFC/RFID card

had to simply modify PrintHex in
Adafruit_NFCShield_I2C.h

to accept an additional argument


What minimum equipment is needed to program the Freematics Vehicle Data Logger?

"Arduino as ISP" refers to using an Arduino board in place of a USBasp.  It involves loading a specific sketch onto the Arduino then using the SPI port (and a few other pins) as the programming interface to the target.

It is most often used to program blank chips for use in breadboards by people who don't have a USBasp.  Great for moving your project from the Arduino board to a breadboard without having to buy a hardware programmer.


Legal or not, I DO NOT reccomend this clone. It is similar and compatible to some extend but it lacks features like an EEPROM. With fuses you can only reserve some FLASH to emulate an EEPROM. Thus have less space for your code.
Also the manual is only available in chinese. There are english translations but those are hard to read as the layout got screwed up.
It has some new features that sound great but I would not see them as replacement for the ATmega328P from Atmel/Microchip.

I bought an Arduino clone with LGT8F328P by accident. I find it barely usable as there are itches here and there which I don't want to deal with.


The newest blinkstick uses an addressable led, while the Adafruit kit appears to use a regular 4 pin RGB led. These are easier to get.

The digispark and the blinkstick are almost identical, but they use different pins for the USB connection. So to use the firmware for the blinkstick on the digispark, you need to change the pin numbers in usbconfig.h

#define USB_CFG_DMINUS_BIT      3
#define USB_CFG_DPLUS_BIT       2

PS. the pin numbers in usbconfig.h don't seem to match the schematic, so I'm not sure what's going on


LED strip problem... getting red when expecting white with lots of pixels. Fine with 1 pixel

According to https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels a Neopixel can consume 60 mA at full brightness white.

Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue). In actual use though, it’s rare for all pixels to be turned on that way. When mixing colors and displaying animations, the current draw will be much less. It’s impossible to estimate a single number for all circumstances, but we’ve been using 1/3 this (20 mA per pixel) as a gross rule of thumb with no ill effects. But if you know for a fact that you need every pixel on at maximum brightness, use the full 60 mA figure.

So your 144 Neopixels would require 8.4 amps. You would need a pretty solid power supply to supply that much.
One way of confirming that would be to measure the voltage in to the Neopixel strip (at the strip end) when it is displaying all white. I'd be surprised if it measures 5V.
The Amazon page you linked says:

Voltage: DC 5V
Power: 0.3W ± 0.01% per LED

That agrees with the figure of 60 mA (0.060A * 5V = 0.3W)

To put it another way, your power supply would need to supply 43.2W (144 * 0.3W). None of the bench power supplies I have here can put out 43W (or 8A), nor any of the wall-warts. You may have a really massive one, but you haven't specified what sort of power supply you are using.

I run them with a power supply (one that is working as expected, but still have it connected to the PC/USB?

Yes, there is a technique for doing that (similar to powering motors etc.).

You have one low-current supply to the Arduino (this could be your USB port even).
You have a high-current supply to the pixels/motor/whatever. This would require thicker cables.
You connect the grounds of both supplies so that they have a common ground reference.
The data line (the pixel information) is sent from the Arduino to the Neopixels

The one power supply can do both roles, just connect the wires together at the power supply end (this automatically connects the grounds, of course).
This way, the heavy-duty current does not go through the Arduino board.

If you are using the USB port for logic power you still connect the grounds like this:


The minimum reference voltage (VREF) for the ATmega8A is 2.0V. Your new reference is too low for the chip.


I had a project where I needed to run two steppers at the same time as they were moving a heavy load and were moving the same piece.

While a servo is going to move the desired spot, a stepper will not.

In the process of setting up the stepper you designated steps per rev and amount of steps to take at a time.

The stepper is only going to move the "amount of steps" at a time for each run of the code. I ran into a similar  problem and I had to put in a 2ms delay after the servo run command to make the motors run smoother and faster, other wise it sounded like a bunch of gears gnashing and skipping.  These steppers were facing each other that is why they move opposite directions.

if (down==true){
  TLstep.step(-step1);
  TRstep.step(step1);
  delay(2);
}

I know it been a year since this was looked at. Hope you got your issue figured out.


Measuring 12 V via voltage divider: choosing the right resistors

What you are looking for is called the Thévenin equivalent source.
For the schematic you are showing, and assuming you can neglect the
output resistance of the battery itself, the output resistance of the
voltage divider is the same as the two resistors in parallel. If you
want the maximum allowed resistance (minimum current) you have then to
solve:

1/R1 + 1/R2 = 1/(10 kΩ)
R2 / (R1 + R2) = 5/12

which gives:

R1 = 12/5 × 10 kΩ = 24 kΩ
R2 = 12/7 × 10 kΩ ≈ 17.1 kΩ

You can then round the values down to the closest standard values,
taking care that the rounding does not impose more than 5 V on the
analog pin. For example, if you restrict yourself to the E6 series, you
could choose

R1 = 22 kΩ
R2 = 15 kΩ

which would give you a Thévenin equivalent output resistance of
8.9 kΩ, and a maximum output voltage of 4.86 V.


Arduino Uno to Arduino Uno Word.doc file transfer

while(fileOut.available()){
    Serial.write(fileOut);
  }

This doesn't quite do what you think it does.

Instead you should send the file length first and then do:

for(unsigned long size = 0; i< fileLength; i++){
    Serial.write(fileOut.read());
}

You should also investigate some kind of rate limiting to avoid overwhelming the reciever and having to drop some bytes.


Moving average sticks in fictitious zeroes for the first readings. This delays accuracy

There are essentially two ways of initializing a low pass filter. The
first is to let it initialize itself “naturally” by feeding it data
until it reaches its steady state. This is the approach of jwpat7's
answer, and it works really well with FIR filters, like a plain
moving average.

Your exponentially-weighted moving average, however, is an
IIR filter. Given constant input, it converges asymptotically to its
steady state. After feeding it 10 values, it will only have reached 65%
of the steady state (exactly 1 − 0.910), thus you
may want to feed it significantly more than 10 points. E.g., you should
give it 22 points if you want it to be 90% initialized.

The other approach is to provision a specific initialization procedure
that sets the internal state of the filter to what it would have been
had it processed an infinite stream of constant values. This is actually
really easy to do with this particular filter, as we only have to set
the output equal to its first input. Here is the self-initializing
filter written as a function (this keeps the code cleaner):

static float movingAverage(float x)
{
  static bool initialized;
  static float output;

  // Initialize the filter as if this input had been on forever.
  if (!initialized) {
    output = x;
    initialized = true;
  }

  output += 0.1 * (x - output);
  return output;
}

You loose the benefit of the averaging on the very first data points,
but in return you have a simple to use self-initializing filter.

Unrelated to your question, I looked at your code and fond so many
confusing and useless statements that I felt compelled to remove all
that cruft. I did not test the simplified version though:

#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

static float movingAverage(float x) { ... }  // as before

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                      | (uint32_t) buffer[2] << 16
                      | (uint32_t) buffer[3] <<  8
                      | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(movingAverage(voltage), 8);
}


Its a long time since I looked at this and the details are a bit misty, so sorry for the inaccuracies, but I'm sure people will correct them for me :)

I originally brought one of these http://www.maplin.co.uk/p/maplin-replacement-wind-direction-sensor-for-n96fyn96gy-n81nf and then decided to take it to bits, like you do.

The vane spins a magnet around and this triggers 1 of 8 reed switches as it passes around.  The read switch is connected to VCC and a resistor and the resistors feed into a common wire back to the microprocessor.  The 8 resistors all have different values, so the result is a differing output voltage depending on which reed switch has been triggered.

So what you need is:

A magnet
A number of read switches positioned far enough apart so only one is triggered at a time
A number of different resistors

Supply 5V from you Nano and read the result on an analogue pin, then come up with a calibration table to work out the direction.

I hope that makes sense.
(Sorry I can't draw you a circuit diagram)


Simply because the Wiring system that Arduino stole was written for the Atmel chips.

Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino.


Can anyone help me figure out why this buffer is overflowing? (Updated)

My guess is this line:

memset(incoming, NULL, strlen(incoming));

When "incoming" hasn't yet been cleared, what is the length of it? It's whatever it counts up until the first '\0' character - and where is that character on the first run through? Who knows.

Instead you should memset the size of the buffer, not the number of non-NULL characters in the buffer:

memset(incoming, NULL, numChars);

However, that is a pointless operation, since you are storing a C string and (should be) properly terminating it, so it really doesn't matter what is in the array to begin with since you are just overwriting it anyway. So you can completely lose that whole function call.

You might like to re-write your receiving routine to use a switch/case construct instead of ifs and elses - it'll be much easier to follow:

#define EVER ;;

const int numChars = 15;
char buffer[numChars];

void Get() {
    int pos = 0;
    bool receiving = false;

    for (EVER) {
        int K = Serial.read();
        switch(K) {
            case -1: // Nothing to read
                break;

            case '\n': // Got the end of the string.
                if (receiving) return; // We have a valid string.
                pos = 0; // Reset pointer to start of buffer
                break;

            case '~': // Starting a new string
                pos = 0;
                receiving = true;
                break;

            default: // Any other characters.
                if (receiving) {
                    if (pos < numChars-2) {
                        buffer[pos++] = K;
                        buffer[pos] = 0;
                    }
                }
                break;
        }
    }
}


Your issue seems to be byte order (big endian) and not bit order. The simplest solution to byte order swap is to use the builtin functions provided by the compiler (AVR GCC).

unsigned long cardCode;
...
Serial.print(__builtin_bswap32(cardCode), HEX);

There are two compiler builtin functions for byte order swap. One for 16-bit data and one for 32-bit data.

uint16_t __builtin_bswap16(uint16_t);
uint32_t __builtin_bswap32(uint32_t);

AVR MCUs are little endian (least significant byte first in memory). There are many devices that use big endian (most significant byte first). This is also known as network order. There are a set of functions/macros to help write portable code, especially device drivers.

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

These are used to map data from host to network byte order and reverse. They are defined as byte swap functions for hosts with little endian byte order. Unfortunately they are not available in the GCC AVR library but easy to define.

#define htonl(x) __builtin_bswap32((uint32_t) (x))
...

Cheers!


esp8266 garbage out only when using SoftwareSerial

Try dropping the SoftwareSerial connection speed to 19200. Ie, esp8266.begin(19200). 115200 it is the absolute max the SoftwareSerial can theoretically handle.
Also if you are not using all the change interrupt pins on your MCU (Uno/Nano?) then use any 2 pins from 10, 11, 12 or 13 rather than 3, 2 // RX, TX.
Not sure about sendCommand function. If you just want to test the connection then it should be as simple as:

SoftwareSerial esp8266(10, 11); // RX, TX

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

    char buffer[50];
    esp8266.write("AT\r\n");
    esp8266.readBytes(buffer, sizeof(buffer));
    Serial.println(buffer);

...
}

Obviously once you need to open web pages and recieve responses then you will need a libary to handle IDP+ data. With a bit of coercion I got Adafruit_ESP8266.h working with SoftwareSerial.


Ideal settings for regulated power using Arduino Uno VIN?

Honestly, it doesn't matter how much power (amps) you make available, it will only draw what it needs.

However, there is definitely something to be said for limiting how much power you provide.  If something in your circuit is miswired or otherwise shorts out, limiting the circuit to something reasonable (wisely including a fuse in your design as well) means that you won't have some enormous current suddenly passing through burning stuff out and possibly injuring someone. :)

As far as what to provide in terms of volts and amps, the data sheet for your particular arduino is the place to go.  As long as you are providing that you are in good shape.


Need some help in coding a "timer" in an if else statement

A flowchart is not bad, but it's not really the most appropriate kind of
diagram for this sort of problems. You should try to think in terms of
finite state machines instead, which is a very useful concept
whenever you try to implement “reactive” systems, i.e. systems that have
to react to some kind of input.

Here is your problem, as I understand it, translated into a state
diagram:

This system has two states:

“waiting”, when it waits for the first button to be pressed
“stand by” when the first button has been pressed and it waits for the
second.

Pressing button 1 makes a transition from “waiting” to “stand by”. The
transition back to the initial “waiting” state can be triggered by two
distinct events:

3 seconds spent in the “stand by” state
the user pressing button 2.

Note that in the second case, the system runs your code while making the
transition.

Once you have the state diagram, and assuming you have read (and
understood) the finite state machine tutorial I linked to, translating
the diagram into code is almost trivial.