Can you activate the whole pixel on LCD? I'm working on a project where I'm trying to display the level of a filled tank through ultrasonic, then displaying it on a 16x2 LCD. I'm trying to do it through the whole LCD Pixels, such that when the tank level is full, the first 5 pixels are activated (as what happens when you connect the LCD initially without having any code for it, the whole pixels are turned on, giving 16x2 white rectangles, as shown in the picture below). Is there a way to activate an entire pixel on the LCD?

The LCD is made up from 32 characters each is 5x7 pixels in size, with a 1 pixel gap between each character.

You can never put anything in the gap between the characters, as there is just nothing there.

But what you can do is define your own characters to fit within the 5x7 pixel rectangles.

Some variants of the HD44780 have character 255 as a solid block, but not all (it depends on what language the ROM is).  If you have one that has that character you can just print it with lcd.print("\xff") or lcd.write(255).  If it doesn't it will print ÿ instead. In that case you will have to define your own character.

One benefit of defining your own characters is that you could then do partial blocks to give you a higher resolution.  Here's an example:

You can find that example and the code that goes with it here.


Controlling an LED using SIM900A and Arduino How can I turn the LED on and off using a received text message?

The sim card is able to receive the message but I can't change the pin status. I also can't see anything in the serial monitor upon reception of the message.

Below is my code.

#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }
  if (gsm.available()>0)
  Serial.write(gsm.read());

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  }
  if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 if (gsm.available()>0)
 {
  msg=gsm.read();
  Serial.print(msg);
 }
}

Try this code.

#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}


Arduino Due SPI speed reduction I need to reduce the SPI clock speed of the Arduino Due down to about 100 kHz. Unfortunately my hardware doesn't support higher speeds.

With the current maximum divider of 255, I can only reach a speed of still 320 kHz (SPI.setClockDivider(10, 255);).

Of course I could use a software SPI, but I'm still interested in using the build-in hardware. A possible solution could be to lower the overall clock speed of 84 MHz. Any idea how to achieve this?

You can try using the SPISettings interface:

SPISettings settings(100000, MSBFIRST, SPI_MODE0);

SPI.beginTransaction(settings);
... do your stuff ...
SPI.endTransaction();


Do I need to solder wires to my tilt sensor? I am using the Arduino Starter Kit and I am on project 8. The picture of the sketch in the book is not clear because it shows the tilt sensor seemingly resting sideways, which is not the way that it connects. If you insert the pins into the board the sensor will always be standing and there will be no way to turn it. I was thinking you might have to solder wires to the pins. Does anyone know?
-Thanks
Edit: Perhaps this picture will help:

I don't have the starter kit but I have a tilt ball sensor:

My guess is that there is a ball inside it, and it connects the wires, like this:

This is confirmed by measurement.

I suggest you either solder wires to it, or push the wires into your breadboard. As you can imagine from the diagram, the contacts will be closed if the ball (or mercury or whatever it is) is downwards. In other words, if the leads are facing down. As you tilt it, the ball will move away from the two wires, breaking the connection. You may have to tilt it quite a lot for this to happen.

(Edited to add)

I see from the Arduino Starter Kit page that the tilt sensor works like this:

This shows that my guess was pretty accurate. :)

There are four pins, so I imagine that the ball would connect four of them if held upright, and various combinations if tilted forwards or sideways.

  If you insert the pins into the board the sensor will always be standing and there will be no way to turn it.

Well, you could tilt the breadboard, yes?

However I agree that if you want to tilt just the sensor, then soldering wires to it would seem quite sensible.

I think the starter kit is there to show you the concepts. There is nothing stopping you tilting the entire breadboard to see how it works. In practice you would mount the sensor in such a way that it activated when moved from position A to position B, whatever that is.


Arduino Nano problems with ESP8266 this is my first post here because I'm a bit lost at the moment.
I currently have my ESP8266-01 hocked up to the Nano like this:

The issue I'm having is that it won't even turn on, only when I'm using the 3.3V pin the red led on the ESP8266 turns on. If connected to 3.3V and I connect the CH_PD pin to 3.3V aswell, the blue led flashes 2-3 times and then the ESP8266 turns off.

I hope someone is able to help me

You need to supply power to the ESP to make it turn on.  What you have done at the moment is got the ESP to supply 3.3V to the level shifter, which you need to do.

You need to supply 3.3V to the ESP from somewhere other than the Arduino, it doesn't have the current necessary.


Arduino Nano clone doesn't fit into breadboard. How can I work around this? I have bought an arduino nano clone (called funduino) and upon trying to place it into my breadboard to work with it I realised that the pins do not line up with the holes on the breadboard so I simply can't use the funduino...

Does anyone have any recommendations on how I can get around this?

You might be able to use these female to female jumper wires and these headers and hook up the board and breadboard like this:

Note, the square female cable ends may not fit closer than 0.1 inches on center.

A more compact and (possibly) mechanically difficult solution may be implemented using wire-wrap sockets.  You may be able to leave the sockets intact and deform the pins to match the breadboard.  Or you may need to remove the pins from the plastic in order to accommodate your (different) Nano:


Safe place to download CH340G drivers from I am working with an Arduino Uno clone that uses the CH340G USB to TTL converter in lieu of the 16U2 found on the Uno. I see that most tutorials suggest downloading the CH340G drivers from what they call "a chinese website". I don't quite trust that site, is there any more trustworthy website where one might be able to acquire CH340G drivers for a modern Linux distro (preferably CentOS or Debian).

I ask here because devices with that chip seem to be popular in the Arduino community. If the unix stackexchange site would be a better place to ask then the question can be moved. Thank you.

EDIT: Apparently my system is having an issue with recognizing the device. Here are some specs:

$ lsusb
Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 004: ID 04d9:3015 Holtek Semiconductor, Inc.
Bus 003 Device 003: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11n
Bus 003 Device 012: ID 045e:0040 Microsoft Corp. Wheel Mouse Optical
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

$ lsusb | wc -l
9

$ # Now I plug in the Uno clone
$ # Wait about a minute just to be sure...
$ lsusb
Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 004: ID 04d9:3015 Holtek Semiconductor, Inc.
Bus 003 Device 003: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11n
Bus 003 Device 012: ID 045e:0040 Microsoft Corp. Wheel Mouse Optical
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
$ lsusb | wc -l
9

$ uname -a
Linux happiness 4.4.0-47-generic #68-Ubuntu SMP Wed Oct 26 19:39:52 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/issue
Ubuntu 16.04.1 LTS \n \l

My entire dmesg file can be found on pastebin, here is the end of it:

[37253.943739] usb 3-6: device descriptor read/64, error -71
[37254.159669] usb 3-6: new full-speed USB device number 15 using xhci_hcd
[37254.159841] usb 3-6: Device not responding to setup address.
[37254.363858] usb 3-6: Device not responding to setup address.
[37254.567744] usb 3-6: device not accepting address 15, error -71
[37254.679654] usb 3-6: new full-speed USB device number 16 using xhci_hcd
[37254.679756] usb 3-6: Device not responding to setup address.
[37254.883917] usb 3-6: Device not responding to setup address.
[37255.087716] usb 3-6: device not accepting address 16, error -71
[37255.087749] usb usb3-port6: unable to enumerate USB device

Linux doesn't need drivers (indeed, the whole concept is pretty alien to Linux users).

The CH340G is fully supported by the default kernel in all distros I have ever used. On my Ubuntu machine the CH340G on my NodeMCU is detected automatically:

[ 8195.450566] usb 4-1: new full-speed USB device number 2 using uhci_hcd
[ 8195.630710] usb 4-1: New USB device found, idVendor=1a86, idProduct=7523
[ 8195.630714] usb 4-1: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[ 8195.630716] usb 4-1: Product: USB2.0-Serial
[ 8196.675137] usbcore: registered new interface driver usbserial
[ 8196.675153] usbcore: registered new interface driver usbserial_generic
[ 8196.675166] usbserial: USB Serial support registered for generic
[ 8196.677581] usbcore: registered new interface driver ch341
[ 8196.677600] usbserial: USB Serial support registered for ch341-uart
[ 8196.677620] ch341 4-1:1.0: ch341-uart converter detected
[ 8196.690670] usb 4-1: ch341-uart converter now attached to ttyUSB0

Nothing to download, nothing to install, nothing to risk the security of your system with.


Switching between SPI Devices when one is an SD card I'm using a USB Barcode scanner connected via a USB shield, I'm able to get the readings from the barcode using this example, After getting this readings, I'd like to save it to an SD card but the SD card won't initialize since the barcode also uses SPI, how can I deactivate the ICSP in order to activate the SD card? Or how to switch between multiple SPI slaves?

with SPI there is an implicit slave select pin on each device that must be pulled low to enable the device.

Connect each slave select pin of the SPI device to their own unused digital pin on your arduino and keep it pulled high until you want to talk to the slave.

However not all SPI devices will properly put the MISO pin into high impedance when SS is pulled high so you may need to use a tristate buffer on that pin or use a multiplexer.

When adding your own tristate buffer (for example a HS125) you need to connect each MISO pin of the SPI device to the input of a buffer, the slave select is then connected to the output enable pin of the tristate. The outputs of the buffers can be connected together along with the MISO pins of the devices that do properly go high impedance to the MISO of the master.

When using multiplexers there are 2 options:

You can daisy chain 2:1 multiplexers by connecting the MISO of the device to the 0-input of the mux and the Slave select to the select input pin of the mux.
you can use a >2 multiplexer to select the correct MISO line based on the address of a set of S lines. Then with a decoder you can provide the actual SS signal to the SPI device. This way you only need 2 SS pins for 4 SPI devices.


Output 3.3V when setting pin to high I would like to pass 3.3V and Ground to an component. How can I achieve such a thing?

I for example would like to let a wire get 3.3V when I for example do digitalWrite(pin, HIGH). It is hard for me to explain this, so I created an illustration in the hope of better clarifying it.

Edit: I have an product that I have dismantled. On the PCB, there is a push button. I would like to solder some wires to the place where the button is so it can be controlled with an arduino (probably wemos d1). When plugging a cable in the 3.3v of the arduino and a cable from the ground, when connecting it to the push button it will cause a boot of the dismantled product. This explains why I would like to give power to a component ONLY when a pin is set high, so I can for example boot the product via a website / app eventually.

The normal way is to use a P-channel MOSFET as a "high side" switch.

simulate this circuit – Schematic created using CircuitLab

R1 keeps it switched off under "normal" circumstances.  Driving D4 LOW makes M1 turn on and allow power through to the "component".

Make sure that the MOSFET has a threshold voltage of no more than (less than?) -3V (that is, somewhere between 0V and -3V - note: P-channel MOSFETs have their thresholds quoted as a negative voltage).

You could connect R1 to 3.3V instead of 5V, but since the  GPIO would have 5V on it when HIGH it would be wasting power while idling - so it's better to pull it to 5V instead.


ESP8266-12E as WiFi interface for Arduino Mega I have an Arduino Mega 2560 that I would like to connect to the internet using an ESP8266-12E.

Searching the internet for relevant keyphrases only yielded one type of result: The articles all explain how to program the ESP using the Arduino. Been there, done that.

Does anybody know of a way to use the ESP as a "wifi interface" for an Arduino, e.g. using a Serial interface from the Arduino?

Basically, I'd want to use the library ESP8266Wifi transparently on my Mega 2560, and maybe in conjunction with something like WifiManager - all of that running on the Mega.

The only thing I found was this: https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e. But this uses AT commands only.

Any hint is appreciated.

If you know how to write code for the esp8266, then write the networking part in the esp8266 and exchange data and commands with the sketch in Mega over Serial.

Other option is to use AT firmware with the WiFiEsp library or WiFiLink firmware with WiFiLink library.

Or you can connect the ESP-12 to Mega over SPI and use the WiFiSpiESP firmware with WiFiEsp library.

All mentioned libraries are 'clones' of the WiFi library.


Initialize object with PROGMEM constants I have a class which has a const char * property:

    class A
    {
    public:
        const PROGMEM char* text;
    };

    void setup()
    {
        // A a{"Hello World!"};
        // A a{PSTR("Hello World!")};

        A a;
        a.text = PSTR("Hello World!");

        Serial.begin(9600);
        delay(30);
        Serial.println(a.text);
    }

    void loop()
    {
    }

I’d like to spare some RAM using PROGMEM.

How to initialize a object then?

Obviously, it can’t be like this:

    A a{PSTR("Hello World!")};

This will do:

    A a;
    a.text = PSTR("Hello World!");

However, I need to pass string to the constructor.

const char* text; is a pointer to constant not a constant pointer (char * const text is a constant pointer). So you can assign a pointer to a constant char array to const char* text; even a pointer to an array in PROGMEM.

The compiler doesn't know the difference between a PROGMEM pointer and a pointer in SRAM. It is on you to work in code with a pointer to PROGMEM the right way.

so remove PROGMEM from const PROGMEM char* text;

add constructor to initialize an object.

A(const char* _text) {
  text = _text;
}

and then

A a(PSTR("Hello World!"));

EDIT:

you could use Arduino's F() macro and __FlashStringHelper type, because it is supported by Serial print and co.

class A
{
public:
  A(const __FlashStringHelper* _text) {
    text = _text;
  }
  const __FlashStringHelper* text;
};

void setup()
{
    A a(F("Hello World!"));

    Serial.begin(9600);
    delay(30);
    Serial.println(a.text);
}

void loop()
{
}

__FlashStringHelper type is trick to distinguish PROGMEM strings from char arrays in SRAM..


LED Blinking Using Push button Whenever I upload the following program I am getting error message
showing "expected initializer before interval".

Kindly Help me to solve out this probleme.

const byte button=2;
const byte LED=10;
bool blinking =false;//defines when blinking should occur
unsigned long blink Interval=250;// number of milliseconds for blink
unsigned long currentMillis;// variables to track millis()
unsigned long previousMillis;
void setup()
{
    pinMode(button,INPUT);
    pinMode(LED,OUTPUT);
}
void loop()
{
    // this code  blinks the LED
    if(blinking) {
        currentMillis =millis();// better to store in variable, for less jitter

        if((unsignedlong)(currentMillis-previousMillis) >=blinkInterval) { // enough time passed yet?
            digitalWrite(LED,!digitalRead(LED)); // shortcut to toggle the LED
            previousMillis =currentMillis;// sets the time we wait "from"
        }
    } else {
        digitalWrite(LED,LOW); // force LED off when not blinking
    }

    int reading=digitalRead(button);
    delay(50); // crude de-bouncing

    if(reading==LOW) // buttons with pull-up are pressed when LOW
    { blinking =true; }// start blinking
    else
    { blinking =false; }// stop blinking
}

It is blinkInterval, not blink Interval. You have an space in the name in the declaration:

unsigned long blinkInterval=250; // number of milliseconds for blink
// ....
if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {


While condition with & bitwise of PINx read I was looking into ATmega32u4 datasheet to configure the SPI, and there is initialization snippet for data transmission.

void SPI_MasterTransmit(char cData)
{
/* Start transmission */
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)));
}

What I didn't quite get is the last line of the snippet with the while condition to check the state of the SPIF bit in SPSR register.

What I think I understand that it means, if SPIF bit with the a conditional value of 1 which would be in the ALU for comparing it with the actual bit state in SPSR. If this is true with & bitwise operator which would be true if the actual bit in the SPSR is set with the given value (1 << SPIF).

My questions:

Am I understanding it right?
What this line actually means?
I have removed the semicolon at the end of the line and it compiled OK! Is what I did OK?

SPI transmitt is started by writing one Byte into SPDR. And this code won't return from SPI_MasterTransmit function before it's complete. Transmitt completition is anounced by setting SPIF by hardware (and if SPI interrupt and global interrupts are enabled, it'll run also ISR and clear that flag).

If you write into SPDR before transmission is completed you'll corrupt current "transaction", so you have to wait until it's complete before another write.

Bitwise & is used for bit masking. Bits in the result are set if bits at corresponding positions in arguments are both set:

0b00110011
         &
0b00100001
        ==
0b00100001

So if bit at position SPIF is not set, it will loop again and when it's set, it exits the loop, as there is inverted logic.

( SPSR     & (1<<SPIF))                    !(SPRS &(1<<SPIF))
0b0xxxxxxx & 0b10000000 == 0b00000000  =>  !0b00000000 == true
0b1xxxxxxx & 0b10000000 == 0b10000000  =>  !0b10000000 == false


Serial.print prints but lcd.print does not The following code reads a txt file from a SD card, finds the corresponding character and prints the next 12 characters:

...
      char temp;
      byte who = random(1, 13); // 1 to 12
      temp = findName(who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    char findName (byte number) {
      char text[12];
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
      return text;
    }

But the following, on a LCD, does not. (setCursor, etc. ommited for clarity)

...
char temp;
byte who = random(1, 13); // 1 to 12
temp = findName(who);
lcd.print(who);
lcd.print("  ==> ");
lcd.print(temp);
...

I'm certain the cause is a variable data type mismatch, but I don't know how to solve it. Any help is appreciated.

Thank you.

In the findName() function, you declare a char array of name text. Internally, text is a pointer to a block of memory 12 bytes in size.

When you return text within the findName() function, you are passing back the pointer to the block of memory. The return type of char is inconsistent with the return command. But probably more problematic is that once findName() ends, the memory set aside for the text array is marked as unused. It is no longer reserved for holding anything and may be reallocated at any time by some other function or operation.

In C/C++, array variables do not refer to the entire array, but to the first element in the array. The fact that your program works with Serial.print() is probably just good luck. lcd.print() may declare some variable or buffer which overwrites what the findName() function had put in those 12 bytes.

There are many approaches to take to resolve this. One way is to declare char arrays in the "highest" scope in which it will be used, and to declare it with the largest size that you could ever see in the operation of your program.

In your case, you can:

...
      char temp[12];
      byte who = random(1, 13); // 1 to 12
      findName(temp, who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    void findName (char *text, byte number) {
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
    }

What this does:

temp is now the char array
findName() takes the pointer to the char array, and the number as arguments
findName() modifies text, which refers to the same block of already-allocated memory as temp, and that block of memory does not go away at the end of findName().
Because findName() is not returning a value, it's return type is void.


Code that worked in Uno is not working in Mega 2560 I send data with Android and read it from the Arduino serial screen. When I use UNO, I can read the data smoothly. When I use MEGA, it uploads the code without error, but does not transfer data on the serial screen. Can you tell me why?

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(2,3);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int strip_anim=0;
int motor_speed=1;
int direct=0;
int level=0;
boolean debug = true;

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  Serial.println("Program is starting...");
  Serial.println("by Berke Ogulcan Parlak");
}

void loop() {
  if (bluetooth.available()) {
    while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      strip_anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(strip_anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {
        azdırma işlemleri bu satırda yapılacak..

      }
    }
  }

}

SoftwareSerial relies on the Pin Change interrupt. Not all pins on the Mega have pin change interrupts.

But that is all a moot point really, because when you're using a microcontroller that has lots of real hardware UARTs there is no call to be using SoftwareSerial in any case.


Is it necessary to set a function with always_inline attribution when the function would work maybe once? I'm going through a library for the ILI9488 running by SPI and want to copy this library in my version.
In the beginning of the source file, there's a guard for the SPI_HAS_TRANSACTION that if the library would run in Arduino compiler then it would use the SPI functions, otherwise it should run from another platform SPI libraries.
Library link:
jaretburkett / ILI9488
This is the part of code I have questions about:
// If the SPI library has transaction support, these functions
// establish settings and protect from interference from other
// libraries.  Otherwise, they simply do nothing.
#ifdef SPI_HAS_TRANSACTION
static inline void spi_begin(void) __attribute__((always_inline));
static inline void spi_begin(void) {
#if defined (ARDUINO_ARCH_ARC32)
  // max speed!
  SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
#else
    // max speed!
  SPI.beginTransaction(SPISettings(24000000, MSBFIRST, SPI_MODE0));
#endif
}
static inline void spi_end(void) __attribute__((always_inline));
static inline void spi_end(void) {
  SPI.endTransaction();
}
#else
#define spi_begin()
#define spi_end()
#endif

My questions:

why the programmer first declare the function in source file not in header file ?
why to use always_inline attribution for a function that's is most the time used once in program file and it's not likely to be used many times during operating time ?
what does this define means ARDUINO_ARCH_ARC32 and where to find it ? I searched in all files in arduino folders and didn't find it. Is it dedicated for fast boards or the usual 16MHz arduino boards ?

Edit:
I want to add another question for the same library.
This function content:
void ILI9488::spiwrite(uint8_t c) {

  //Serial.print("0x"); Serial.print(c, HEX); Serial.print(", ");

  if (hwSPI) {
#if defined (__AVR__)
  #ifndef SPI_HAS_TRANSACTION
    uint8_t backupSPCR = SPCR;
    SPCR = mySPCR;
  #endif
    SPDR = c;
    while(!(SPSR & _BV(SPIF)));
  #ifndef SPI_HAS_TRANSACTION
    SPCR = backupSPCR;
  #endif
#else
    SPI.transfer(c);
#endif
  } else {
#if defined(ESP8266) || defined (ARDUINO_ARCH_ARC32)
    for(uint8_t bit = 0x80; bit; bit >>= 1) {
      if(c & bit) {
    digitalWrite(_mosi, HIGH);
      } else {
    digitalWrite(_mosi, LOW);
      }
      digitalWrite(_sclk, HIGH);
      digitalWrite(_sclk, LOW);
    }
#else
    // Fast SPI bitbang swiped from LPD8806 library
    for(uint8_t bit = 0x80; bit; bit >>= 1) {
      if(c & bit) {
    //digitalWrite(_mosi, HIGH);
    *mosiport |=  mosipinmask;
      } else {
    //digitalWrite(_mosi, LOW);
    *mosiport &= ~mosipinmask;
      }
      //digitalWrite(_sclk, HIGH);
      *clkport |=  clkpinmask;
      //digitalWrite(_sclk, LOW);
      *clkport &= ~clkpinmask;
    }
#endif
  }
}

what I understood from this is that the programmer wants the library to be more versatile to support AVR chips programmer by another IDE than Arduino, also supports ESP8266 and anything else should be handled by softSPI, actually pretty smart coding I guess.
My question here, is does #if defined (__AVR__) checks for either AVR/Arduino in general and when specifies SPI_HAS_TRANSACTION means Arduino SPI library specifically ? right ?

Here I am only addressing question number 2. The others have already
complete answers.
The choice to whether a function should be inlined or not is a
speed/size trade-off. There is a cost to calling a function. On AVR, for
example, the call instruction takes 4 CPU cycles, and ret takes
another 4. Inlining the function removes this cost. On the other hand,
you end up with as many copies of the function as places where it is
inlined, and this in turn costs flash memory.
The compiler is usually smart enough to make wise decision regarding
function inlining. In this case, it is not obvious what decision it
would make on its own. On the one hand, the function is used multiple
times in the code, which makes a good case against inlining it. On the
other hand, the body of the function is tiny: only setting up some
registers (the two parameters of SPIClass::beginTransaction(),
including the implicit this) and jumping to another function,
so the cost of inlining is small.
For this library, the programmer happened to have a strong opinion on
this matter, and he though inlining was really the best option. Also, he
did not thrust the compiler to make the good decision. This is the
reason why he used the gcc extension:
__attribute__((always_inline))

And no, it is not necessary, it is just an optimization choice.


Connect 4 HC-12 transmitters to 1 HC-12 receiver I am currently receiving data from HC-12 modules via USB-TTL that are working in pair . But I want to receive data simultaneously from 4 Hc-12 modules to a single HC-12 module via USB-TTL.

When a HC-12 is transmiting all other HC-12 in his range (using same frequency) are receiving. So if you want your transmiter to talk to one specific HC-12 then to an other and so on, you have to create a kind of "message protocol".
Let's say you have an Arduino with a HC-12 and 4 buttons and want to turn on-off 4 lights, each connected to a HC-12. You can use a binary representation, so a byte, on which each bit as a meaning.
Bit 0 -> at 1 -> turn on the light at 0 turn off
Bit 1-2 -> give the number of the HC-12
So 00000111 -> message for HC12 number 4, tell it to turn on the light.
ALL HC-12 will receive the message. So each has to check the incoming byte to see if "it's for me" or nor.
If you want one HC-12 to receive from many HC-12, that's the same: the message must contain the "id" of "who is sending".


Arduino nano and wemos sd shield Is it possible use Arduino nano with wemos sd shield? If I can, how to I connect sd shield to arduino and what modification I need to do on library setting?

No, you can't. The WeMos boards operate at 3.3V, and so does the SD card. If you want to use a 5V Arduino with a 3.3V SD card, you'll need voltage level shifters.

The schematic of the WeMos SD shield will tell you what SD connections go to what pins. Then just google how to use an SD card with Arduino to connect those pins to the correct Arduino pins.


Looking for a Mega 2650 drawing or picture that shows the components labeled I am Looking for a Mega 2650 drawing or picture that shows the components labeled.

I've seen the schematics but didn't find a labeled assembly drawing yet.  Should this exist?

Thanks

Yes, it exists, but not (commonly) as an "image" in the traditional sense.

You need to install Eagle PCB design software and open the PCB file downloadable from the Arduino site from where you can see exactly which component is where.


Solution needed for sending HTTPs requests from multiple Arduino units in the field I'm using the Arduino Wifi Nina Library to connect an Arduino Uno Wifi Rev2 to wifi and then using the Arduino HTTP Client library to make HTTP post calls to the internet. It is working. However when I switch from HTTP to HTTPs (ie: switching the port to 443 from 80) the code below fails. I understand This is because I don't have a cert on the Arduino. I need to purchase/obtain a cert and download it to the Arduino.

I need to find a solution to this problem that meets the following constraints I have:

I will only be sending https requests to one URL:
https://api.mailgun.net
The amount of memory storage available on Arduinos is severely constrained
I plan to deploy this Arduino into the field. After I deploy it, I will no longer be able to physically access it to manually update any expired certificates. But the Arduino unit must be able to send HTTPs requests to https://api.mailgun.net in perpetuity.
I plan to deploy not just this Arduino unit, but a fleet of similarly functioning Arduino units with the same functionality. And I need to keep the costs of any certificate(s) to an absolute minimum.

    #include <WiFiNINA.h>
    #include <ArduinoHttpClient.h>

    #define REMOTE_SERVER_DOMAIN "api.mailgun.net"
    #define REMOTE_SERVER_PORT 443
    #define MAILGUN_USER "my-user"
    #define MAILGUN_PASSWORD "my-secret"

    bool sendEmailViaHTTPS()
    {
        WiFiClient wifiClient;
        HttpClient httpClient = HttpClient(wifiClient, REMOTE_SERVER_DOMAIN, REMOTE_SERVER_PORT);
        httpClient.beginRequest();
        httpClient.post("/v3/sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org/messages");
        httpClient.sendHeader("Content-Type", "application/x-www-form-urlencoded");
        httpClient.sendBasicAuth(MAILGUN_USER, MAILGUN_PASSWORD);
        String postData = String("from=Mailgun%20Sandbox%20%3Cpostmaster%40sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org%3E&to=Me%20%3Cmyemail%40gmail.com%3E&subject=Hello%20World1&text=Hello%20World2");
        httpClient.sendHeader("Content-Length", postData.length());
        httpClient.beginBody();
        httpClient.print(postData);
        httpClient.endRequest();
        int statusCode = httpClient.responseStatusCode();
        String response = httpClient.responseBody();
        Serial.print("Status code: ");
        Serial.println(statusCode);
        Serial.print("Response: ");
        Serial.println(response);
        return statusCode == 200;
    }

What is the best solution to enabling my Arduino to send HTTPs requests as stated above with the least cost and friction?

For secure TCP connection with WiFiNINA library use WiFiSSLClient instead of WiFiClient.

The Arduino firmware in the NINA ESP32 module has certificates of well known CA authorities so the server's certificate verification should work. If necessary, you can add public keys of server certificates to NINA.


Switch to drive Arduino and optocoupler At the moment I have a switch that connects to a digital pin on an Arduino as per the schematic below.  (Obviously there is an pull-up resistor on the pin).

simulate this circuit – Schematic created using CircuitLab

I now want this switch to also connect to another Arduino via an optocoupler. Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Probably not, because of two issues.  First, adding circuit elements between the switch and ground raises the voltage the pin will see when the switch is closed, which might keep a switch closure from registering as a low pin voltage.  For example, with Vcc=5V, table 30.2 DC Characteristics in the Rev. 8271J 11/2015 ATmega328P datasheet shows the guaranteed maximum input low voltage as 0.3 Vcc and the guaranteed minimum input high voltage as 0.6 Vcc; that is, 1.5 V and 3 V if Vcc=5V.  If the voltage drop across the optocoupler is between 1.5 and 3 V then the pin might register high or low with no guarantee which.

Second, if the pullup is large, not enough current will flow to trigger the optocoupler.  For example, at Vcc=5V if the internal pullup is used and the optocoupler drops two volts, I/O Pin Pull-up Resistor Current will be about 80 μA, too little to trigger a typical optocoupler.  (See figure  35-17, ATmega328P: I/O Pin Pull-up Resistor Current vs. Input Voltage (Vcc = 5V) in datasheet.)

What you might do instead is use two optocoupler channels in parallel or series, one for each of the Arduinos.  The switch lets current pass through an appropriate resistor or resistors and the optocoupler inputs;  optocoupler outputs go to  Arduino inputs.

Or, tie one side of the switch to +5V and the other to a resistor in series with an optocoupler input.  Connect the first Arduino's input pin to the low side of the switch.  I think that input will register low when the switch is open.  It will register high when the switch is closed.


DS1307 RTC not working with CC3000 WiFi shield (I2C bus hangs) I am trying to use a DS1307 (from Sparkfun, BOB-12708) with an Arduino Leonardo. I have connected the SDA, SCL, GND, and 5V pins from the RTC to the Arduino. However, with a CC3000 WiFi shield on the Arduino, the I2C bus hangs. Specifically, Wire.endtransmission() hangs, called by rtc.isrunning(). I have confirmed that it works properly on the same Arduino without the WiFi shield. I am using the ds1307 RTClib example for testing it.

It could be that the CC3000 interrupts are affecting the Wire library's behaviour since the latter is interrupt-driven itself.
Try disabling the CC3000 IRQ before calling rtc.isrunning() or any other RTC functions. First #include "ccspi.h" in your sketch. Then place WlanInterruptDisable() before any RTClib function call, and then WlanInterruptEnable() after the RTC function returns.

Even if this works, it may affect the functionality of the CC3000, since it increases the chances of missed interrupts. You can search for DS1307 libraries that employ SoftwareI2C instead such as this one. They should be better able to recover from the CC3000 interrupts.


Error saying an included library is not The IDE tells me the included library isn't? I tried restarting the IDE and my computer but it doesn't work. The other libraries work fine it's only with Keyboard that it fails.

My code:

#include <Keyboard.h>

int buttonState = 0;

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);

  Keyboard.begin();
}

void loop() {
  buttonState = digitalRead(2);
  if (buttonState == HIGH) {
    digitalWrite(13, HIGH);
    Keyboard.press('A');
  } else {
    digitalWrite(13, LOW);
    Keyboard.releaseAll();
  }
}

Error log:

Arduino: 1.6.8 (Windows 10), Board: "Arduino/Genuino Uno"

D:\Documents\Test\Test.ino: In function 'void setup()':

Test:9: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
   Keyboard.begin();

   ^

D:\Documents\Test\Test.ino: In function 'void loop()':

Test:16: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
 Keyboard.press('A');

 ^

Test:19: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
     Keyboard.releaseAll();

     ^

exit status 1
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

I see you are using an Arduino Uno.

An Arduino Uno cannot act as a USB keyboard - therefore the Keyboard library doesn't exist for it (the file Keyboard.h is seen as being empty).

You can only use Keyboard.h on boards where using Keyboard.h makes any kind of sense, such as the Leonardo.


Circuit diagram for ACS712 and ZMPT101B with ESP8266 using ADS1115 This is probably a cry for help for a circuit diagram which involves connecting ESP8266 with ADS1115 with ACS712 and ZMPT101B(voltage sensor). Since both of them uses analog pins, and using a diode separator is not a proper idea in real-life. Therefore I ended up using the ADS1115 for more analog pins, which should be working fine. I am not a electrical engineer so I am having real trouble as to how to fix all Four of them together. Can any one help me with a circuit diagram for this? Any links or research papers links, etc. Thanks

Step one is to get the ADC working.  Once that is done everything else will fall pretty much into place.

The ADC you have chosen is an I2C device.  The ESP8266 doesn't have I2C as such, but it does provide a software-emulated I2C implementation.  This can be used on any pair of pins, but the default ones are GPIO4 for the data (SDA) and GPIO5 for the clock (SCL) (this corresponds to the Arduino Uno using pins A4 and A5 for I2C, so it should be easy to remember).

Once you have that working the wiring for the rest is the same as for any other system. The only thing that differs is that your analogue inputs are on the ADC chip, not the main module.

Here's a block diagram to get you started:

simulate this circuit – Schematic created using CircuitLab

This is assuming:

Single voltage output from each of your sensor modules
I2C pullup resistors provided by either ESP8266 or ADS1115 (add your own if not)
All modules providing the required support components for the chip


Newbie need help to make a motor run for a laser scanner and some questions I am trying to make a laser scanner consisting of a webcam and a line laser scanner. I have tried to use a manual scanning (by hand) and has worked, but would now like to consider automating the laser rotation (upwards and downwards) as a higher accuracy entails a slow and smooth rotation.

I came across arduino a few weeks back and realised it could possibly help to make this a reality. From my limited readings so far, I have obtained an Arduino Uno and a motor shield that seems to be the essentials for my purpose.

I have a few queries that hopefully someone can help:

Do I need a stepper motor for slow rotations, instead of a normal brushed motor?
Do I need to connect the Arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?
How long will a standard 9V battery last?
For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial.
Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

A servo motor would have a lot more control than a normal motor. You usually command them to go to one of the predefined steps (stops) by using a function call in the servo motor library.
You can run independently of the computer. Many people do this. Certainly you can run off a battery. It doesn't have an ON button, you normally would have this between your battery and the Uno (eg. built into the battery pack). Like this:

A 9 V battery? I wouldn't use one, especially to drive a motor. It won't last long. Get something like 3 x AA batteries in a battery holder.

To show you the idea, I have this servo motor (SG-5010) I got from Adafruit.

I measured it using about 200 mA of power when operating. Now, I looked up a typical Alkaline 9 V battery, and found that, consuming 200 mA, it lasts for around 400 mAh. Thus, you could say it would be good for two hours at that rate. Plus, the Arduino will take around 50 mA, so maybe less than two hours.

A smallish servo motor won't need a motor shield. The pictures on the linked page show ordinary brushed motors. A servo motor has 3 leads:

Power (eg. 5 V)
Gnd
Data

Make sure you connect the grounds together, but the power could go to a separate power pack. A bit depends on how much power your motor will use. The data goes to the Arduino for the information about which rotation point to step to.

You should be able, in code, to change the rotation position, forwards and backwards.


Avoid blocking from bluetooth callbacks I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.

// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffer.push(a);
}

void loop(){
    if buffer.isFull() {
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffer.getData());
        myFile.close();
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    int freeSpace = SD.vwd()->fileSize();
    // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace);
}

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.

What is the recommended technique to make sure that data collection process will not be affected?

UPDATE:

The actual usage is that RFduinoBLE_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE_onConnect requests?

Well, one easy, but effective improvement is to use 2 buffers for writing data - while you are writing the one full to file, your interrupt can safely push values to the other and then after the other is full, your ISR would go to first one, while the second will be written. So even long open/seek/write/close loop does not get hit by new data arrival.

Then the main problem - RF - I would bet, that the on_connect() is called from interrupt too, as it is not mentioned anywhere in the loop(). In that case you would like to have it as small and fast as possible. So if you are only providing data, I would collect all the data in the main loop() in some variable (structure, class, what you need), get it thread safe as much as possible (atomic operations, or have two instancies, one actually enabled for the callback, the other opened for filling new data, then pointers to point which is which and just reassigning those pointers in atomic way (means disable interrupts, swich two pointers, enable interrupts - interrupts can wait for time need to two pointers be changed - on other hand you have no chance do anything in main loop (as disabling interrupts), while interrupt is actually running)

So (I know, it is just example, but) you know, that fileSize() is changed only after file is written - so save its value to some (volatile, of course) variable each time you write to the file and use that variable in onConnect.

So more like this (did not tested it, just idea):

volatile buffs[2];
volatile actBuff;
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffs[actBuff].push(a);
}

volatile int freeSpace;
void loop(){
    if buffs[actBuff].isFull() {
        int fullBuff=actBuff;
        cli();             // disable global interrupts
        actBuff = 1 - actBuff; // switch actual Buffer between 0 and 1
        sei();// enable global interrupts
        // ISR have nice free buffer to fill, we will write and empty the old one
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffs[fullBuff].getData());
        myFile.close();
        buffs[fullBuff].empty()
        int tempval = SD.vwd()->fileSize();
        cli();             // disable global interrupts
        freeSpace = tempval;
        sei();// enable global interrupts:
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    // int freeSpace = SD.vwd()->fileSize();
    // do the same trick here // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace); // use the value from loop
}


Serial Monitor and UART After uploading the code, can I connect a UART peripheral's RX, TX to TX, RX (D0 ,D1) and use the serial monitor of the arduino together ? Will data reception from the peripheral properly work in this case, or will it conflict with the serial monitor ?

You can use the serial monitor in this way, as long as you ensure you do not send anything from the serial monitor out to the Arduino or peripheral, only to monitor data.

That said, if you try to send debug prints from the Arduino to the serial monitor, they will also be sent to the peripheral device, where there may be conflict, depending on the peripheral.

So you technically can, but it's not advised because there are several ways it can go wrong.

One alternative is to use the SoftwareSerial library to create a second, bit-banged serial port. Note, however, that this library can't operate at high speed (probably best to keep at 9600 bps) reliably.


When does the ADC take the reading? I'm experimenting with the "2 pin capacitance meter" and trying to make it more accurate. Currently I've made the Arduino read 62.5 ns intervals but this means the time for the ADC to read is taking up a bigger part of the interval. I'm currently using a prescaler value of 8 on the ADC. Unfortunately reading continuously isn't really an option so I am limited to around 8us of read time instead of 6.5us. This isn't that much of a problem since I know that the read will take near 8us from experiments, however I do not know when during that 8us interval the actual reading takes place.

So that is my question, does the adc take the average value during those 8us, does it "lock" the bits at the beginning or when exactly does the reading occur?

Link to capacitance meter, specifically the third one: http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/#comment-363733)

The ADC is a "Successive Approximation" type ADC.  It works by:

Taking a snapshot of the incoming voltage in a small capacitor
Generating a reference voltage
Comparing the voltage in the capacitor to that reference voltage
Refining the reference voltage
Go back to 3 until you have the accuracy you desire.

There's lots of "time" involved there:

The capacitor can only store the voltage accurately for so long before the self-discharge (leakage current) causes the voltage to drop (this defines the maximum amount of time you can take to do a reading)
Each refining of the reference voltage and comparison thereof takes one ADC clock tick. There are a few "setup" clock ticks as well. This defines the minimum number of ADC clocks that you need to take a reading (13)
The DAC and comparator take a certain amount of time to operate each clock tick - this limits the maximum clock frequency the ADC can run at.

So you have a "sweet spot" of speed (like the "goldilocks zone" of the solar system). Set the ADC too slow or try and get too high a resolution out of it and you lose accuracy due to voltage droop on the capacitor. Set it too fast and the DAC can't keep up and you lose accuracy due to the comparison voltage not being right.

Well, that's the internals. Then on top of that you have the Arduino API. That adds an entire other layer of complication. analogRead() is a blocking operation.  It:

Congfigures the IO pin (if needed)
Turns on the ADC (if needed)
Configures the ADC MUX to the right channel
Starts a conversion
Sits there twiddling its thumbs for a while
Reads the conversion result
Returns it to you

And it does that (except maybe 1 and 2) every time you take a reading.  That's fine for reading a potentiometer, or an LDR, etc. But rubbish when you want to do fast, time-based, readings.

Instead you need to push the envelope a little and step away from the Arduino API.  Much of what the ADC does is done without intervention of the CPU. Manually configuring the ADC to read continuously and trigger an interrupt when the conversion is done, and then using that interrupt to grab the result of the comparison and start a new one (or use a timer interrupt to read the previous result and trigger a new reading) will give you much more control over the ADC and exactly when things happen.

So, now to answer your main question of "when during that 8us interval the actual reading takes place.", in the context of how the ADC works:

At the moment the SAH capacitor is detached from the MUX to start the comparison sequence.

When exactly is, though, is subjective.  If you use the Arduino API (analogRead()) then it's at some point near the start of the function call, but not at the start of it.

If you configure it manually and trigger it from within a timer interrupt, it's on the second (out of 13) falling edge of the ADC clock after ADSC has been set HIGH.

There are also "Free Running" and "Auto Trigger" modes whose timing is the same as for a single conversion.  Note that the first conversion performed in any mode imposes a "run-in" clock sequence where the ADC MUX and reference voltage DAC are initialised.

All this timing can be found in figures 23-4 and 23-5 on page 209 of the ATMega328P datasheet.  On page 210 there is a handy table that gives you how many ADC cycles from the start of a conversion the Sample And Hold occurs and how long the conversion takes in clock cycles.

For best throughput you want to use "Free Running" mode and read and store the ADC result in the interrupt the ADC triggers.  For most accurate and controllable timing you want to use Auto Triggered mode with a timer for the trigger source, and again read the result in the ADC interrupt.


How do I make a proper long string scanner to detect specific tags in a stream of characters? Here's my code:

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

void setup() {
    Serial.begin(9600);
    BTserial.begin(9600);
    Serial.println("Communication with HC-05 successfully started.");
}

bool is_uploading_book = false;
char c = ' ';
String recv_scanner = "";
void loop(){
    if (BTserial.available()) {
        c = BTserial.read();
        recv_scanner += c;
        if(recv_scanner.length() >= 50) {
          recv_scanner.remove(0, 1);
        }
        // I believe there's something wrong with the recv_scanner.
        if(is_uploading_book) {
          Serial.write(c);
        } else {
          if(recv_scanner.indexOf("(__BOOK_UPLOAD_START__)") >= 0) {
            is_uploading_book = true;
          }
        }
        Serial.println("\n\n" + recv_scanner + "\n\n");
    }
}

I'm sending a book (long text) in the form of characters one by one from my phone to my HC-05 module (and the Arduino).
My goal is to spot the tag "(_BOOK_UPLOAD_START_)" in the incoming characters.
Arduino allows me to receive the characters of the book one by one on each loop.
I'm storing those characters in a string called recv_scanner where I allow it's maximum size to be 50 characters and once it reaches those 50 characters, I start to remove the first character and add a new one on each loop (so it can only see 50 characters at a time because maximum String length is 200 and for my purposes, 50 is enough).
The thing is, it doesn't work properly.
When I Serial.println the recv_scanner on every loop (so I see how it progresses) it starts to look like this:

⸮qsnieq⸮cn .laslvanm.⸮⸮⸮d⸮alvuv⸮⸮urosqiam tr⸮⸮⸮

(It starts normally and then slowly progresses into this)
I have no idea what that is.
As far as my predictions go, it should show 50 characters and they should be parts of the books.
Is there something fundamental about Strings that I don't know of?
I'm doing this so I'm able to detect a tag (_BOOK_UPLOAD_END_) at the end of the book and finish uploading.
Feel free to ask my questions if something is unclear.

Another option is to not save the characters in buffer but instead check each one as they arrive to see if the character is the next in the tag sequence.

This has the advantage that you don't need a buffer to match the tag and you don't have to repeatedly search for the string in the buffer.

const char* TAG_STR="(__BOOK_UPLOAD_START__)";
int tag_pos = 0;
char c;
bool is_uploading_book = false;

void loop() {
  if (BTserial.available()) {
    c = BTserial.read();
    if (is_uploading_book) {
      //do book stuff
    } else {
      if (c == TAG_STR[tag_pos]) {
        // c matched the next character in the string
        tag_pos++;
      } else if (c == TAG_STR[0]) {
        // matched first char in the middle, restart
        tag_pos = 1;
      } else {
        // Did not match the next character so we should start over
        tag_pos = 0;
      }
      // The next character to match is the string terminator
      // so we must have matched the whole string.
      if (TAG_STR[tag_pos] == '\0') {
        is_uploading_book = true;
      }
    }
  }
}


How can I write an integer to a Mifare RFID card using the RFID library? I'm a beginner to C++ and I'm clearly missing some fundamental knowledge of data types. As such, I'm struggling to adapt the examples in the miguelbalboa/rfid library to my use case. I'm simply trying to write an integer to a 13.56Mhz RFID tag. Ideally I'd like to optimize the data so as to be quick to read (it seems fully reading these cards can take a while and I'd like to read the integer, an ID, as quickly as possible).

So on to my actual questions... what is the data type shown in this block of example code (shown below) and how can I turn an integer into the same data type? Finally, how should I read this saved value back into the familiar integer data type?

byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x09, 0x0a, 0xff, 0x0b, //  9, 10, 255, 11,
    0x0c, 0x0d, 0x0e, 0x0f  // 12, 13, 14, 15
};

The dataBlock[] variable is an array of bytes. One byte can represent an integer ranging from -128 to 127, or a positive integer ranging from 0 to 255. If your integer value will always be in one of those ranges, then you can just put your integer in the first element of the array and zero out the remaining.

byte dataBlock[]    = {
    0x01, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00
};

(That saves a value of 1 to the first element, and zeros to the rest. If you want to change the first element:

dataBlock[0] = yourValue;

If your integer is a 2-byte integer, as is typically found in Arduino with type int, you need to split your value into the high byte and low byte:

dataBlock[0] = (byte)(yourValue & 0xFF); // Low byte
dataBlock[1] = (byte)(yourValue >> 8);   // High byte

Then you write the data block as per the example. To get your 2-byte integer value back:

yourValue = ((int)dataBlock[1])<<8 | dataBlock[0];  // Shift high byte, OR with low byte.


An array of existing arrays I have a bunch of 3D arrays in the following form:

byte lines[][4][2] {
                     { {B00000000, B11110000 },
                       {B00000000, B11110000 },
                       {B00000000, B11110000 },
                       {B00000000, B11110000 } },
                     { {B11110000, B00000111 },
                       {B00000000, B11111000 },
                       {B00000000, B11111000 },
                       {B00000000, B11111000 } },
// continues for numerous elements
                    }

They are a bunch of values to push out to a pair of shift registers controlling an LED matrix. Each array is essentially an animation that plays across the LED matrix.

I would like to put my collection of arrays into an array so I can iterate through them. I know I can just combine them into one big array but the code is already opaque and I would at least like to keep separate named arrays so I can sequence and rearrange a series of animations by rearranging a series of named arrays in another array rather than one massive array of opaque binary values.

I want to do something like this

sometype* sequence[] = { lines, circles, squares } ;

or if that's not possible then:

sometype* sequence[3];
sometype[0] = lines;
sometype[1] = circles;
sometype[2] = squares;

Can I do this or some approximation thereof? If so what is "sometype"? I can't figure out how to say "an array of pointers to 3d byte arrays" or whatever it is I am trying to do. What is the syntax for deeclaring the array and dereferencing the pointers?

Try this:

byte (*sequence[])[4][2] = { lines, circles, squares } ;

Explanation: The identifiers lines, circles and squares decay
to pointers to the first element of each array. Their decayed types are
then “pointer to array of length 4 of array of length 2 of byte”. This
type could be declared as

typedef byte (*pointer_to_2d_array)[4][2];

The sequence is then an array of this type, which can be declared as

pointer_to_2d_array sequence[] = { ... };

or, if you appreciate the obscure elegance of the C syntax, as in the
beginning of this answer.


On UNO, when serial.print to UART pin 11, nothing comes out of pin 11 The problem: Message prints only to the Arduino IDE's Tools > Serial Monitor, not coming out of TX pin 11.
Question, please how to get Arduino Uno or Mega to send data out of pin 11?

#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX pins on Arduino
void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.print("This is a test\n\n");
  delay(1000);
}

Of course it's only coming out on the serial monitor - you are printing it to the hardware UART which comes out on the serial monitor.

You have created a SoftwareSerial object which you are then completely ignoring and then using the HardwareSerial UART object instead, which is on pins 0/1.

If you want to use a SoftwareSerial object you should actually use the SoftwareSerial object.

Replace all the references to Serial with mySerial instead.


How to print 'µ' in the serial monitor? I have been trying to print the letter µ on the Serial Monitor of Arduino IDE but I failed to do so. Is there any way to print µ or any other Non ASCII characters such as Ó,ß,Ô,Ò,õ,Õ,þ, etc using Serial.print()?

Most of what follows has already been covered in previous answers. I am
posting this nevertheless because I feel no answer so far makes the
whole story clear enough. Let me break down the question into two
sub-questions.

1. How can I get non-ASCII characters correctly print on the serial monitor?

The answer is simply send them as UTF-8.

That's really all there is to it. The serial monitor expects you to send
UTF-8, and it will print the characters correctly only if you use this
encoding. But that brings the second question:

2. How can I get the characters as UTF-8 in my Arduino program?

Here you have several options:

Option 1: encode them yourself

For example, the Greek letter “μ” (U+03BC) in UTF-8 is (0xce 0xbc). You
can send those bytes explicitly, like

Serial.write(0xce);
Serial.write(0xbc);

or, more comfortably, like

Serial.print("\xce\xbc");

The second syntax is more convenient because it allows the character to
be embedded within a longer string.

Option 2: let the Arduino IDE encode them

If you can get the characters in the IDE's editor window, either with an
appropriate keyboard layout or by copying and pasting from another
application, then you can use them as is in the string:

Serial.print("μ");

The editor will save the source code as UTF-8, and those UTF-8 bytes
will go undisturbed from the source file to the compiled program, to the
Arduino memory, to the serial port, and finally to the serial monitor.

This option is the best for readability. However, it is somewhat
fragile: if the source code ever gets re-encoded (e-mail clients and
servers sometimes do that), then the resulting program will not work as
expected.

Options 3: let the compiler encode them

You can ask the compiler to do the UTF-8 encoding for you with the
syntax

Serial.print(u8"\u03bc");

Here, the escape sequence \u03bc is a way to represent the Unicode
character U+03BC (i.e. “μ”), and the u8 prefix means that you want the
string as a byte array encoded in UTF-8.

Note that, in practice, the u8 prefix is not needed, as the gcc
compiler assumes UTF-8 by default. I would keep the prefix anyway
because it doesn't hurt to make the encoding explicit, and it may avoid
angering some language lawyer...

Note also that the syntax above only works for characters U+0000 through
U+FFFF, i.e. the basic multilingual plane. For other Unicode characters,
you have to use the syntax \U + 8 hex digits. For example, the
character “” (U+1F60E: smiling face with sunglasses) can be printed
with:

Serial.print(u8"\U0001f60e");

Clarification about UTF-16: A common misconception has it that with
\u you write the characters as UTF-16 code units, and with \U you
write UTF-32 code units. But it is incorrect:
both syntaxes are used to describe a
single character (technically, a code point), irrespective of the
encoding. Since the UTF-16 encoding for “” is (0xd83d 0xde0e), one
could be tempted to write

// Write as UTF-16 code units in the source code.
Serial.print("\ud83d\ude0e");  // WRONG

but then the compiler rightfully complains

error: \ud83d is not a valid universal character
error: \ude0e is not a valid universal character

So forget about UTF-16. There is no UTF-16 involved anywhere, except in
the internal representation used by a Java widget used to implement the
serial monitor, which is a completely irrelevant implementation detail.


Example code and documentation on using Firmata communication in native Java I have been trying for some time to get documentation on using Java and a Firmata client library for the communication between a PC and an Arduino. Please note I want to use Java only, i.e., not Processing.

Up to now I used the excellent Haskell library hArduino for Firmata communication with Arduino boards.

Now I am teaching a Java course at the university as a PhD student. Therefore I need to use Java. However, compared to Haskell there are no centralized libraries, packages, documentation as with Haskell.

So I used Google to find more information on using Firmata client libraries for Java. Unfortunately, the search results are polluted with irrelevant results about Processing and Javascript. Therefore I ask here.

According to the Firmata client library page, there are two Java client libraries. However, only 4ntoine seems to be up to date, while the Javarduino project seems abandoned.

So I guess the standard way is to use the "4ntoine" Java client library. Or are there other options?

(I am not interested in Processing or Javascript.)

Question: Where do I find up-to-date documentation and example code on using Firmata client libraries for Java?

Maybe this can work for you.
Some months ago i used RXTXcomm library [1] to send Arduino data to a Program i made in java and store in in a file, it works fine with some issues:

I made the Java programm in linux but just works in java 6, so in the windows pc of the client i installed that version, i don't know if works with java7 or java8 in windows.
Java programm reads data from Arduino sketch with Serial.print() function, Arduino continously is using this function, i lose some data, so i had to put a short delay to java programm get all data send by Arduino.

[1] http://rxtx.qbang.org/wiki/index.php/Main_Page


'AttachPinChangeInterrupt' was not declared in this scope I am a beginner trying to upload the SimpleExample328.ino sketch on my Arduino Uno. When I verify my sketch however, I run into the error:

  'AttachPinChangeInterrupt' was not declared in this scope.

I would assume the header file PinChangeInt.h is not in the correct location; currently the PinChangeInt folder (that contains PinChangeInt.h) is placed in the Arduino IDE libraries folder, which I believe is the correct location.

Did I place the header file in the wrong location or does this error result from another cause? Thanks :)

You don't have the library installed. To install:

Go to https://github.com/GreyGnome/PinChangeInt
Click the green Clone or Download button
Select Download ZIP

The .ZIP file will download to your computer. Take note of the location.

Open up the Arduino IDE
Go to Sketch > Include Library > Add .ZIP library...
Browse to the download location
Select the PinChangeInt ZIP file

Its done! Compile your program and all should work!


WiFi.status() hangs / resets board Using one of the RobotDyn boards with onboard WiFi and a Generic ESP8266 module.

I can load the sketch, but when WiFi.status() is called to see if WiFi enabled, the sketch hangs, rebooting the board after ten seconds are so.

void setup() {
  Serial.begin( 115200 );
  Serial.println( "begin - wifi status: " );
  // program hangs here - - - - - - -
  int status = WiFi.status();
  Serial.println( status );
}

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


Arduino USB Power vs External Power Supply Why is the Arduino able to accept ~5V from the USB, but requires a min of 7V when using an external power supply?

The design assumes USB provides a regulated 5v so no further regulation is necessary. The power connecter is meant to accept a wider range of voltage and regulate it to 5v, and the kind of regulators used on the Arduino board need that much higher voltage to provide regulation. If you already have a regulated +5v source you can supply it to the 5v pin. You'll bypass the on-board regulator this way, so just know that it will then be up to you to provide clean power.


ML8511 Sensor, unable to achieve meaningful results. Output voltages are atypical Problem: ML8511 Sensor, unable to achieve meaningful results.  A mapping to the voltage output yields values that are unrealistically high. Variance is greater than expected [by me], and sensitivity, if any is questionable. In essence, the sensor reports high levels of UV whether is a dimly lit room, or exposed to daylight.

Background:
The interface is simple enough, and Google Search renders numerous hits, e.g., https://learn.sparkfun.com/tutorials/ml8511-uv-sensor-hookup-guide
All coding examples I have seen are akin to the one shown by Sparkfun.

Prior experience: I have a number of other Arduino devices running my sketches that record, collect, analyse, distribute, transmit and display findings.  All of these work as intended.

Observations:  I have spent a lot of time trying to make sense of the behaviour i observe with the sensor output, but have been unsuccessful. I have used two different sensors [same model], and switched UNO boards.  I've removed all other connections to the board, reverted to using the example code, then to code measuring only pinout values.  I have also measured pin voltage via voltmeter for both the output signal and the 3.3 volt reference pin..  According to specs, the sensor outputs voltage correlate with UV levels, and calibration is achieved via a known voltage reference level.

Based on a 3.3 volt reference, the sensor should output 1 to 3 volts, which can be mapped to a UV Intensity (mW/sq cm) range of 0 to 15.  My output voltages range from 2.8 to 3.2 v, the last of which is seemingly out of specs.
I have also used different sample sizes that comprise a data point, but that has little effect, but since the underlying values are out of range, it really would not matter.
Although cheap sensors such as this are not known for great accuracy. I find that they generally work rather well.

My supposition is that:
a) I am working with defective [abeit new] sensors.
b) This particular model of sensor functions in an atypical manner.
c) Being unexperienced in such, I an overlooking something glaringly obvious to others.
d) Somehow my perception of reality is defective.
e) I have truly entered into the Twilight Zone.

Seeking: Information that supports or refutes my observations.  Ideas that I might use to further isolate/ identify the problem.  A solution to the problem.

Image of item used

ML8511 UV Intensity Graph from specs

[

Typical ML8511 Wiring Diagram, the GYML8511 also has an additional connector for 5V, which I have tried both connected and disconnected, not understanding the board behaviour.

I found another, third sensor identical to mine and functioning properly.  By measuring pin output, then cross swapping with one of my two "supposedly abberant" sensors, I have identified my two as being defective, i.e., the other sketch then failed to function properly with one of those so identified sensors, whilst mine now worked as it should.

I typically buy at least two of everything in an effort to isolate such problems, but if from the same batch, two may not be sufficient in some situations.


Sound or motion activated long term battery powered Arduino Basically, I want an Arduino to power up whenever a "creature" enters viscinity (at least within up to 3 meters).

I would really like this to be able to keep monitoring for at least 4-8 weeks, without having to replace batteries. I don't want to use more than 1 or 2 18650 Liion cells.

Couple of methods that I believe would work:

Changes in light-conditions.
Sound.
Small vibrations in the ground.

Approaches to conserve power:

Checking for changes in light at most every 30 seconds (boot the Arduino, and power off quickly).
Checking for 1 second for sound, every 10-15 seconds.
Vibrations in the ground using an accelerometer?

The ideal solution does not run the Arduino at all, unless a trigger causes it to run. When the Arduino starts, it will have to turn itself off again to resume monitoring mode.

What approach should I go for? I'm not very good with electronics, and would like to avoid configurations involving transistors, resistors and so on - unless stricktly required.

Is it possible/easy to wire an Arduino Pro Mini to run directly off a 3.7 V battery, bypassing any power hungry voltage regulators?

What you want to do after the triggering is an important part of this design.

An Arduino platform is not necessarily the best choice for power sensitive applications.  You identified one problem in your post: Linear regulators.  What you are likely wanting is an efficient switching power supply to support a wide range of voltages as your batteries drain.

Many embedded processor have low power modes.  Some are specially designed to reduce current draw down into the nA range when idle or sleeping.  However, all such processors require special care when configuring for these deep sleep modes.  That is to say, the application plays an important roll in deciding how to put a processor into such modes.

Supporting hardware is perhaps the most important aspect of a low power designs.  Contributions from the most advanced low power processors can be wiped out if supporting hardware runs at mA ranges.  A simple 10K pull up resistor will draw 0.5mA in a 5 volt circuit. The impact is meaningless in a mains powered application.  But for long term battery operation is could means days of lost time.

All that said, there are resources for Arduino low power operation.  Here is a low power library.  You will have to decide if it is sufficient for you application. Or if you need to also investigate low power hardware solutions.


Use Arduino to turn fan on / off I have a simple fan.
When I plug it to GND and Vin it spins.
I'd like to have the ability to turn it on / off with code.
Any example will do, as long as it gets it to spin.
I have a NodeMCU board, if that helps.

Depending of the type of fan you are using, two solutions exist.

First one, use a MOSFET to drive the FAN from you nodemcu
Second one, use a relay to drive the FAN from your nodemcu

Things to consider :

The mosfet allow you to drive the fan without mechanical part moving.
The relay require some transistor and feedback diode to be driven by your µc.


Arduino Loading doesn't work Hello I have an Arduino program that loads strings from a file and stores them in an array. It works fine when I load it the first time but when I load it a second time it doesn't seem to work.

 String content = "";

 char character23;

 String result[10];
 int arraysize = 10;

 void loadPrograme(String sss){
   File file = SD.open("basic.txt", FILE_READ);
   Serial.print("Reading, Checking and Compiling \n\n\n");

   for (int i = 0; i < arraysize; i++) {
     result[i] = "";
   }

   for (int i = 0; i < arraysize; i++) {
     while (file.available()) {
       character23 = file.read();
       if (character23 == '\n') break;
       if (character23 != '^') {
         content += character23;
       }
     }
     content.trim();
     if (content != "") {
       result[i] = content;
       content = "";
     }
   }

   for (int i = 0; i <arraysize; i++) {
     Serial.print("result[");
     Serial.print(i);
     Serial.print("]: ");
     Serial.println(result[i]);
   }
   file.close();
 }

This works fine when I call loadProgramme("basic.txt") in the setup function.

void loadfileMethod(String s){
  if(consolemode){
    u8g.setFont(u8g_font_micro);
    u8g.drawStr(2, 6-camy, s.c_str());
    camy+=6;
  }
  camy = 0;
  loadPrograme("names.txt");
}

When I call loadprograme in this method it runs through loadrograme but only gets as far as the while loop and it doesn't do anything in the while loop.(I check this using serial.println().

Can someone tell me what I'm doing wrong that makes it work the first time and not the second?

EDIT: I found the problem but I don't know how to fix it. when I do Serial.println(file.name()); it prints the correct name the first time but the second time it just prints a tiny box which I presume is nothing or an error.

How can I fix this?

If you know that your while loop isn't working as expected, I'd instrument the while loop and see if it parses as you expect:

for (int i = 0; i < arraysize; i++) {
  while (file.available()) {
    character23 = file.read();
    if (character23 == '\n') break;
    if (character23 != '^') {
      content += character23;
    }
    Serial.print(i);
    Serial.print(':');
    Serial.print(character23);
    Serial.print(':');
    Serial.println(content);
  }
  content.trim();
  if (content != "") {
    result[i] = content;
    content = "";
  }
}

Are you certain it is working the first time?


XBee + Arduino Problem I've been doing some XBee experiments with Arduino Pro Mini 5V. I knew that XBee S2 is 3.3V only, so I've connected its Vcc to 3.3V from external supply, but I had also connected XBee RXTX to arduino TXRX, in this order, and since that i can't use my XBee Explorer to communicate with XCTU on my notebook. The connections with an 5V Arduino RXTX can cause damages to the XBee, even if the XBee was powered with 3.3V?

Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, knowledge.digi.com/articles/Knowledge_Base_Article/…. I really think that the XBee is gone. One way to avoid this problem is to get one of this regulated breakout board. http://www.hobbytronics.co.uk/xbee-explorer-reg. As it says in the description, it regulates ALL pins to 3.3V, making me believe that I needed to take care of that before making such a mistake. Hopefully this prevent someone from doing this mistake in the future. So, bye-bye XBee.


RPM measurement using quadrature encoder I am trying to build a RPM controller for my project. I am using a quadrature encoder (ppr=400) and Arduino Uno for this purpose. I am using the code given below inorder to caluculate the RPM of the DC motor. I get a reading on my serial Monitor. However, this RPM doesn't match with my manual calculation (i.e when I calculate the RPM Manually using a stop watch- for lower speeds).

EDIT-> Eg- Manually I get around 10 RPM, but my program shows 60 and more.

I have used one interrupt pin on my Arduino UNO.

#define encoder0PinA  2
#define encoder0PinB  3
int power=6; // to power up the encoder
int gnd=4;  // to provide ground to the encoder
int motor=11; //motor PWM pin
int dir=10;
volatile unsigned int encoder0Pos = 0;

void setup() {
  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor
  pinMode(power,OUTPUT);
  pinMode(gnd,OUTPUT);
  digitalWrite(power,HIGH);
  digitalWrite(gnd,LOW);
  pinMode(motor,OUTPUT);
  pinMode(dir,OUTPUT);
  digitalWrite(dir,LOW);

  attachInterrupt(0, doEncoder, RISING);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");    // a personal quirk
  analogWrite(motor,120); // to set a particular test RPM to the motor.
}

void loop() {
  encoder0Pos=0;
  delay(1000);
  float rpm=encoder0Pos/(400);
  Serial.println(rpm);
}

void doEncoder() {

  encoder0Pos++;
  }

Also I tried the very first code on the following link "https://playground.arduino.cc/Main/RotaryEncoders".. In this case my Arduino stops transmitting completely. I tried the same code on one of my friend's setup.. surprisingly it works there.
Can't understand where I am going wrong... Is my coding approach correct?? Please enlighten me...
Thank you.

Ensure the encoder outputs 400 pulses on each phase. It could be 200 on each phase for one rotation

Rather then clearing your pulseCount, figure out the time it take to make one rotation (as close as you can tell) and turn the motor on for only that amount of time, and then off again. This will allow you a more controlled environment to test your code in, and it will be the same(almost) every time.

You are calculating revolutions per second with your code, not per min
number of pulses/400(if this is correct number)=Revolutions     which you are clearing ever 1000ms

Ensure good connections on your wiring as it does not take much to allow the interrupt to fire twice when it should have only fired once.

Use the second phase of the encoder, this is what gives the ability to decipher bad signals and change of dirrection,   ie- multiple A pulses in a row(without any B pulse) does not equal movement, it means either the motor is hanging out right on a phase line, or something is causing the interrupt to fire more often then it should.


Standalone 328p Programming with CH340G programmer I have made a standalone arduino board with a Atmega328p w/ Uno bootloader taking inspiration from this video https://youtu.be/sNIMCdVOHOM
However, when I try to program mine all I get is "Problem uploading to board".
I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter to program the board instead.

Other things that I have tried:
Swapping Tx/Rx from adapter to board

Adding 100nF capacitor on DTR to RST

Trying without DTR

(The board also has a 10k pullup resistor on the RST line)

Burning a new bootloader after programming with Arduino as ISP

Any suggestions are greatly appreciated.

Thanks,

Verbose Upload Output

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM7 -b115200 -D -Uflash:w:C:\Users\Admin\AppData\Local\Temp\arduino_build_446007/Blink.ino.hex:i

     Using Port                    : COM7
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe8

avrdude done.  Thank you.
Problem uploading to board.

I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter.

Because the ATmega family does not support a partial flash erase via ISP, loading a sketch via ISP removes the bootloader.

Therefore you must (re)load a suitable bootloader using the ISP connection, before you can perform a serial upload of a sketch using that bootloader.


Can't program Arduino via Bluetooth (HC-06) with a Mac I bought a HC-06 Module for my Arduino Uno the other day, yesterday it arrived and I'm having trouble using it with the Arduino IDE.

I set it up, connecting 5V, GND and RX/TX crossed. After a bit of searching, it shows up on the bluetooth settings on the macbook. When I click "connect", it fails, after I click "Options", then set the Pin to 1234 it says "Connected". The LED on the HC-06 is still blinking (which is OK I guess, since I'm not yet communicating).

I have a Sketch running on the Uno that prints out some text. When I open the serial monitor (after connecting like above) it works, displaying the values I expect. However, after closing the serial monitor the HC-06 changes to "not connected" on the mac.

Also, if I try to upload code via the Arduino IDE it states: avrdude: ser_open(): can't open device "/dev/tty.HC-06-DevB": Resource busy
ioctl("TIOCMGET"): Inappropriate ioctl for device or throws a processing.app.SerialException: Fehler beim Öffnen des seriellen Ports "/dev/tty.HC-06-DevB". (German for "Error while opening Serial Port "/dev...." ").

Do I have to configure the HC-06 or the Arduino IDE in any way to make this work, and, if so, how can I do that?

Edit:
I've also connected TX and RX uncrossed, though that alone doesn't solve the problem.

Thanks in advance for your Support!

The on-board USB-to-serial pulses the reset line to start the bootloader. HC-0x don't have the extra signal available that USB uses for that so you'll have to manually reset the Arduino just as - or very slightly after - you click to start the upload on your Mac; you may need to experiment to get the timing right, but once you know it, it isn't hard to do. Keep Rx & Tx crossed as you do for Bluetooth terminal communication. And even with all that, I've never achieved anything like USB upload speeds (baud rate for baud rate) using Bluetooth.

Update:
In brief, it could be timing, baud-rate, or pairing.

I find it easy to get the timing: hold reset / click (and let go) the upload button / release reset. It doesn't need to be so fast that it's a challenge to coordinate but do it faster than counting seconds.

Your HC-06's baud rate will have to match the baud-rate your boot-loader expects. It looks like Uno's bootloader's use 19200 baud (and there are some way older ones that used 9600). My bare, pre-programmed chips' boot-loaders from Adafruit.com use 57600 baud. Your preferences.txt file should contain a line like 'atmega328o.upload.speed=115200'; assuming you're able to upload via USB, then use this baud rate for the HC-06. (The path to your preferences file is displayed on the Arduino IDE's preferences dialog.)

The 'Resource busy' message sounds like your Mac isn't paired with your HC-06. In the MacOS Bluetooth System Preferences pane, pair the Mac with the HC-06 and be sure HC-06's LED is on steady (not blinking).


Convert float to char array on ATtiny85 I'm having a hard time trying to convert a float into a char array so it's stored like '7.125' just like the float looks.

I'm trying to communicate with an ATtiny85 (slave) and a program on a Raspberry Pi (master) over I2C.

The master expects 31 bytes from the slave when data is sent to it.

When I use this code on the ATtiny85 everything works as it should, the Pi gets the data correctly.

    char computerdata[35];
    computerdata[0] = '3';
    computerdata[1] = '.';
    computerdata[2] = '8';
    computerdata[3] = '7';
    computerdata[4] = '7';

    TinyWire.send(1);
    TinyWire.send(computerdata,30);

Of course I need to put a float variable in the array and not define numbers like I have for testing and this is where it breaks.

When I do something like this, it doesn't work, the Pi reports parsing error yet when I do this on the Due with Serial prints the char array looks good but something is different about it.

  sprintf(computerdata, "%2.32f", pH);

OR

  snprintf (computerdata, 35, "%f", pH);

What am I missing? Any ideas?

Thanks

Just to complement Michel Keijzers’ answer: sprintf() or snprintf()
are normally the right solution. On the AVR platform, however, float
conversions are left out of their default implementation, because they
take quite a lot of flash space, even when not used. On the other hand,
the avr-libc provides the non-standard function dtostrf()
for doing this conversion. The program

void setup() {
    float f = 3.877;
    char str[35];
    dtostrf(f, 0, 3, str);
    Serial.begin(9600);
    Serial.println(str);
}

void loop(){}

outputs

3.877


wdt reset cause:4, boot mode:(3,6) I'm working on Python and nodeMCU with websocket connection.
So, I send a string from Python to nodeMCU and nodeMCU collects the string and decodes to set values to a stepper motor. Initial code worked fine before updating with stepper motor code. Now it triggers watchdog resets.
Here's my full code:-
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AccelStepper.h>

// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPin 8  // clk+
#define stepPin 9  // cw+
#define motorInterfaceType 1

AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);

const char ssid[] PROGMEM ="PencoNetwork2";    //change it to your wifi SSID
const char password[] PROGMEM ="Penco1234567890";    //change it to your wifi password

AsyncWebServer server(80);
AsyncWebSocket ws("/test");

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println(WiFi.localIP());

  ws.onEvent(onWsEvent);
  server.addHandler(&ws);

  server.begin();

}

void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){

    Serial.println("Data received: ");

    for(int i=0; i < len; i++) {
//          Serial.print((char) data[i]);
           String data_String = (String) data[i];

          int commaIndex = data_String.indexOf(',');
          int secondCommaIndex = data_String.indexOf(',', commaIndex+1);
          String firstValue = data_String.substring(0, commaIndex);
          String secondValue = data_String.substring(commaIndex+1, secondCommaIndex);
          String thirdValue = data_String.substring(secondCommaIndex+1); //To the end of the string

          int mDist = firstValue.toInt();
          int mspeed = secondValue.toInt();
          int mAccel = thirdValue.toInt();

          stepper.setMaxSpeed(mspeed);
          stepper.setAcceleration(mAccel);

          stepper.moveTo(mDist);
          stepper.runToPosition();
          delay(1000);
          stepper.moveTo(0);
          stepper.runToPosition();
          delay(1000);

    }

//    Serial.println();
  }
}

void loop(){

  }

It would be a great help pointing out my mistakes.

You're calling delay() in the onWsEvent() callback. The ESPAsyncWebServer documentation specifically says not to do that in the 'Important things to remember' section:

You can not use yield or delay or any function that uses them inside the callbacks

When you call delay() or loop inside an async web server callback, you block its event task from doing any other processing. This can interfere with a variety of housekeeping functions that HTTP, TCP and the Arduino Core need to perform. In general you should do as little as possible during a callback and return as quickly as possible.
The correct way to structure this code is to set a flag in the callback and inspection the flag and do the work in loop().
For instance,
AsyncWebServer server(80);
AsyncWebSocket ws("/test");

boolean flag_move_stepper = false;

void setup(){

and
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){
    flag_move_stepper = true;

    // you'll need to rewrite this code to share variables with `loop()` and do the work there

and
void loop(){
  if(flag_move_stepper) {
    flag_move_stepper = false;

    // do the work formerly in onWsEvent() here
  }

}

You'll need to make the variables you stored data in in the event handler available to loop() and move the stepper code there for this to work.


How can I identify, debug or fix a faulty IMU? I have an LSM9DS1 breakout board by Sparkfun, and am communicating with it using a Mega 2560 over I2C. The board is given 3.3 V power as defined in the data sheet, though there seems to be confusion whether the SDA and SCL pins need level shifting for communicating with the 5 V Mega. In theory it shouldn't need to.

I am able to connect with the device and get its accelerometer and magnetometer data, however the gyro is just returning noise and no signal. I have dug in to all the registers I know of regarding high pass filters, logging rates, enabling and powering the sensor, but the only hints are that when the gyro is disabled and then polled, it returns a constant nonzero value on all three axes, as though a bit somewhere is stuck. With any other setting the results are unchanged: finite noise on a constant DC signal. Is this even possible? How can I dig deeper to understand and solve this problem?

In theory you must use a level shifter for SDA and SCL. The Arduino Mega 2560 board has internal pullup resistors of about 50k for SDA and SCL and extra 10k pullup resistors of 10k to 5V and according to the datasheet the ATmega2560 requires 3.5V to detect a high level for the I2C bus.

Those pullup resistors might damage the LSM9DS1.
5V-3.3V / 50k//10k times two (both SDA and SCL) = 400nA that might be pushed into the sensor (I assume there are protection diodes, and the maximum voltage is 3.6V, therefor the 400nA is just an indication).
I assume the 10k pullup resistors to 3.3V on the sensor module are enabled. They will take away some over-voltage.

The current by the pullup resistors (to 5V) is a very small current, and I don't know if the sensor is in sleep mode during startup.

To be sure you need to buy another LSM9DS1 and a level shifter. Or even better: buy a 3.3V Arduino board, like the Due or the Zero, M0, and so on.

Have to compared the raw sensor data with others ? Those sensors are very noisy. That is why there is so much to do about filter algoritms to get data that can actually be used. The LSM9DS1 does not do processing or smart filtering with the raw data. All you get is the raw data. Did you assume that the values would be zero ? They never will be, because such sensors are far too noisy and too sensitive for that.


Reset NodeMCU master from Arduino slave I designed a PWS (personal weather station) which will be placed in a difficult to access location.  In case of the master crashing and not requesting from the slave for a certain amount of time (stay alive protocol), is it possible to reset the master from the slave by powering a digital pin?

Note, I improvised a pull down circuit so that the Arduino Nano's D7 (or any other digital pin) 5V output could be pulled down to 3.3V.

There is no need for a voltage divider or a level conversion on the reset pin of the esp8266. The esp8266 has internal pull-up on reset pin. To reset the esp8266 the reset pin must be connected to ground for a very short moment.

To pull the reset pin LOW with pin of the other MCU we do:

void resetEsp() {
  pinMode(ESP_RESET_PIN, OUTPUT);
  delay(1);
  pinMode(ESP_RESET_PIN, INPUT);
}

ESP_RESET_PIN is the pin wired to reset pin of the esp8266. It is not configured in setup() and it is never set HIGH (we don't want to send 5 V to esp8266). Setting the ESP_RESET_PIN to OUTPUT connects it to ground, setting it back to INPUT hands the control of the line back to esp8266 reset pin's internal pull-up.