String comparison problem I have this callback function in my Firmata sketch. It receives a string as a character array and does something with it. The problem is, that the string is being sent to the Arduino in T\0h\0i\0s\0 form - after each character there is a \0 terminator. As you can see, my function is switching the d13 LED on if the string incoming is COMMAND. I had tried to use several comparison methods:

strcmp(myString, "COMMAND") == 1;
myString == "COMMAND";
strcmp(myString, "COMMAND\0") == 1;
myString == "COMMAND\0";
strcmp(myString, "C\0O\0M\0 M\0A\0N\0D\0") == 1;
myString == "C\0O\0M\0 M\0A\0N\0D\0";
== with saving the COMMAND to a char array variable;
strcmp with saving the COMMAND to a char array variable;
last two things with converting both the incoming and the needed to a String instance;
comparing a String instance with a directly stated "COMMAND"...

Nothing works. How can I compare the strings workably?
Full Arduino sketch:
#include <Firmata.h>

void stringCallback(char *myString)
{
  if (strcmp(myString, "COMMAND") == 1) {
    digitalWrite(13, HIGH);
  }
  Firmata.sendString(myString);
}

void sysexCallback(byte command, byte argc, byte *argv)
{
  Firmata.sendSysex(command, argc, argv);
}

void setup()
{
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
  pinMode(13, INPUT);
}

void loop()
{
  while (Firmata.available()) {
    Firmata.processInput();
  }
}

Full code of the desktop program:
import pyfirmata, time

class CustomArduino(pyfirmata.Arduino):
    def __init__(self, port: str):
        pyfirmata.Arduino.__init__(self, port)
        self.iterator = pyfirmata.util.Iterator(self)
        self.iterator.start()

        self.add_cmd_handler(0x71, self.receiveString)

    def receiveString(self, *args, **kwargs):
        print(f'Raw: {args}\n'
              f'Received: {pyfirmata.util.two_byte_iter_to_str(args)}')

    def sendString(self, data):
        self.send_sysex(0x71, pyfirmata.util.str_to_two_byte_iter(data))

    def send_sysex(self, sysex_cmd, data=[]):
        """
        Sends a SysEx msg.
        :arg sysex_cmd: A sysex command byte
        : arg data: a bytearray of 7-bit bytes of arbitrary data
        """
        msg = bytearray([pyfirmata.pyfirmata.START_SYSEX, sysex_cmd])
        msg.extend(data)
        msg.append(pyfirmata.pyfirmata.END_SYSEX)
        self.sp.write(msg)

print('STRING TESTER\nPlease input your COM port: ', end = '')
myCom = str(input())
device = CustomArduino(myCom)

while True:
    device.sendString(input('Send: '))
    time.sleep(1)

Strange detail: my Arduino is on the COM6 COM-port. If I connect it via my program and send com6 to the arduino, the D13 LED turns on!

As @timemage stated, strcmp returns 0 for equal. Sincerely in the provided code, while you send a message, which contents are not COMMAND, the LED will be turned on.
To get what we need, we must compare strcmp return value with 0! If it equals, then the strings match, and your suggested code is being executed:
void stringCallback(char *myString)
{
  if (strcmp(myString, "COMMAND") == 0) {
    digitalWrite(13, HIGH);
  }
  Firmata.sendString(myString);
}


Can we burn Arduino bootloader into any microcontroller chip? I am new to this Arduino community
I noticed on youtube that while the prototype is complete people purchase new ATmega328p chips and flash bootloaders into them using in-system-programmers so that the chip could actually understand and interpret the instructions that are written in the high-level language if I am right(No I was wrong, it's actually the compiler that sits on Arduino). so I thought what if we could burn the atmega328p bootloader into any other microcontroller. So that we could program it in Arduino programming language(C/C++). Is this possible? sorry if I am dumb, but I wanted to know. And can anyone tell me whether could we use ATmega328p for production purposes(consumer electronics)? Thanks in advance.

The answer needs to have multiple parts:

Yes, in principle you can create a bootloader for any microcontroller, which acts like the Arduino's.

Please be aware that there are different bootloaders, not just the common STK500 compatible one. Each of these bootloaders implements a certain protocol to transfer the binary code to the target system.

Additionally, some protocols also include commands to restart the microcontroller, to set configuration registers, and maybe more.

You need to read the bootloader's documentation to become familiar with its capabilities.

But it is your decision whether such a bootloader on a non-AVR system or an non-Arduino-AVR system is good for you.

No, the bootloader does not enable the microcontroller to "understand" the high-level language.

The standard Arduino IDE uses the specific compiler for the target microcontroller to translate the C++ source code to machine language. The resulting binary commonly runs on this target microcontroller only.

The bootloader just implements the protocol. In general, it is completely unaware of the meaning of the transferred data.

Microcontrollers in general use different processors with possibly different machine languages, contain different kinds of memory of different sizes, include different sets of different peripherals. But you know this for sure. You need to write and compile your source code for the specific part you're targeting.

Yes, you can use ATmega328P for a consumer product, as Michel already said.

You need to take the common measures that you take with any part of your product, though.


SIM900 AT command HTTP GET request not show the web page I build a simple HTTP GET request by SIM900. Here is it:

-----1-----
AT+CSQ

+CSQ: 25,0

OK

-----2-----
AT+CGATT?

+CGATT: 1

OK

-----3-----
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK

-----4-----
AT+SAPBR=3,1,"APN","indosatgprs"

OK

-----5-----
AT+SAPBR=1,1

OK

-----6-----
AT+HTTPINIT

ERROR

-----6.1-----
AT+HTTPPARA="CID",1

OK

-----7-----
AT+HTTPPARA="URL","http://www.minimalsites.com"

OK

-----8-----
AT+HTTPACTION=0

OK

-----9-----
AT+HTTPREAD

OK

-----10-----
AT+HTTPTERM

ERROR

+HTTPACTION:0,200,1240

-----10.0-----
AT+SAPBR=0,1

OK

The step 9 AT+HTTPREAD I supposed to see some html from http://www.minimalsites.com. But i dont see anything, What wrong with me?

From what I can see in your results, it seems AT+HTTPINIT returned an error. This means the HTTP service wasn't even successfully activated. So there's no way the commands you issued later would have been successful. From the AT command manual, AT+HTTPINIT is necessary before you can do any HTTP-related stuff.
You need to run the command AT+CGATT=1 to attach GPRS, even if your query shows its value is already 1.
It could also be that your APN requires authentication, using a username and password. So once you find out the username and password authorized by 'indosatgprs' (customer care?), you can use them in the following commands.

    AT+SAPBR=3,1,"USER","Enter the username here"
    AT+SAPBR=3,1,"PWD","Enter password"

Both commands should return OK if successful. To view all the parameters you have set, you can use AT+SAPBR=4,1. If all the parameters are satisfactory, and you have sufficient airtime in the SIM, then you can attempt AT+HTTPINIT. Only if this command returns OK, should you proceed to run AT+HTTPPARA-related commands.


Can an arduino tell between being powered by USB or by the jack? I have an arduino mega that will be communicating through serial to a pc. One of the things I want it to tell the pc is whether or not it is connected to a wall power to 12V converter (where there is a switch between the arduino and the wall power). I was just wondering if there was a way to do that in software without having any additional hardware.

Thanks!

No, you can't do it without extra hardware.

You need to pass VIN through a voltage divider so it sits within 0-5V when powered by 12V, then feed that into an ADC input. Protect the on-board voltage regulator with a diode between 5V (anode) and VIN (cathode). Then you can measure the voltage on VIN and make a decision on if it is around 4.5V or 11.5V

A 22K/10K voltage divider will reduce 12V down to 3.75V, which gives plenty of "headroom" for over-voltage situations (where your 12V unregulated power supply actually provides, say, 15V):


Reading 4-20ma signal on arduino I want to read a 4-20 mA analog signal from a 24V flowmeter. I've read the simplest way is to convert it into 1-5V signal using a 250 ohm resistor. The thing is I want my reading to be precise so my question is; is there any resolution loss when converting it to 1-5V?

I've also looked up on current to voltage converting boards similar to this one: https://www.sparkfun.com/products/14544

but I don't think they can detect 4mA signal.

I am a beginner in this so need some guidance here.

Using a resistor is the "Normal" way, yes. 250Ω will give you 1-5V, yes, which means that you get 4/5 of the actual resolution of the ADC at your disposal.

That means instead of 0-1023 you're actually reading 204-1023, or 819 possible values. Spread over 16ma (or 4V, which are the same thing) that gives you about 20µA resolution.

If you really really care about that extra 1/5 of the resolution you can instead use a 300Ω resistor to give you 1.2 to 6V, then pass that through a subtracting amplifier (see this post) and subtract 1.1V from it (you need to create that 1.1V, of course).  That will give you 0.1 to 4.9V, which then covers more of the ADC's available range (20-1002, or about 16µA resolution).

Is it worth it? Probably not. Any increase in resolution will likely be swamped by the inaccuracy of the resistor and potential drift though self heating.


How to return the value in Arduino function (that can be read by the connected device)? Right now I have an RC car program for Arduino. The code is like this:

void loop() {
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  if(Serial.available()) {
    lkf = Serial.read();
  switch(lkf) {
  case 'a':
     forward();
     servoX.write(90);
     lkf=0;
     break;
  }
}

I wrote a TCPclient that can order the RC car to move forward by connecting through TCP and sending the message "a" to the Arduino board.

The problem is how to return the distance to the cilent? Is it simply return distance; or something like system.println(distance);? Thanks for helping.

You are using the USB interface, right? So you just use Serial to send data back. For example, this would send the distance every second:

unsigned long lastSent;
void loop() {
  distance = Dist.getDistanceCentimeter();
  if (millis () - lastSent >= 1000)  // every second
  {
    lastSent = millis ();
    Serial.println (distance);
  }

  if (distance <= 5 & distance > 1)
  {
    if (Serial.available()) {
      command = Serial.read();
      switch (command) {
        case 'a':
          forward();
          servoX.write(90);
          command = 0;
          break;
      }  // end of switch
    }
  }
}


ESP8266 ESP-07 does not respond to commands I just bought an ESP8266 ESP-07 V1.0 Serial Wifi Transceiver. Similiar to this: https://www.ebay.com/itm/ESP8266-Serial-Wifi-Transceiver-Module-for-Arduino-ESP-07-V1-0-New-/331868488091

I have connect the RX and TX pins to the RX and TX pin of the Arduino (RX to TX and TX to RX), VCC is connected to 3.3V and GND is connected to Arduino ground.
I have used the following code and writing commands to the module using the serial monitor:

#include <SoftwareSerial.h>

int RX_PIN = 3;
int TX_PIN = 4;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

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

    while (!Serial){
    ;
  }

    while (!mySerial){
    ;
  }
  Serial.println("Ready");
}
void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( mySerial.available() )   {  Serial.write( mySerial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  mySerial.write( Serial.read() );  }
}

Whatever I type (for example AT+GMR) in the serial monitor at 9600 baud I don't get any response. What could be the reason? Both NL and CR is added to the command.

When pressing reset on the ESP-module I get this in the Serial monitoring:

Thanks for any help!

The esp8266 is without AT firmware. Even with SoftwareSerial at 115200 baud you should see "ready" from AT firmware and get some response to AT commands.

This esp8266 module adapter is simple to flash. It makes the 5 V to 3.3 V conversion for power and RX pin and has a program switch (io 0) and a reset button to put the esp8266 into flashing mode.

Use an USB-to-TTL-Serial adapter or an Arduino with USB chip to connect the adapter to PC. Then switch to "program" and reset it and it will be in flashing mode.

You can download the AT firmware here. I recommend ESP8266 NonOS AT Bin V1.7.1. Don't try 2.0, it is very different (ESP32 AT firmware build for esp8266).

To flash it, use esptool

The command to flash the AT firmware binaries to any module with at least 1 MB flash memory is:

esptool.py write_flash --flash_size 2MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin

don't wonder about the 2MB-c1 setting and don't change it. The AT binaries are build for 2MB-c1 partitioning. On 1 MB flash it will not support AT firmware OTA update.

If you want to use the Espressif Flash Download Tool, use the same settings as on esptool command line.


Switch two or more digital outputs of ESP8266 at the same time I'd like to control some digital ICs with a ESP8266-12.

How can I switch 2 pins to HIGH in the same moment?
How can I switch one to LOW and the other to HIGH in the same moment?
Is it possible with every port or only with grouped ports and how are the groups?

See the datasheet: esp8266-technical_reference_en

Paragraph 2.2.2 shows how to use the output registers.

With the registers GPIO_OUT, GPIO_OUT_W1TS and GPIO_OUT_W1TC you can set or clear multiple GPIOs.


Arduino Nano and ESP8266 I am trying to use Arduino Nano with ESP8266 (01). I tried to follow a lot of online tutorial with no result.

In particular this one http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/.
I think connections between Arduino Nano and ESP8266 are fine, when I upload the code on Arduino the red led on the ESP8266 turns on, I set the Arduino Monitor to 9600 BAUD and try to send command like "AT" but I got not reply from ESP8266. I also tried to switch to 115200 BAUD with no result too.

I don't if is something wrong or ESP8266 is damaged. Is there any tutorial that you may suggest?

Thank you.

The Serial Monitor's baud rate must match what you have in

Serial.begin(9600);

The EDP8266's baud rate is specified in the line

ESPserial.begin(9600);

and that is the one you need to change to try different baud rates with the ESP8266. The newer AIThinker firmwares default to 115200 baud, not 9600 baud.

Be warned, though, that SoftwareSerial isn't that great at 115200 baud - you tend to get some data corruption. It is best to change the baud rate to 9600 baud with

AT+CIOBAUD=9600

I'd also recommend investing in one of the ESP-01 programming boards from eBay. Make sure you get one of the ones with a switch on it that switches between programming and UART mode. Something like this one. It makes working with the ESP-01 much simpler - you can directly use your PC to set it up right for your system, and even upgrade the firmware (or program it directly with a sketch from the Arduino IDE if you install the right core) with minimum hassle.


sending and recieving data from esp8266 We're trying to make an network of connected cars in which the status of one car is continuously updated to the nearby cars (for example, speed, gear, brakes, etc.).

Can I continuously send out sensor data via ESP8266 and and any nearby ESP8266 can pick it up? Is it possible? Or if there's any other method?

Yes, you can - if all the "cars" are on the same WiFi network.

If that is the case, then I'd recommend using UDP as your transport layer, and either broadcast or multicast the packets.

I use UDP and Multicast to send sensor data from multiple sensors to multiple receivers on my network. All nodes subscribe to the same multicast address, and the sensors include their own ID in the packet to identify them. A sensor sends out one packet, and all the other nodes can receive it.

However, if there is no active WiFi network already established between the "cars" then no, there's not a lot you can do with an ESP8266. It communicates using IP, and that relies on there being an established layer 2 network (WiFi / Ethernet, etc) already in existence. You should instead investigate more peer-to-peer communication technologies, or communication technologies that don't rely on establishing a connection to a network of any form.  Maybe the nRF24L01+ would be a better fit?


Connecting to WIFI using esp8266 This is my code. I am tring to make a connection to my wifi through esp8266.

#define DST_IP "192.168.1.5" // my IP
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);

void setup()
{
  Serial.begin(115200);
  mySerial.begin(115200);
  while (! Serial); // Wait until Serial is ready - Leonardo
  Serial.println("AT+RST");
  delay(4000);
  Serial.println("AT+CWJAP=\"Ahmed\",\"12341234Aass\"");
  delay(4000);
  if (Serial.find("OK") )
  {
    Serial.println("1");
  }
  else
  {
    Serial.println("0");
  }
}

void loop()
{

}

This is the result of my code.

SoftwareSerial mySerial(0, 1);

try changing pin0 and pin1 with some other pins. (lets say with pin2 & pin3)

pin0 and pin1 are used by default Serial.


TIMER1 CTC Interrupts not working with avr-gcc I am attempting to program my arduino in plain C, and I've come across some very strange behavior. If I load the following code from the Arduino IDE, it works as expected and toggles Pin 6 every 100ms. However, if I compile it with avr-gcc and then load it with avrdude, no interrupts are run.
Here is the C code:

#include <avr/io.h>
#include <avr/interrupt.h>

int main();
void timer1_init();

int main()
{
    // connect led to pin PD6
    DDRD |= (1 << 6);
    PORTD |= (1 << 6);

    // initialize timer
    timer1_init();

    // loop forever
    while(1)
    {
        // do nothing
        // whenever a match occurs, ISR is fired
        // toggle the led in the ISR itself
        // no need to keep track of any flag bits here
        // done!
    }
}

// initialize timer, interrupt and variable
void timer1_init()
{
    /*cli();*/
    /*TCCR1A = 0;*/
    /*TCCR1B = 0;*/
    /*TCNT1 = 0;*/
    OCR1A = 24999;
    TCCR1B |= _BV(WGM12) | _BV(CS11) | _BV(CS10);
    TIMSK1 |= _BV(OCIE1A);
    sei();
}

ISR (TIMER1_COMPA_vect)
{
    // toggle led here
    PORTD ^= (1 << 6);
}

And here is the Makefile I'm using to load it onto the arduino:

CC = avr-gcc
CFLAGS = -g -O0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106

SOURCE = test

all: load

$(SOURCE): $(SOURCE).o
    $(CC) $(SOURCE).o -o $(SOURCE)

hex: $(SOURCE)
    avr-objcopy -O ihex -R .eeprom $(SOURCE) $(SOURCE).hex

load: hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodem1411 -b 115200 -U flash:w:$(SOURCE).hex

clean:
    rm -f *.o *.hex
    rm -f `find . -perm 755 | perl -pe 's/\.\n//g' | perl -pe 's/\.\/(\w+)\n/\1 /g'`

Is there something that the arduino ide automatically adds to it that makes it work? What am I missing?

Edit: Here is the make output:

avr-gcc -g -O0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106   -c -o test.o test.c
avr-gcc test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodem1411 -b 115200 -U flash:w:test.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
         avrdude: erasing chip
         avrdude: reading input file "test.hex"
         avrdude: input file test.hex auto detected as Intel Hex
         avrdude: writing flash (196 bytes):

         Writing | ################################################## | 100% 0.04s

         avrdude: 196 bytes of flash written

         avrdude: safemode: Fuses OK (E:00, H:00, L:00)

         avrdude done.  Thank you.

I just tried using arduino-mk https://github.com/sudar/Arduino-Makefile, and it worked, so I guess I'm just going to stick with that.


Using c_str() on String for IPAddress with NTPClient provides wrong values Libraries

NTPClient

Board

Olimex ESP32-POE board

Behaviour

I have written a code that connects the board to a local NTP Server (which is an embedded board). I tried assigning the IP Address of the above NTP Server using IPAddress and then convert it to c_str() to pass into the NTPClient constructor as follows:

 WiFiUDP ntpUDP; // udp socket object for NTP

 IPAddress NTPServer(192.168.3.11); // Local NTP Server IP Address

 NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000);

The reason for this is because the NTPClient class uses const char* for the IP Address of the NTP Server.

The values that are obtained once the code is flashed on the board are wrong because the timestamps are have the year 2106.

On the contrary, when I use

 NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000);

and run the code on the board, this provides me perfect values of UTC time.

Why is there some discrepancy here?

Code

#include <Wire.h>
#include <ETH.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <RTClib.h>

WiFiUDP ntpUDP;
/* IP CONF for NODE */
///////// >>>> MODIFY Values Here <<<< ////////
const IPAddress node_static_ip(192, 168, 3, 101);
const IPAddress default_gateway(192, 168, 3, 250);
const IPAddress subnet_mask(255, 255, 255, 0);
const IPAddress dns_add(192, 168, 3, 250);
const IPAddress NTPServer(192, 168, 3, 11);

NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000); // This works
NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000); // This won't (provides timestamps of 2106)

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL);
  Serial.begin(115200);
  ETH.begin();
  ETH.config(node_static_ip, default_gateway, subnet_mask, dns_add);
  delay(1000);
  if (!rtc.begin()) {
    Serial.println("No RTC");
  }
  timeClient.begin();

}
void loop() {
  // put your main code here, to run repeatedly:
  timeClient.update();
  Serial.println(timeClient.getEpochTime());
  DateTime now_time(timeClient.getEpochTime());
  Serial.print(now_time.year(), DEC);
    Serial.print('/');
    Serial.print(now_time.month(), DEC);
    Serial.print('/');
    Serial.print(now_time.day(), DEC);
    Serial.print(now_time.hour(), DEC);
    Serial.print(':');
    Serial.print(now_time.minute(), DEC);
    Serial.print(':');
    Serial.print(now_time.second(), DEC);
Serial.println();

  delay(2000);

}

The String object created as return from IPAddress.toString() as parameter to constructor of NtpClient is temporary. It contains the char array returned by c_str(). NTPClient doesn't copy the string, only stores a reference to it. And the referenced string (char array) doesn't exist at the time the NTPClient wants to use it.

class TestClass {
public:
  TestClass(const char* _ip) : ip(_ip) { }

  void test() {
    Serial.println("--");
    Serial.println(ip);
    Serial.println("--");
  }

private:
  const char* ip;
};

//String s("abc");
//TestClass Test(s.c_str()); <- this works

TestClass Test(String("abc").c_str()); // <- this can't work

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


Frequency of Retrieving Data from Website I have wrote a code that communicate with my website to retrieve data to power on or off a 5V relay. I'm running the code every second to make sure it is real time. Is there more efficient way to tell Arduino to get the data whenever it is changed rather than continuous GET request.
// Send HTTP GET request
  int httpResponseCode = http.GET();

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");        Serial.println(httpResponseCode);        String payload = http.getString();
        StaticJsonDocument<2000> doc;             DeserializationError error = deserializeJson(doc, payload);
        if (error) {              Serial.print(F("deserializeJson() failed: "));              Serial.println(error.c_str());              return;            }

        String status = doc["status"];
        Serial.println(status);
         if ( status == "ON" ) {
           digitalWrite(ledPin, LOW);
         } else {
           digitalWrite(ledPin, HIGH);
         }
  }

Your two best options would be MQTT and WebSockets.
Both would open a long lived TCP connection that the ESP8266 and browser could use to transmit and receive data. Both would avoid constant polling to see if there's a new command.
MQTT requires an external broker. There are MQTT services with free tiers you could use for this or you could run one locally - Eclipse Mosquitto is a popular MQTT broker that runs nicely on a Raspberry Pi. MQTT is particularly useful for networks with multiple publishers and subscribers (it's a "pubsub" protocol) and is probably overkill if you just have a single device and endpoint.
It's easy to use MQTT from a browser using Javascript. The Paho Javascript MQTT client works well. The ESP8266 would establish a connection to the MQTT broker, subscribe to a topic name and set a callback function that would be called when data was published to that topic. The browser would also establish a connection to the MQTT broker and would publish a message to the topic when responding to events from the user.
WebSockets would allow the ESP8266 and browser to establish a full duplex connection between them. The ESP8266 would create a websocket server which the browser would connect to. The ESP8266 would check for data on the websocket during while running code in loop() and would assemble messages from the browser.
Either works easily if both your devices are on the same network (for instance, at home). If your browser is outside the network, it won't be able to communicate directly with the ESP8266.
MQTT has the advantage that an MQTT server located outside of the network (not one running locally on a Raspberry Pi) would allow the browser and ESP8266 to communicate with one another through it. WebSockets would require the use of a proxy server (there are modules for popular web servers like NGINX and Apache, but this requires control of the web server to configure). If you only ever want to use the browser to control the ESP8266 while they're both on the same network you don't need to worry about this.


Cannot display a chr string using Wire.read() and u8g2.drawStr() I'm still getting myself acquainted with C++, so I expect this is a very basic issue I'm facing. I've got an OLED screen connected to a Teensy LC and can display text on it just fine. The Teensy receives bytes via I2C, and I want to reassemble those bytes into strings and display them on the OLED.
My relevant code:
#define I2C_ADDRESS 4
char buf[16];

void setup(void) {
  Serial.begin(9600);
  Wire.begin(I2C_ADDRESS);
  Wire.onReceive(receiveData);
  u8g2.begin();
}
void loop(void) {
  // U8G2 setup code snipped
  // This line doesn't output anything on the screen:
  u8g2.drawStr(0, 0, buf);
  // This line does:
  u8g2.drawStr(0, 20, "Foobar!");
  u8g2.sendBuffer();
  delay(1000);
}

void receiveData(int byteCount){
  Serial.print("Data received: ");
  int i;
  for (i=0; i<byteCount; i++)
  {
    buf[i] = Wire.read();
    Serial.println(buf[i]);
  }
  buf[i] = '\0';
  Serial.println(buf);
}

In the receiveData() function, the Serial.println() within the for loop prints out each letter of the payload as it's received, one after the other - but the Serial.println() below the for loop, which in my estimation should print out the whole message, prints out a blank line. I presume that's related to the fact that the received string doesn't show up on the OLED display.

This is kind of convoluted to put as a comment and it is sort of an answer, so I'm making it an answer.  Just to warn you, I have not tried to compile any of the code snippets here.
Wire.onReceive(receiveData); registers your function so that it can be later called back in the context of the interrupt service routine used for handling I2C ("Wire") data.  Or at least this is how it usually works.  So when your receiveData function is running you are in the middle of handling an interrupt associated with the I2C peripheral.
Using Serial.print(), .println(), .write(), and many other things, including non-serial related things like delay() inside of an interrupt service is usually a no-no.  On the AVR Arduino core, if the outbound serial buffer happens to fill, your code will deadlock with the underlying .write() waiting for there to be room in the outbound serial buffer and the serial transmit interrupt waiting for .write() to get done waiting for it.  I don't know how the Teensy LC and its MCU are configured, whether or not it prioritizes interrupts, etc, but it is likely that you're still not supposed to call functions like these inside the interrupt context.
There's really not a lot you're supposed to do in an ISR except:

communicate with hardware (which is being done for you here)
manage the non-volatile variables that belong to the ISR itself.
set global volatile qualified variables to communicate with the main line of execution.
call functions that have no shared state with the main line of execution.
call functions that have shared state but are carefully designed to be called from both ISR contexts and main line of execution.

That said, I don't know precisely why you're seeing what you're seeing, but I'm not overly surprised either.  The above may be related to it, but I haven't drawn that connection yet.
The way you currently have receiveData, it may overflow buf.  All that's required for that is for the sending side to send more than 15 bytes.  Any number of weird things can happen if you manage to overflow.  Is it related? Maybe.
For communicating between the receiveData running in the ISR context and the main line of execution in loop, buf should be volatile qualified.  Without that the main line of execution can behave as though buf never changes after it is first seen.  Because of how you're using it and familiarity with the compiler, I'm going to guess that this isn't manifesting as a bug, but I don't know that; it could be related.
So I'd recommend updating something like your buf declaration to volatile qualified and removing the Serial print calls from the receiveData function, and preventing overflow:
volatile char buf[16];

/// ...

void receiveData(int byteCount){
  static const size_t room_for_non_null_chars = sizeof buf - 1;
  const size_t read_amount = min(byteCount, room_for_non_null_chars);

  int i;
  for (i = 0; i < read_amount; ++i) {
    buf[i] = Wire.read();
  }

  buf[i] = '\0';
}

If it weren't for the fact that we need to read into something volatile qualified the above loop could really just be a read call taking the buffer and size.  You can see that's updated to prevent overflow.
Part of loop would then become something like:
void loop() {
  char non_volatile_buf[sizeof buf];
  size_t write_index = 0;

  noInterrupts();
  for (char c: buf) {
    non_volatile_buf[write_index++] = c;
  }
  interrupts();

  // U8G2 setup code snipped
  // This line doesn't output anything on the screen:
  u8g2.drawStr(0, 0, non_volatile_buf);

  // ...

We're turning off interrupts while copying the data into a local buffer so that the onReceive handler cannot interrupt the use of the buf, updating while you're in the middle of using it in drawStr.
If you care about losing messages there's more that would need to be done.  Surrounding what to do if you've got a call to receiveData while there's a message currently in buf.  The way the above is written it just drops whatever is in there whether it's been seen by loop() or not.


Are there any electro-chemical sensors available to measure nutrient contents of soil? I want to develop a soil fertility testing device and need an electro chemical sensor to do so.
I searched the online available sensors but didn't get any source. Does anyone knows anybody in development of such sensors ?

You have pH and humidity sensors for Arduino, but "soil fertility" is an unprecise term.

If you do a web search, you will find results for a number of devices that claim to measure soil fertility. I am highly suspect of these devices. Even laboratory testing cannot tell you accurately how fertile your soils are because of the methods used. Most labs test for the presence of inorganic chemals, including nitrogen, potassium, phosphorous and an array of other nutrients plants need. What most of them do not or cannot measure is the amount of plant-available nutrients in the soil. It takes a host of soil organisms to make nutrients in the soil available to plants. If those organisms are not present or are low in numbers, it is difficult for plants to take up nutrients. Fertilizers only exacerbate the problem because they kill off soil organisms, especially mycorrhizal fungi, throwing the entire ecology of the soil out of kilter. There are a couple of laboritories out there that test for soil biology and some nutrients.

Soil is hard. There is a lot of things in soil (compactness, unwanted chemicals/elements, microbes) that can affect the fertility, even if you have the right nutrients in it.

For hydroponic (not your case), you have cheap handheld EC/TDS meters. The pH and EC of your reservoir is all you need to measure the fertility of your water solution.

Go hydro and stop worrying about your tomatoes.


How to track revolution of DC motor? I am currently trying to build a line follower robot that is designed to solve maze. This maze has a loop, thus it needs to know distance it already travelling (or at least I assume so, please let me know otherwise).

I am aware of a rotary encoder motor from Polulu (for example) but it's not available in my country and shipping price is too expensive.

So I need to find way around it. Should I use Stepper motor? Is there any other way? Thanks in advance.

You can Use wheel encoders. You can even make your own wheel encoders with general parts like photoTransistor and lasor or led light. you can make your encoder or print it out in paper. The use little math to calculate the distance. It will give you measurement with good level of precision.

Basic principle:

more information at

wheel Encoder

another encoder


Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?) I've a SparkFun Pro Micro which is an Arduino Leonardo clone. Unfortunately my attempts to upload programs failed. I did some research in the internet and found you have to use SparkFun's configuration. There is a board manager's URL you have to use: https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

So far so good. After trying to use this I attempted to do an upload and failed. I tried it with different settings but all failed. While earlier there was a serial port named /dev/ttyACM0 there now is no such port any more. Further research gave me the information that you might get the device running if you a) reset to boot loader mode where you should have an 8 seconds window to upload and b) actually perform the upload.

I can verify: If I pull RESET to ground I can switch into this 8 seconds mode. Then the device /dev/ttyACM0 appears after about 1 second for about 7 seconds. As instructed I immediately try to do an upload. This is strange: I immediately (!) get the following output:

Line 1: Sketch uses 4140 bytes (14%) of program storage space. Maximum is 28672 bytes.
Line 2: Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.
Line 3: avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
Line 4: Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The TTY should be there as the 7 seconds have not been passed in that case. Furthermore my user account is in dialout which enables it to use the tty.

If I trust this error message that means the tty is gone as soon as avrdude tries to access it. Which shouldn't be that way, should it?

Has anyone encountered this situation before? How can I upload a program to the mikrocontroller? Has anyone has any experience with that situation here?

--

Additional information:

ArdunoIDE 1.8.5
Ubuntu (Mate) Linux 16.04

We use these a lot, and it's very easy to accidentally program the boards with the incorrect settings - particularly as the Sparkfun Pro Micro library defaults to the 3.3V/8 MHz variant instead of the more common 5V/16MHz.

I have recovered the boards with the bootloader reset method, but it is hard - you have to get the timing just right. What we do now is to simply reinstall the bootloader using an ISP programmer (instructions: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader). It works first time, and ends up being much quicker than repeated tries to get the reset timing right. Just make sure that you have the right board selected when you burn the bootloader. We use a USBASP, and it only takes a couple of minutes to set up.


How can I tell which fuses are set on an ATtiny? Following on from this question, Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature,
if the response from avrdude is 0x000000 then the internal oscillator is probably not being used and an external one (be that crystal or clock signal) is required.
However, as this menu, from Engbedded Atmel AVR® Fuse Calculator, shows, there are a lot of options:

So, instead of having to configure circuits for each of the options, in turn, until the ATtiny responds, is there any way that I can read which of the CKSEL and SUT fuses are set?1

Background
I am using a Nano/Uno as an ISP programmer, and the ATtiny is on a dev board like this (although it would be the same issue if I were to use a breadboard):

I know for sure that the connections are fine as I have checked them from pin to pin of the two ICs (ATmega328PU to ATtiny85), using a DMM.
I am receiving 0x000000 as in:
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

because the ISP programmer can't read the ATtiny, because an external clock source has been set via the fuses. However, I wish to know how to read which clock source has been specified, without having to manually try all of the circuit permutations.
I don't think that just connecting a crystal (and two ceramic capacitors) will work if the exact setting, i.e. external clock, has been selected. However, if a 16MHz crystal works for all, or any, of the external clock settings then that would be great, but I'm sure it doesn't work like that, as you can have a crystal attached but the it might not be used, see Does device signature 0x000000 mean the atmega is bad:

Even though you have a crystal connected, that does not mean it is oscillating. For example, IF you set fuses for "External Oscillator", that will turn the crystal oscillator off.

When I move the ATtiny85 to a breadboard and add a crystal (16 MHz) and two 22 pF capacitors, the error has changed for the better (at least now it sees that a ATtiny is connected)
avrdude: Device signature = 0xff0000
avrdude: Expected signature for ATtiny85 is 1E 93 0B
         Double check chip, or use -F to override this check.

Interestingly the signature varies:

0xff0000
0x00ffff
0xff00ff

When I add an external power supply to the ATtiny on the breadboard, following advice from Atmega (any chip) Device Signature issues and stk500_getsync()(resolutions), then unfortunately the device signature in the response returned by avrdude reverts back to 0x000000
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

1 This is, admittedly, a bit chicken-and-egg, as if I can't communicate with the ATtiny, due to the incorrect clock setting, then how can I read which fuses have been set..?
It's a bit like saying "If I don't have petrol in my car, then how can I drive to the petrol station to fill up?" - but I was hoping that there might be some sort of time saving measure

This seems to be an X -> Y problem, with X being the missing clock source on your ATTiny, which prevents communication.

If you have a second Uno or other AVR device, you can use that to generate a clock signal on any of the digital pins:

void setup() {
  DDRB = 0b00100000;
}

void loop() {
  PINB = 0b00100000;
}

This creates a square(~ish) signal on Pin 13 with a frequency of 1.6 MHz.
Depending on the IDEs optimization level (platform.txt), a frequency of 4 MHz is also achievable (at -O3 instead of -Os).

Connecting this to the XTAL1 pin of your ATTiny85 should allow you to communicate with the board.
Make sure to interconnect all grounds.


How does the dual 5V and 3.3V output on the Uno R3 work exactly? I'm constructing a circuit that needs both voltage supplies (for 3.3V RFID and 5V relay, GPS and screen) but the Uno is physically too big so I need to use a nano or mini pro, both of which I can only get in 5V. I understand how to use a regulator to drop 5V to 3.3V for the RFID-IC power but I keep seeing instructions to use a level shifter between the IC outputs and arduino input pins. I was just wondering if the Uno has a built-in level shifter for all pins or some other method as the I/O pins do not have specified voltages or uses.

Thanks for your time.

Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.

ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.

Sources:

Schematics of Arduino Uno
Datasheet of ATmega328p (28.2 DC Characteristics)


4-digit 7-segment display resets when common pin set to HIGH I'm trying to make a simple stopwatch application with my Arduino Mega 2560 and a 4-digit 7-segment display, but the leftmost three digits only light up for a split second before they go out every time the counter increments up. The rightmost digit is counting normally.

After going back to basics to diagnose the problem, I've discovered that every time one of the common pins is set back to high so I can pick another digit to manipulate, the digit goes blank.

Code for my basic program, which should display "0123" on my display.

int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);
  delay(5);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);
  delay(5);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

}

void loop() {
}

But all the display shows is a 3 on the rightmost digit. I followed the video in this guide and hooked my Mega up the same way. Is this still the right way to code a 4 digit display to make all the digits display different numbers, or is this normal behavior?

This should work (sort of). It will be flickery, but it should give you a starting place to work from.

int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {

  // put your setup code here, to run once:
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);
}


How do I read the fuse bits from within my sketch? How can I read the fuse bits from within my sketch?

You can use the boot_lock_fuse_bits_get function from <avr/boot.h>.

#include <avr/boot.h>;

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

    cli();
    uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
    uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
    uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
    uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
    sei();

    Serial.print("Low:  0x");
    Serial.println(lowBits, HEX);
    Serial.print("High: 0x");
    Serial.println(highBits, HEX);
    Serial.print("Ext:  0x");
    Serial.println(extendedBits, HEX);
    Serial.print("Lock: 0x");
    Serial.println(lockBits, HEX);
}

void loop()
{
}


Can I use a UDOO as an Arduino? I have a UDOO, and I wonder whether or not it is possible to use the Arduino that it has without starting the UDOO's operating system, i.e., I would like use Atmel Studio to load a program within the Arduino at UDOO.

Yes, but you have to erase the flash (and reset the ATMEL SAM3X8E processor) manually before the programming. You can use the J16 and J22 jumpers to do this.


First Project (auto garden) I've been tinkering for quite a while and I'm looking to try out an arduino to control an automated small garden project for growing seeds. I've never done any coding before and am looking for some advice on what hardware/software I should use that's easy to learn and will work for my application. My idea is to have an arduino control a lighting and sprinkler system that would work on timers to be on or off at specific intervals with the potential to be upgraded in the future to run off moisture sensors when I feel more confident in my coding abilities. I'm trying to keep this project on a budget so the Arduino nano is tempting because of its price point but could it do everything I want? Any advice or recommendations are welcome, thanks.

There's a few similar projects already done on YouTube, which you can use for guidance. If this is your 1st project using arduino I would recommend the Uno as is the easiest to work with. As you become more familiar with microcontrollers you can easily switch to the nano.
As for what sensors you decide to use is up to you. You have quite a bit of flexibility. Check out Adafruit and arduino websites for ideas. What you choose to go for would depend on the specifics of your project, which a bit vague in this post.


Peristaltic Pump Project I am designing a peristaltic pump and need some advice for parts. I am using an Arduino Leonardo and also have an UNO and am planning on adding a temperature and pH sensor as well. I have two questions:

1) I am planning to use a Stepper Motor but am unsure if I should use the NEMA 17 or 23 or some other motor. I need a relatively "high" amount of torque maybe around 1 to 3 N-m.

2) Should I go with a Motor Shield or Motor Driver. I am currently looking at the Big Easy Driver or A4988 Bipolar Driver or the simple Arduino Motor Shield.

Does anyone know which of these would be best or have any suggestions? Thank you very much!

The specifications for each stepper motor varies, with the larger models having the greater torque. With great torque comes the requirement of great power. A quick search for nema 17 stepper motors finds the torque figures on the low side of your request, while the nema 23 motors display a greater range, including your figures.

The additional power requirements may exceed the capabilities of the Arduino Motor Shield (2a per channel, 4a max), while the A4988 board specifies up to 2a per coil. Also note that to achieve the use of the higher power levels, these boards will require heat sinks.

If you expect to require the higher figure for torque, consider to research for a driver board that has a greater power limit, "just in case".


Function is executing when I try to store it in an array I am trying to store a set of functions with different parameter in an array. When the code enters the function songlearn with tune==1 I want the functions with set parameters to be stored in the array without executing. What am I doing wrong? Here's my code:

const int x=100;
int (*SongSeq[x])();
int note[x];
int playNote(int midi, int row, int col, int len, bool short_led = false);
void songlearn(int tune);
int tune;

void songlearn (int tune){
  if (tune==1){
    state=1;
   lcd.clear();
  lcd.setCursor(4,0);
  lcd.print("Learning Song :");// Print a message to the LCD.
  lcd.setCursor(1, 1);
  lcd.print(menuP1);
// if (songpage==1){
// if (BackState==HIGH){//leaving song
//     posP=0;
//     Page=2;
//    Play(posP);
//    }
// }
  //Plays Mary Had a Little Lamb on a loop at 145 BPM
//Bar 1
SongSeq[0]= playNote(0x40, 3, 1, 414); //Quarter note: E
note[0]=0x40;
SongSeq[1]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[1]=0x3e;
SongSeq[2]=playNote(0x3c, 2, 2, 414); //Quarter note: C
note[2]=0x3c;
SongSeq[3]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[3]=0x3e;
//Bar 2
SongSeq[4]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[4]=0x40;
SongSeq[5]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[5]=0x40;
SongSeq[6]=playNote(0x40, 3, 1, 828,1); //Half note: E
note[6]=0x40;
//Bar 3
SongSeq[7]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[7]=0x3e;
SongSeq[8]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[8]=0x3e;
SongSeq[9]=playNote(0x3e, 2, 4, 828,1); //Half note: D
note[9]=0x3e;
//Bar 4
SongSeq[10]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[10]=0x40;
SongSeq[11]=playNote(0x43, 3, 4, 414,1); //Quarter note: G
note[11]=0x43;
SongSeq[12]=playNote(0x43, 3, 4, 828,1); //Half note: G
note[12]=0x43;
//Bar 5
SongSeq[13]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[13]=0x40;
SongSeq[14]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[14]=0x3e;
SongSeq[15]=playNote(0x3c, 2, 2, 414); //Quarter note: C
note[15]=0x3c;
SongSeq[16]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[16]=0x3e;
//Bar 6
SongSeq[17]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[17]=0x40;
SongSeq[18]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[18]=0x40;
SongSeq[19]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[19]=0x40;
SongSeq[20]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[20]=0x40;
//Bar 7
SongSeq[21]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[21]=0x3e;
SongSeq[22]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[22]=0x3e;
SongSeq[23]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[23]=0x40;
SongSeq[24]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[24]=0x3e;
//Bar 8
SongSeq[25]=playNote(0x3c, 2, 2, 1656); //Whole note: C
note[25]=0x3c;

//End song
  }
 }
 int playNote(int midi, int row, int col, int len, bool short_led = false)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}

What you have done will certainly call the function. Since it is always the same function, just store the arguments into an array. Something like this:

const int COUNT = 100;

struct
  {
  int midi;
  int row;
  int col; int len;
  bool short_led;
  } notes [COUNT] = {
  { 0x40, 3, 1, 414 },  //Quarter note: E
  { 0x3e, 2, 4, 414 },  //Quarter note: D
  { 0x3c, 2, 2, 414 },  //Quarter note: C

  // and so on
  };

int playNote(int midi, int row, int col, int len, bool short_led = false);

void setup()
  {
  // put your setup code here, to run once:
  }

void loop()
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (notes [i].midi)
      playNote (notes [i].midi, notes [i].row, notes [i].col,
                notes [i].len, notes [i].short_led);
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}

  yeah but i want to be able to store the function in an array with the set parameters

Do you? I wonder why.

Anyway, you can do that by making an array of lambda functions like this:

const int COUNT = 100;

int playNote(int midi, int row, int col, int len, bool short_led = false);

void (*SongSeq[COUNT])() =
 {
 [] { playNote(0x40, 3, 1, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,
 [] { playNote(0x3c, 2, 2, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,

 // ... and so on

 };

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

void loop()
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (SongSeq [i])
      SongSeq [i] ();
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
  Serial.print ("Playing note ");
  Serial.println (midi);
  delay (100);
}


Does anyone have a data sheet for MC16-0072 I can't seem to relibly find data sheets for MCM electronics parts.. Searched for hours.. Any help?

A quick search gave me the impression that MC16-0072 is actually some sort of rebranding. It seems MCM is not the manufacturer, simply a distributor.

Does the hardware itself have any number or serial printed on it?

In any case, when I dug a bit deeper and found this datasheet. However, without an image of your hardware or its serial number, I cannot confirm the datasheet is for your hardware.


Why is my DHT22 sensor reading 1.00% humidity? I have a seemingly simple problem but I haven't found a solution yet. I recently got a DHT22 temp/humidity sensor and I wired it according to the guide from Adafruit.

I downloaded and installed the library. I loaded the "DHTtester" example sketch. I also included the Adafruit Unified Sensor library to be safe, because the guide said I might need to. But when I upload the sketch and check the serial monitor the humidity value is always "1.00%". The temperature also seems to be off by about 4 degrees F.

I don't know what is going wrong here. I've removed the 10K resistor but nothing changed. Does anyone know why this might be happening? Any help would be appreciated. Thanks!

I have 2 suggestions for you.

If you compare these 2 data sheets:
This one says "adafruit learning systems" on it
and this one is from the Adafruit website
, you'll see there is a discrepancy regarding the pull-up resistor value to use. One document says 10k ohm, the other says 1k ohm. It's a bit of a long shot, but you could try adding another 10k ohm resistor in parallel with the one you already have on the data line. This gives you an equivalent resistance of 5k ohm which works when used on a DHT11 sensor (cheaper, less accurate version of the DHT22).
There are several versions of the DHTxx library out there, so my next suggestion is to try a different one. You may have to remove the library you currently have installed before trying a new one.


Serial broken into two shorter shorter strings I'm trying to do a serial read:
    if (Serial.available() > 0) {
  int inputValue = Serial.read();
  Serial.println();
  Serial.println("I got this:");
  Serial.print(inputValue, BIN);
}

However, it seems that what I receive is always 6 bits first and then followed by 4 bits. I'm really confused. I used a different board just to be sure that it's not just a problem with the board. Could it be the serial monitor I'm using? I'm using the Arduino serial. This is an example of the output:
21:31:02.021 ->
21:31:02.021 -> I got this:
21:31:02.021 -> 110101
21:31:02.021 -> I got this:
21:31:02.021 -> 1010

Can anyone shine a light as to what is happening here?

I guess you are sending 5 and have the line ending set to newline only. Then everything is correct and as expected. You see 2 bytes, that are transmitted. Serial.print() will cut out the leading zeros of the byte, so all other digits before that are just zero.
The first byte is the character 5 encoded in ASCII (53 is the decimal representation of the ASCII value here). The second byte is the newline character \n, which marks the end of a line or the end of the data message (depending on the interpretation of the data). If you don't want to send the newline character, select Nothing for the line ending (My Arduino IDE is in German, so I don't know, what exactly is the term in the english version here, but you need to set it for not using any line ending).
As it seems, that you don't know that currently: When you write a number into the serial monitor, you are not sending the direct binary value of that number. You are sending the ASCII representation of the individual digits. ASCII is a system, where the values of a byte represent a character. That includes decimal digits, the alphabet and some special characters. So when you type "255", you are not sending 0b11111111 (1 byte with all bits set --> decimal 255), you are sending 3 bytes with the ASCII byte value for the characters 2, 5 and 5. You can read the byte values for all the characters in tables, just by googling for "ASCII" and looking at the images found.


TX pin sends wrong data in Arduino Uno I want to send some data to an IP Modem from Arduino Uno. That IP Modem has TTL levels TX and RX inputs.

I used this connection between Arduino to the IP Modem:

I am powering Arduino with 12 V plugged in the barrel.

This is the photo of the connections:

I connected the PC to the USB connector of Arduino and I uploaded the following sketch to send "AABB" to the Modem:

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

void loop(void) {
 Serial.print("AABB");

 delay(5000); // Envía la temperatura cada 5 segundos
}

When monitoring what is received by the modem, it is

0x5F 0x5F 0xAF 0x2F

If I send just "A", the character received each 5 seconds is 0x5F.

Of course, both ends are configured as 115,200bps, 8N1.

In order to discard Modem problem, I connected RX, TX and GND in Arduino to a DB9 female connector and then to a RS232 - USB converter and started monitoring with my PC.

My surprise was that the data received is exactly the same as the received by the modem when it was connected. As seen in the following picture:

As you see in the picture, "_" twice was shown (ASCII 0x5F), {\xaf} and finally "/" (ASCII 0x2F).

Above test confirms Arduino is sending wrong data.

Something to note. When I monitor using USB cable connected to Arduino and using Monitor Serie in the Arduino IDE, I  see correctly "AABB". The problem is when using TX and RX pins (the same happened if I used other pin along with SoftwareSerial library)

What may be going on?

Since you have already tried SoftwareSerial, also try inverting the serial protocol via SoftwareSerial.  Sometimes a device uses inverted serial protocol and you don't know it.

So initialize inverted add 1 to the end of the contructor like so :

SoftwareSerial mySerial(RXPIN, TXPIN,1); // RX, TX, inverted


Reducing static on button reading I have a very simple code for a controller I'm working on for a robot.

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(3));
}

The only problem is that I can't get a constant reading on switches because when I flick the switch I will get a constant stream of 1s, but when I flick the switch off I get a sporadic stream of ones and zeros. I have noticed though that if I put my finger on the USB port leading from my Arduino Nano I get a constant stream of 1s when on and zeros when off.

Does anyone have a recommendation to get around this problem or simulate touch on the USB port?

Sounds like you need a pull-down resistor.

If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.

Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.

If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.

(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting INPUT_PULLUP instead of INPUT when you configure the pin with the pinMode() function. That way you don't need an extra resistor.)

Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)


Connect function generator to Arduino How do I connect a function generator that generates an analog signal to an Arduino Uno?

I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?

I plan to visualize the output on Processing.

Confirm with an oscilloscope

When I connect my function generator I usually always make sure that the output is in the range 0 to 5V, with my oscilloscope. The default is probably more like ±2.5V - but I don't have an Agilent so you would have to check. Press the Ampl button to check. (Mine reads 5VPP).

You can see from the above image that we indeed have (roughly) 5VPP - and that there is a -2.56V component, which will damage the Arduino, being negative.

Add an offset

So press the Offset button and add a 2.5V DC offset. Now the voltage jumps 2.5V and is between 0 and 5V:

The scope confirms that the minimum is 80mV and the maximum is 4.96V, which is in range for an Arduino pin (assuming you are running an Arduino at 5V, which is not always the case).

Now you should be safe to experiment with different frequencies and wave-forms. Just leave the Amplitude and Offset alone. :)

Extra precautions

You could feed the function generator through an input protection circuit, just in case you absent mindedly forget to carry out the appropriate steps.

The zener diode will conduct negative voltages to ground (dissipated through the 1k resistor) and will also limit positive voltages to around 5.1V.


How do I connect an 8x8 LED RGB matrix to an Uno? I have this 8x8 LED RGB matrix. How do I get it connected to an Arduino Uno?

It came with no other wires/modules/connectors and has a veritable crap-ton of pins to connect.

Because you have, unfortunately, decided to buy a product without a datasheet (and the product description can't even decide if it's common anode or common cathode!), you'll have to find a product which is similar that has a datasheet, and determine by experimentation if the pinout matches.

For instance, this Sparkfun LED matrix looks similar. Take a look at the datasheet for an internal schematic and manually verify the pinout.

Once you know the pinout, you can begin to figure out how to drive it. There are many ways to drive large numbers of LEDs, one of the simplest of which is a bunch of shift registers.

Getting yourself a couple of 595 SRs and playing with the matrix (hint: try and get a single colour working first, then add the others) would be a good place to start.

Alternatively, the display description says that it is compatible with "Arduino RGB LED Matrix Driver Shield". That may or may not be true, but looking at a schematic of that board would give you insight into how to drive the matrix. I believe that board uses a DM163 8x3 CC LED driver chip, which seems to be perfectly suited to drive the matrix, but buying and wiring that chip up may be non-trivial.


Error while burning bootloader I am trying to burn bootloader on Arduino UNO using MEGA2560 as the programmer,
I followed the steps stated here but still get the error below:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/arduino/arduino-nightly/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/webdev/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Note: The Arduino UNO stopped responding when I mistakenly short-circuited a connection, I mistakenly passed 12v to one of the header pins of sensor shield mounted on the board.
How it was connected

Based on this:

Note: The Arduino UNO stopped responding when I mistakenly
short-circuited a connection, I mistakenly passed 12v to one of the
header pins of sensor shield mounted on the board.

There are no I/O pins on the Arduino that are 12V tolerant.  You have almost certainly "fried" your Uno board.  It's possible the only casualty is the ATMega chip itself and replacements are available from a number of sources or you can purchase a "raw" one from an electronics reseller and use your programmer setup above to burn your own boot loader.
It's also quite likely that your sensor board is damaged as well.
From the Microchip datasheet:

You want something like this:
Adafruit Pre-programmed ATMega168p
Buy several, accidents happen!


Circuit diagram interpretation and electrical flow I'm new to Arduino and consequently, to circuits. I've been reading Arduino Robotics by Warren and this was a circuit present in the book.

From what Warren has said, electricity in the circuit travels from the negative pole to the positive, BUT to imagine it as going the other way for simplicity. So, looking at this circuit... it seems useless to have the resistor placed after the LED, based on the + --> - model. Wouldn't the LED turn on before going through the resistor, rendering the resistor useless?

Sorry if this seems like a basic concept, I'm entirely new to this.

Should the Resistor be Placed Before or After the LED?

The important thing to remember is that the direct current electricity must flow through the circuit to be useful. Since the resistor is part of the circuit (meaning that there isn't another path for the current to take) it resists the overall flow, thereby helping to protect the LED. Whether before or after the LED, it would still be in the circuit, and would therefore still reduce current flow.

Visualizing the Flow of Water

Think of it like a water hose, where the LED is a flow meter and the resistor is your foot. If you step on the hose before the flow meter it will cause the overall flow to slow down. Stepping on the hose after the flow meter but before the nozzle will have the same result, as the water must pass through the entire length of the hose before being released.


Arduino Fried? Power is being delivered to Arduino but COM not found When i connect my arduino nano to windows 10; the arduino nano is powered on (the "POW" led is on and not blinking; none of the others are on) but it doesn't show up on my computer. It used to but I think I may have shorted it.

Oddly, I get a measurement of 5V coming from digital pins 2,3,4 if connected through USB or 12V if I connect external power source to V_in. These are the pins that were on before what I believe was a short. Can someone tell me what is the component that is damage and whether it is possible to fix. Thanks!

If you were powering from 12V and shorted the 5V to GND then yes, it is all dead. The regulator will have stopped regulating. 12V will have then been sent to every component on the board. The USB chip, the main MCU, the 5V regulator - all will be toast.

You could repair it by replacing almost every component on the board, but when they're so cheap, why would you bother?


Convert Long to binary - least signifant bit first I have found an Arduino function which converts a 2-bytes-long-value to a binary value.

e.g. I call sendCommand(0x05) And it gives me an output:

00000101

void sendCommand(unsigned long command){
  for (unsigned long  mask = 1UL << (7);  mask;  mask >>= 1) {

    if (command & mask) {

    Serial.print( "1" );
    } else {

    Serial.print( "0" );
    }
  }
}

my Problem is, that I want to have the Least significant bit first. How do I have to adjust this function to achieve this?

e.g.
sendCommand(0x05)
shall give an output:

10100000

void sendCommand(unsigned long command){
  for (unsigned long  mask = 1UL; mask<256UL;  mask <<= 1) {

    if (command & mask) {

    Serial.print( "1" );
    } else {

    Serial.print( "0" );
    }
  }
}

PS a long is actually 4 bytes long. But your code only uses 1 byte of it.


Using N mosfet to switch ESC to BLDC phases I have an ESC that powers 36v 3 phase BLDC motor. The ESC has limited functionality and can power motor only in one direction. If I switch manually two of the ESC to Motor phase connections, than the motor direction will change. Now, I want to do the same i.e. switching phase to phase connections with 4 power mosfets.

As in scheme, the blue ESC phase will be connected to Mosfet source and the drain will be connected to Motors yellow phase. The next mosfet will connect to ESC yellow at source and motor blue at drain.  Two other mosfets will connect blue to blue and yellow to yellow.

I won't  do the switching while motor is on so I assume it should be safe.

How can I connect MOSFET's gate to Arduino ?
I need no pwm just ON/OFF.

This is covered fairly well in an EDN.com “MOSFET pair makes simple SPDT switch” article.  You would use two of the SPDT circuits to make a DPDT.  Attach switch commons to yellow and blue, and attach the “switch points” of one circuit to motor yellow and blue, and those of the other vice versa.  Attach both control pins to one Arduino IO pin.  The picture below comes from the referenced article, which shows the circuit in use for a primary-power vs secondary-power application.   See the article for details.


Is it possible to build a 1080p OSD webcam shield? What do I need to build a shield capable of receiving 1080p video from USB camera, timestamp each frame and send the frame to memory card?

None of the ATmega based boards have the hardware (in terms of acting as a USB host) or power (in terms of handling probably compressed 1080p video).

Potentially one of the ARM boards could do this. The Arduino Due can act as a host, but it sounds fairly experimental, and none of them will have drivers to connect to the camera.

If a shield was developed to do this, it would have so much more power than the Arduino that the Arduino would probably better be viewed as a slave to the other device.


Arduino SoftwareServo by example I am interested in writing a simple Arduino program that will turn a servo back and forth (180 degrees each time) continuously.

I am looking at these servos and am planning on following this example.

Being so new to Arduino, I first wanted to confirm that the SoftwareServo library in that example will drive those particular servos. If it will not, then can someone begin by explaining to me why these servos are incompatible with the lib?

Assuming they are compatible, I am looking at the main example on that page (comments stripped out for brevity):

#include <SoftwareServo.h>

SoftwareServo myservo;

int potpin = 0;
int val;

void setup() {
    myservo.attach(2);
}

void loop() {
    val = analogRead(potpin);
    val = map(val, 0, 1023, 0, 179);
    myservo.write(val);
    delay(15);

    SoftwareServo::refresh();
}

My concerns:

There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?
Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?
Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.
Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?
According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?

No, there is only 2 pins.  The value of the potentiometer attached to pin 0 is read and stored in the variable val.  That is then used to set the angle of the servo motor on pin 2.

  Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?

Yes.  It'll never get called.  setup() is the first function to be called and its purpose is to perform any initialization routines, such as attaching the servo code to the pin the servo is connected to.  So you have to call that either from setup() or from a function which setup() itself calls.

  Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.

map() is part of the standard Arduino API.  http://www.arduino.cc/en/Reference/Map

  Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?

You don't need the delay() call, but you don't want to set the value of the servo too rapidly.  You really want to allow at least one PWM cycle between each call to ensure the values have been set properly.

  According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

SoftwareServo is just what it says - a piece of software.  You have to run that software for it to work, and the refresh() function is that bit that you run.  If you don't call that then the PWM signal for the servo will never get generated and nothing will happen.

Oh, and yes those little servos should be fine.


Neo 6m outputting something i as a noob can't understand So i connected my ublox neo 6m gps breakout board GY-GPS6MV2 to the arduino software serial and got this result, i used resistors and only supplied 3.3v to the board, gps encode library couldn't give me anything out of this. if possible please help and if this is the wrong forum please suggest a better one. also the board thinks that the date for some reason is Mar 17 2011 16:18:34*59. which is pretty wierd.

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$GPTXT,01,01,02,ANTSUPERV=AC SD PDoS SR*20

$GPTXT,01,01,02,ANTSTATUS=DONTKNOW*33

$GPRMC,,V,,,,,,,,,,N*53

$GPVTG,,,,,,,,,N*3⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$GPTXT,01,01,02,ANTSUPERV=AC SD PDoS SR*20

$GPTXT,01,01,02,ANTSTATUS=DONTKNOW*33

$GPRMC,,V,,,,,,,,,,N*53

$GPVTG,,,,,,,,,N*3⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 F⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$GPTXT,01,01,02,ANTSUPERV=AC SD PDoS SR*20

$GPTXT,01,01,02,ANTSTATUS=DONTKNOW*33

$GPRMC,,V,,,,,,,,,,N*53

$GPVTG,,,,,,,,,N*30

$GPGGA,,,,,,0,00,99.99,,,,,,*48

$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30

$GPGSV,1,1,00*79

$GPGLL,,,,,,V,N*64

$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

Here is the full unedited output after 40 mins
https://drive.google.com/file/d/148W_6shE0U2lprimApvtvG1i3Vf2-Izx/view?usp=sharing
edit:- i also connected the tx pin to the rx and vice versa and used a resistor as told by an tutorial on the tx pin from the arduino or the rx pin of the board. it is also sending many gptxt messages which some say on other forums are usally send when some error occurs or the board restarts. idk why it is coming on my board.

someone on ublox portal recommended me to connect the boards vcc to 5v's and when i did that, it stopped rebooting, and after 20 mins got a lock, thanks for your help.
the guy on ublox portal

Post a photo of the board and a link of where you bought it so that we can point out that 5V is needed.
The reboot symptom is usually caused by an inadequate voltage source --- when the 6m starts, current draw is low, when it finishes initial startup, it goes to work looking for sats and current draw jumps up. The higher current draw on a poor power source causes supply voltage to drop too.low which then causes the 6m to reset and restart and will happily repeat the cycle forever.
Use a good DVM or oscilloscope to verify the inadequate voltage source.

after connecting the board to 5v supply the problem seemed to be fixed


Getting sensor data wirelessly from arduino to PC I am working on a project that involves sending motion sensing data wirelessly from an arduino to computer. Sensor readings have to be transmitted continuously (say every mili second). I am not sure if Xbee is my bet. I came across this link
which suggest s that there should be atleast 10 ms delay between packets if you're using xbees.

What are your experiences with xbees? I don't want to waste money.

Xbee costs about 1000INR. They are really expensive. You should buy HC-05 module, which costs about 320INR.
You can easily interface them with Bluetooth of your Laptop using Processing Application.

You can even use ESP8266 ESP-01 Wireless Module. They Cost about 3$.
Wireless module gets connected with your router. this tutorial will help you to start. You can by this module from here.

nRF24l01+ modules can not be interfaced with Laptop...


How to make a smooth serial print? I have a code which make some calculations using sensor values and provide two comma separated values.

float x;// initialization
float y;// initialization
//some calculations here using sensor values
Serial.print(x);Serial.print(",");Serial.print(y);

but the issue is due to some unstable situations of the sensor readings, I don't receive sensor data in same time intervals (overall delay is 1 second). I send these values to my Android device through a Bluetooth connection. At that stage, android device cannot separate two values due to lack of smoothness of the Serial.print(). Is there any way to make it smooth (like saving to a buffer before serial print or something) ?

I bet your problem has nothing to do with “smoothness” (whatever that
means), but is entirely due to lack of message framing. The serial and
bluetooth links do not transmit messages: they transmit only a stream of
bytes, with no built-in notion of where a message ends and the next one
starts. Relying on the timing of the received bytes to tell the messages
apart is very unwise. You should instead use some kind of delimiter for
your messages.

For text-based transmissions like yours, the most natural choice is to
send a line terminator at the end of each message. Typically a CR+LF
pair. The Serial object has the println() methods designed precisely
for this purpose: they send their arguments immediately followed by
CRLF:

Serial.print(x); Serial.print(","); Serial.println(y);

At the receiving end, you have to buffer all the incoming characters
until you see the line termination. Then you know the message is
complete and you can process it.


If statement behaves erratically I connected the output from an encoder motor to int0. this is used to increment a counter at every pulse. in the loop(), I check this counter and stops the motor if it is above certain value. But this "if statement" works erratically. The while loop should break at 380, but sometimes it breaks at 256.

Serial.print(cnt);
cnt=0;
Serial.print("  ");
Serial.print(cnt);
motor1_up(255);
motor2_up(255);
while(1)
{
    if(cnt>380)
    {
        Serial.print(" break ");
        Serial.print(cnt);
        break;
    }
}
motor1_down(255);
motor2_down(255);
Serial.print("  ");
delay(40);
Serial.println(cnt);
motor1_down(0);
motor2_down(0);
delay(2000);

Here is the serial output

 1  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389
 396  0 break 381  389
 396  0 break 256  264
 270  0 break 381  389
 397  0 break 381  390
 396  0 break 381  389
 397  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389

Not only must cnt variable be declared volatile, but accessing it from the main loop must also be protected because:

it can be modified by an ISR
it is longer than 1 byte

In AVR architecture (8-bits), read/write operations on bytes are guaranteed to be atomic, i.e. no function can access a byte while it is read/written by an ISR.

However, operations on types larger than bytes are not atomic!

This means that reading e.g. an int variable from your main loop might be interrupted in the middle of the operation (only 1 byte read) by an ISR that could modify the value (both bytes this time); then when the ISR is finished the main loop would resume reading the second byte -modified by the ISR- of the variable, while keeping the first original byte -not modified by the ISR.

I would advise you to write a pair of functions to read and write cnt in a protected way, i.e. with interrupts disabled:

volatile int cnt;

void set_cnt(int val) {
    uint8_t status = SREG;
    cli();
    cnt = val;
    SREG = status;
}

int get_cnt() {
    uint8_t status = SREG;
    cli();
    int val = cnt;
    SREG = status;
    return val;
}

What those functions do are:

get the current status of exceptions (from SREG register)
disable exceptions with cli()
access cnt without any risk of it being accessed concurrently
restore initial status of exceptions (to SREG register)

Everywhere in your code (except in code called from an ISR where it is not necessary), you must then call these functions to access cnt variable.


Arduino Disconnects after router password changes I am working with arduino Uno R3 connected with EPS8266(http://www.amazon.in/ESP8266-Serial-Wireless-Transceiver-Module/dp/B00O34AGSU?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=858e5035-7713-403a-942e-487a0fe24800). After router password is changed, it should be re programmed with new password. Is there any another way not to do so repeatedly. I managed 2 SSID for router which one have always unique password. But I think this is not a solution. Is there any technique or idea that says only for particular mac address, the SSID will be opened.

Routers have multiple "passwords".  I assume you are talking about your wireless encryption key (i.e. WPA/WPA2 key).  When the encryption key is changed, you are correct: you have to re-program the ESP8266 with the new key, because it can't learn this information on its own.  If this key were broadcast, then your network would not be secure as everyone would be informed of the encryption key.

Why is the key changing?  Is there really a need to change the encryption key often?

MAC addresses can be spoofed, so permitting a specific MAC address to "always connect" is not secure.


I need help creating a code that moves a DC motor CW or CCW based off of 2 different buttons I know I can make the motor move backwards and forwards with buttons but I don't want it to move at full speed. I want it to increment in very small amounts to where it can be adjusted very small amounts at a time. I should also be able to hold the button so it moves continuously. I also have a motor with an encoder on it. Maybe there is a way to use the numbers on the encoder to increment? so press the CW button and now the motor wants to move till the encoder reaches +10 from where it was at? I understand what I want to do, just need help getting there. Thanks
HERE IS THE CODE I FIGURED OUT THAT MAKES MY DC MOTOR INCREMENT CW AND CCW

#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

  //delay(100);

}

To formulate the comments into an answer:
In principle it is of course possible to put an encoder onto a DC motor shaft and then drive the motor, until you reach the desired position. But you won't get good precision or accuracy with this. You wrote

till the encoder reaches +10 from where it was at

Since most encoders have more than 10 tics per full rotation (you didn't specifiy how much yours has), this can mean  rotating only a fraction of a full rotation. Let's assume, that the encoder has 40 tics per full rotation. With 10 tics you have a quarter rotation. It seems you want precision in the range of about 1 tic.
DC motors are made for spinning relatively fast. They don't give you control over the position with steps. They mostly have very few coil/magnet combinations (for example just 2 coils, which are switched internally). Thus you have just an inert motor shaft, which is driven by the motor. It will need time to accelerate and to decelerate. With most motors, you may even get a half or full rotation, when you wanted only a quarter rotation (the 10 tics). Calculating the correct timings to get it any better will be not easy for relatively small reward. DC motors are not made for rotations below a small number of full rotations.
You could tackle that problem by using a geared DC motor. The shaft after the gears will run slower and thus have the explained problem not so badly. Then you have to live with the smaller speed.
Or you could go a more proper way and just use a stepper motor, which is made for small steps in the range of sub-full-rotation. It is a bit more difficult to drive (also depending on the driver circuit), but it gives you the position control, that you want. And to rotate continuously: A continuous rotation on a stepper motor is nothing else but step after step taken in fast succession (much like running is a fast succession of steps with your feet).

Note: The stepper motor does not have a feedback like an encoder on it. The motor driver will just drive the coils to step the motor. If the motor is stalled or if it is overloaded, you might loose some steps (meaning that the coils are driven for the steps, but the motor doesn't actually move). You could sense that with an additional encoder on the motor shaft. But in most cases that is not necessary. If you just make sure, that the motor is not overloaded at any time, you will be fine. Or you might not worry about some steps being lost sometimes, if the overall precision is good enough. That is your decision.


How to store u-blox coordinates (lat, lng) values in doubles? [TinyGps++] I use a u-blox gps with my arduino. I can successfully write out the value of a coordinate (lat, lng) like this: Serial.println (gps.location.lat(), 8); but when I try to store the value with all the decimals it returns 8.00 instead of the correct coordinate + all of the 8 decimals.

This is my code:

#include "TinyGPS++.h"
#include <SoftwareSerial.h>
SoftwareSerial gpsconnection (4,3);
TinyGPSPlus gps;

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

void loop()
{
 while (gpsconnection.available())
 {
   gps.encode(gpsconnection.read());
 }

 //this works and returns 8 decimals
 Serial.println (gps.location.lat(), 8);
 Serial.println (gps.location.lng(), 8);

 //but if i try to store it like this:
 double latcord = (gps.location.lat(), 8);
 double lngcord = (gps.location.lng(), 8);

 //it returns 8.00 on both the "latcord" and "lngcord" which is the wrong coordinate and also it doesnt return 8 decimals
 Serial.println (latcord);
 Serial.println (lngcord);

 //if i try to convert the value to a string and then back to a double like this:
 double lat = gps.location.lat();
 String msgLat =  String(lat, 8);

 double thelat = atof(msgLat.c_str());

 //with this i get the correct first two numbers out but only 2 decimals after, not 8 decimals as it should be.
 Serial.println (thelat);

}

You forgot the , 8 from your println that specifies that it should print 8 decimal places. Instead you seem to have added it to the end of an assignment which makes absolutely no sense whatsoever.

double latcord = gps.location.lat();
double lngcord = gps.location.lng();

Serial.println(latcord, 8);
Serial.println(lngcord, 8);


Arduino Object Array initialization I just got an Idea of trying to code rain simulation with arduino and Adafruit OLED display. When I finished it was quite messy code so I thought That maybe doing it Object Oriented would help. This code is just a sketch that MAYBE works. The thing is that I need to create an array of objects(drops) and then display them. I have tried to display just one drop and it does not seem to do anything, even Serial wont print the pos_y. I have never wrote an Arduino code with objects so I just made a quick research and tried. here is the code:

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

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

class Drop{
  private:
  int pos_x = random(0, 128);
  int pos_y = random(-5, -20);
  int len = random(3, 7);
  int speed = random(6, 13);
public:
 void fall()
{
 display.drawFastVLine(pos_x, pos_y, len, 1);
 pos_y = pos_y + speed;
 delay(5);
 Serial.println(pos_y);
 display.display();
 display.clearDisplay();
}

};

Drop* drop = new Drop[50];

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

void loop() {
  drop[1].fall();
}

I will appreciate any suggestion or solution, spent almost entire day doing this "simple thing"..

The code works without the display commands. A problem could be that you start with negative pos_y and use it as parameter for drawFastVLine.

Function random returns first parameter if it is a larger value then the second parameter. random(-5, -20) always returns -5.

To have more random random values, you should call randomSeed in setup().

And you can use global array Drop drop[50];.