Can I corrupt my Arduino if it's unplugged during an upload? When messing around with code and uploading a sketch to my Arduino board, I almost accidentally pulled out the USB cord. Everything is fine, but then I started thinking what would've happened if I had pulled it out.

How safe is avrdude? Could it damage or brick the board? I'd imagine that you would just have to upload code to it again... but what would happen before you upload the new code? I've seen something about how you can always upload new code if the bootloader is intact, but I would imagine that there would be some problems. If this were to happen, should I unplug everything connected in case Arduino writes a HIGH to an input (or similar) that would damage the component?

AVRDUDE does not actually perform the write, it merely directs it. The actual writes are performed either by the bootloader or by the ISP firmware/hardware within the MCU itself.

With the bootloader it depends on how itself is coded, but at worst it would finish off the flash byte or page or EEPROM page zero- or one-filled and then fail to communicate further with AVRDUDE, aborting programming.

With ISP, the page write command would never be received and the programming would be aborted at the last full page. Fuse bytes are done singly and so programming a single fuse can be viewed as an atomic operation.

In either case, a chip erase operation should reset the MCU to a known working state, fuse changes excepted.


Individually control ~200 LEDs I am planning to build a LED polar clock, so it will need about 181 LEDs (12 Month, 31 Day, 7 Day-of-week, 12 Hour, 60 Minute, 59 Second) and I need to control each one individually. I will be buying everything from scratch so I ask for help on:

Which arduino to use
How to make it keep time
How to control the LEDs

The LEDs need to stay on once they're lit, e.g. at 5 o'clock, the 1-5 LEDs would be on.
This is why I don't know that multiplexing or charlieplexing will work, as I read that it is better if the LEDs wont be remaining on/only a few are on. The most that could be on is 179 (Friday, December 31, 11:59:59 [Won't happen until 2021]).

Thanks in advance.

Instead of a multiplexer you can use a "shift register"; the difference is that it keep the last state of the pin, while the multiplexer goes unconnected (and this is because you need at least 30fps, and even so you'll get low light as you are PWMing the leds).
This is why shift register are also called "led driver".

Official tutorial can be found here http://arduino.cc/en/Tutorial/LEDDriver


How to change the resolution of DS18B20? I'm using DS18B20 sensor with this library, the 750ms delay is causing problem in timer part of my code. the code below is from DallasTemperature.cpp:

// returns number of milliseconds to wait till conversion is complete (based on IC datasheet)
int16_t DallasTemperature::millisToWaitForConversion(uint8_t bitResolution) {

    switch (bitResolution) {
    case 9:
        return 94;
    case 10:
        return 188;
    case 11:
        return 375;
    default:
        return 750;
    }

I'm reading the temperature like this:

#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS A0
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {}

void loop () {
    float currentTemp = sensors.getTempCByIndex(0);
    sensors.requestTemperatures();
}

sensor is not connected in parasite mode, and there is only one sensor.

How can i change the resolution from 12 to 9 bit?

Simple:

sensors.setResolution(9);

It normally defaults to 9, but then probes the connected device to find the maximum resolution it supports and sets it to that. This would normally be done in sensors.begin() which you omitted from your snippet above. If you don't have that it will be on 9 bit anyway, and also the bus probably won't work regardless.


Using the MIDI library in my own library Error message :

"error: invalid declarator before 'MIDI'
         MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
                                                       ^
Plusieurs bibliothèque trouvées pour "libMidi.h"
/home/due32/Arduino/libraries/MIDI/midi_Defs.h:170:31: note: in definition of macro 'MIDI_CREATE_INSTANCE'
     midi::MidiInterface<Type> Name((Type&)SerialPort);"

libMidi.h

#ifndef libMidi_h
#define libMidi_h

#include <Arduino.h>
#include <MIDI.h>

    void midiSetup();
    void pmbMIDI();

//  void MIDI_CREATE_DEFAULT_INSTANCE(); //doesn't work

#endif

libMidi.cpp

#include "libMidi.h"
#include <MIDI.h>

void midiSetup(){

//midi::MidiInterface<Type> Name((Type&)SerialPort);

        void MIDI_CREATE_DEFAULT_INSTANCE();
        void MIDI.begin(MIDI_CHANNEL_OMNI);
}

void pmbMIDI(){
    if (MIDI.getType() == 144){
        digitalWrite(13, 1);}

    if (MIDI.getType() == 128){
        digitalWrite(13, 0);}
}

Thank you by advance

void MIDI_CREATE_DEFAULT_INSTANCE();

This line should not be placed inside a function, because it is a forward function declaration.

However, I think there are more problems in your code.

My wild guess is to improve the following lines:

Uncomment line that doesn't work

Change

MIDI_CREATE_DEFAULT_INSTANCE();

to

MIDI_CREATE_DEFAULT_INSTANCE();

and place it outside a function.

Remove the word void  in the following lines

void midiSetup();
void pmbMIDI();

And also align the { and }

void MIDI.begin(MIDI_CHANNEL_OMNI);

So it's a function call.

Other improvements is to remove spaces or tabs  in

    void midiSetup();
    void pmbMIDI();

Also align { and } in

if (MIDI.getType() == 144){
    digitalWrite(13, 1);}

if (MIDI.getType() == 128){
    digitalWrite(13, 0);}


How can I tell the resistance of an internal pull-up resistor? I have a SparkFun ESP8266 Thing Dev board, to which I want to perform a digitalRead() on one of the GPIO ports. I'm using D15, and I'm configuring it for input like this

pinMode(15, INPUT_PULLUP);

It does seem to work as intended, and I am able to pull it down by connecting it to ground via a 4.7kΩ resistor.

But how do I know what the actual "correct" resistor would be? I can't find any specs for the internal pullup resistor online. On a related note, I first tried using D0, but it didn't seem to have an internal pullup resistor, since even using INPUT_PULLUP didn't turn it on.

Perhaps there are specs online and I'm just not able to find them, but is there any other way (measuring?) to find out which pins will work with INPUT_PULLUP and if so, what their internal resistance is?

io 0 and io 15 are with io 2 boot configuration pins of the esp8266. esp8266 dev boards have external pull-up on io 0 and io 2 and pull-down on io 15.


Why does this button have a connection to ground? I am testing this basic button example  from the Arduino tutorial page.

This circuit lets power flow to pin 2 when the button is pressed. When the button is not pressed, the power goes through the resistor to ground, but my question is: why would you even need the connection to ground?

Can't you have power flow from 5V to pin2 or just have NO connection at all when the button is not pressed?

That resistor is called a pull-down resistor. It's there to make sure pin 2 read low when the button isn't pressed. If you don't put it there pin 2 is left 'floating', and it could erroneously read a high value. Google it for more info.

If you want to simplify you circuit you could instead use a pull-up resistor, and connect the button to ground instead of 5v. The ATMega chip on the arduino has these pull-up resistors build into the chip itself, so you don't need to add one to the breadboard. Just not that the input values will be reversed. So pin2 will read LOW when the button is pressed, and HIGH when not. To activate the internal pull-up use pinMode(2, INPUT_PULLUP)


Update variable using buttons I made a part of code to change the temperature limit for alarm system. On warm days user have to change the temperature limit with buttons and OLED display.

The question is: How can the variable templimit keep its last setup value after many restarts(for many reasons)?

This is the code:

const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit; // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.print("Update temperature limit if not wait 10 sec time out");
  updatevalue();
  Serial.print("Done");

}

void loop() {
// do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  timenow = millis();
  // this loop is just for 10 sec time out
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) {
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    if (timepassed >= 10000)
    return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }
  templimit = buttonPushCounter; // update templimit value

}

An Arduino Uno has 512 bytes of non-volitile memory called EEPROM or Electrically Erasable Programmable Read Only Memory. Other Arduino platforms might have more. Accessing it is complex.  Fortunately there is an Arduino EEPROM library already written for you.  Your value is stored in a type int so I would use the read() and update() methods in the EEPROM library.  The read is self explanatory.  But the update, unlike the write, only runs if what is in the EEPROM location is different from what you want to write.  In this way we save the EEPROM a little bit of ware and tare.  As EEPROMs usually have a finite number of write cycles until they start failing.  Which usually is in the tens of thousands.


Flash a hex file to an MCU/Arduino over the air? I have a processor AT328 , Arduino bootloaded, and a Bluetooth on the serial lines Tx,Rx .

I would like to program the chip over Bluetooth, not using a computer or IDE, but mobile phone with my own Hex uploader.

So, if the hex file was just a huge text that you have to send, i would obviously just send it and thats it, as I understand there is a mechanism ?

Question : How exactly a Hex file is sent over serial to program the chip ? is it like any other text file? is there any mechanism I have to write? specific baud rate? is there any article about this ?

Basically, this is much more involved than it might appear on the surface. If you haven't already, I would make sure that I was comfortable with finding things in the datasheet (and it's a really good datasheet, at that). If you're still up for it, read on.

Bootloader

The way a bootloader works on the ATmega328 is that the memory on the chip is self-modifying. This means you can have a piece of code on the chip that modifies memory on the rest of the chip. A bootloader is one such piece of code that runs when the chip first starts up, and checks to see if there's code to be loaded. If there is, it writes that code to the rest of the memory, and then executes it. See section 12.2 of the datasheet.

The way you would program an actual bootloader is described in detail in section 30 "BTLDR - Boot Loader support". I haven't programmed a bootloader before, so you're on your own here, but there are plenty of resources to guide you. In fact, the datasheet has example code in there for it.

(Note that you must program your chip normally at least once, to put the bootloader on it.)

One thing to note is that bootloaders should be small. You don't want bootloaders to take up a lot of your memory, since they only run once on boot and are really just a convenience feature. There are competitions for writing the smallest/most efficient bootloader, and you'll almost certainly want to write your bootloader in assembly. Notice that the only example code given in the datasheet is in assembly. Which brings me to my next point:

Bluetooth

Bluetooth is very annoying to program for. You have to set up different profiles, or do GATT stuff if your module is actually BLE/"Smart" instead of classic bluetooth, etc. However, I'm assuming from your post that you just have one of those serial modules you can find on eBay for dirt cheap. Before I go on, I want to make this very clear: It is non-trivial to set up. It will take up lots of precious code space on your microcontroller that you would want to use on your actual program. Remember how bootloaders are written in assembly? Writing a bluetooth interface in assembly will probably take a while.

As for how your bluetooth module works; it is basically a serial port, but over-the-air. This means the bluetooth interface that you write would need to bit-bang everything if you don't use the built-in USART (say you need those pins for your actual program), and if you do use the built-in USART, setting that up will take even more time. (For a guide on how to setup the USART, see section 24 of the aforementioned datasheet. See? It's really handy.)

Once you actually have bluetooth working, you can do whatever you want. Since you write the bootloader, you can read data from your bluetooth serial link however you fancy. As long as you know what you're sending, all you have to do is read it back accordingly.

Bonus: Flashing

You are correct that a .hex file is just a huge text file that you send to the chip. However, the way the ATmega is actually programmed is not simply using the serial port; instead, it's a slightly extended SPI protocol. (If you don't know what SPI is, you really shouldn't be doing this. If you're curious, Sparkfun has a nice tutorial on SPI.) This is called ICSP, or "in-circuit serial programming". The way to do this for AVRs is explained in an application note.

Of course, you cannot replicate this with just a bluetooth module. Instead, you would need a co-processor to program your chip for you, and read the data to-be-programmed from your bluetooth module.

TL;DR: This is probably not worth it. If you're planning on doing this, it will take significant resources, and you might even need a better chip to get anything done. You almost certainly should just buy an ESP8266 / ESP32 instead.


Failing to write to SD card using SD.h Using a knockoff Arduino Nano (pinout seems to be the same), I would like to record data to an external SD card. I have everything hooked up (correctly I think) but I continue to fail to initialize the card using SD.begin().

Here's a snippet of code that I'm running to do this:

//Wire and MS5803_I2C libraries for communicating with the pressure sensor.

#include <Wire.h>
#include <SparkFun_MS5803_I2C.h>
// For the SD card reader.
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup(void) {
  Serial.begin(9600); // Set baud rate.
  pinMode(10, OUTPUT); // Set data output pin for the SD card reader.
  digitalWrite(10, HIGH);
 // see if the card is present and can be initialized:
 if (!SD.begin(10)) {
   Serial.println("Card failed, or not present");
   // don't do anything more:
   return;
 }
 Serial.println("card initialized.");
  delay(500);  // Wait half a second before continuing.
}

void loop(void) {
  Serial.println("Hello Library!");
  delay(100000);
}

Here's the Nano pinout:

And a picture of the circuit.

The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?

When your Nano board is 5V, you need a SD module with a level shifter for the signals.

To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.


Can we use UART COMMUNICATION with MCP23017? I am using MCP23017 as a GPIO expander with Arduino in my project. I have too many serial devices and no pins left on Arduino for UART communication.
I am wondering if I can use this MCP23017 GPIO expander pins for UART communication or not?

I can think of one way.
In theory you could use the GPIO pins of the mcp23017 to control a couple of 2-way multiplexers. With these multiplexers you could split your Rx/Tx pins to more than one serial bus.
May it be obvious that you cannot used the split busses at the same time. So depending on your specific use-case this may or may not be a solution.


Why my Arduino output active on reset using relay module? I have a problem with relay module when I reset the arduino all the relay go active i.e all the light turned on by itself which is  a drawback of my project .Arduino pin output is negative by default i.e on reset after sending command through hc-06 it becomes positive i.e relay  become inactive. In the other hand when I use LED instead of relay module it Works fine I used One Pin ground and other to my output with 330ohm resistor. Any helping word in this regard will be appreciated greatly.
Sorry for my poor English.

The relays may be low-level triggered relays so to turn them on you need to set the pin connected to the relay to digital LOW and to turn them off you need to set the pin to digital HIGH; Please verify this first whenever you get a new relay and there is no mention on it if its a low-level triggered relay;


How can I determine how many bytes an I2C master read from my Arduino acting as I2C slave? I have an Atmega328 programmed using the Arduino software and libraries (but is standalone on on a board in the TSOP package) without bootloader and with ISP programming). I am using the Wire library to act as an I2C peripheral, where I implement (and register) the requestEvent and receiveEvent callbacks.

Is it possible to determine, either during the requestEvent callback or after it at some point, how many bytes were read by the master before it sent a NACK?

You can't.

The master will have to inform the slave how many bytes to transfer, or the master will have to query the slave how many bytes there are to receive.


Arduino servo acts weird with photocell (lightsensor) I have a weird thing with my servo, I really dont know what is wrong with my code, I tried everything. Either it is my connection on arduino or my code. Please help me guys, this is my code.

#include <Servo.h>

int servoPin = 9;
Servo servo;
int angle = 0;
int photocellPin = 0;

void setup() {
  servo.attach(servoPin);
}

void loop() {
  int reading = analogRead(photocellPin);
  Serial.print("Reading = ");
  Serial.println(photocellPin);
  int newAngle = reading / 2;
  servo.write(newAngle);
  delay(80);
}

Servos accept a signal from 0 to 180, with 90 being the center point on the servo. analogRead() will output a number from 0 to 1023. The arduino "map" function makes a conversion easy to do. just replace

int newAngle = reading / 2;

with

int newAngle = map(reading, 0, 1023, 0, 180);

you can read more about the map function here: http://arduino.cc/en/reference/map

It is hard to tell from the picture that everything else is wired correctly, but this should fix up your code.


In multidimensional arrays, can you use variable arrays or their names instead of the actual data? Referring to this thread
How to declare and use "Variabled arrays" inside arrays
Example
byte array[2][4] = { {1,2,3,4}, {5,6,7,8} };
Serial.println(array[0][2]); is equal to '3'.

Instead of using {1, 2, 3, 4} and {5, 6, 7, 8} I want to be able to declare separate arrays for each of them and just put the name.
Another big issue is putting arrays of different sizes for each entry and it would be wrong to do so. Is this really not possible? Do I have to use some other concept instead if I want to have an array that contains entries of arrays that have different sizes? I heard about pointers but not familiar with that.
Example,
byte arrayX[3] = {1, 2, 3}
byte arrayY[4] = {5, 6, 7, 8}

byte array[2][4] = { arrayX , arrayY };

Take note that the code was not taken from the link I mentioned, I just used the same array names. Also I changed arrayX from the link to 3 entries because I want to emphasize the part of my question if it is possible if arrays have different sizes and you would just use the biggest size?
Now I think this is wrong and I haven't tested it currently but I want to ask if there is a solution that makes use of what I have mentioned? The site I linked to gave a solution which feels very redundant in terms of declaration and I would not want that. This is the solution mentioned there.
byte arrayZ[2][4] = {
  {arrayX[0],arrayX[1],arrayX[2],arrayX[3]},
  {arrayY[0],arrayY[1],arrayY[2],arrayY[3]}
};

The issue I had when searching the internet is the same as the link. "Surfed on the internet to find a bunch of examples but the only difference is that they don't use arrays that have been declared to have a name inside array."

Two-dimensional arrays come in two "flavours". Actually, multi-dimensional arrays are possible in any combination of these.

All elements in a rectangular grid, at least from the abstract view of the programming language;
A one-dimensional array of one-dimensional arrays.

If you declare:
byte array[n][m];

then you have reserved space for "n times m" bytes. From the programmer's view it is a rectangular grid, actually all bytes are in sequence in a one-dimensional array. This is because the memory of our computers are commonly organized as a big one-dimensional array of bytes. The compiler generates the correct calculation for the offset into this array, multiplying one index with the size of the width (or length, depending on your mental model) and adding the other index.
You can initialize such an array with the nested set of curly braces like this:
byte array[n][m] = {
    { /* ... */ },
    /* ... */
};

But you cannot initialize it as you show.
Otherwise, if you declare
byte* array[n];

then you have reseved space for "n" pointers to bytes, that is a one-dimensional array of pointers. Each of these pointers can point to a different or the same one-dimensional array of bytes, or to no array at all if it's nullptr.
Now you can set up the array as you like:
byte arrayX[m1] = { /* ... */ };
byte arrayY[m2] = { /* ... */ };

byte* array[n] = { arrayX, arrayY, /* ... */ };

The arrays arrayX and arrayY (and any further) don't need to have the same length. Each can have its own length. But beware, you need to trace the length somehow to avoid out-of-bounds accesses. And of course, you need to check or be sure that a pointer is not null before dereferencing it.
In both cases you can access a single element with:
byte element = array[i][j];
array[k][l] = 23;

This is because the syntax with the brackets is equivalent to the dereferencing operator:
x[y] == *(x + y)

Note 1: Since Arduinos are programmed in C++, there is another option. You can use references instead of pointers. Because it is really hard to create a null reference, some see it as a safety measure against null pointers.
Note 2: Again, since Arduinos are programmed in C++, you can implement an own class that provides the operator[]. With this option you can do any magical stuff, but it might break the user's expectation. Be careful if you go that route.


Did I just brick my ATMEGA 2560? I bought an ATMEGA2560 on eBay and programmed it with Arduino IDE 1.6.9 using the USB cable, and the LED blinked as expected - All well and good.

Now I wanted to program the mega from my UNO as follows:

Uploaded ArduinoISP to the UNO
Changed the Board to Mega2560 and changed the Programmer to Arduio as ISP
Connected the two ICPS sockets with a 6 wire cable, where pin 5 on the UNO ICPS is cut and instead connected to D10 on the UNO
Upload the Blink sketch: IDE says Uploading for a minute, then some errors:

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

5) Upload Using Programmer: Activity on the UNO (RX/TX) and the LED on the mega lights constantly - And I can no longer program the mega using the IDE

Any pointers to what I did wrong and how to fix it?
Best regards

Ah, the problem seems to be in the IDE - Something with the fuses when programming the mega (I won't even pretend to understand that yet).
I upgraded to 1.6.12 and everything works like a charm.

Best regards
Stefan


How can I connect to an Arduino using WiFi? I'm working on building a solar powered, Arduino based weather station. The weather station consists of a temperature sensor and a photoresistor, and I plan to add an anemometer in the future. I would like to connect the weather station to my wireless network so that I can retrieve the sensor data from my computer without having to run wires (I live in a rental).

What are the different options for connecting the Arduino to WiFi? I've looked at ethernet shields, WiFi shields, and something called Xbee, but I don't understand what each of them are for.

I also have a wireless home router that I could use. Is it possible to connect my Arduino Uno to the router via the routers ethernet or USB port and then receive data from and send commands to the Arduino wirelessly over my home network? If so, how would this be accomplished?

I currently have a bare Arduino Uno.

You have a few options for connecting your Arduino to the network/Internet.

Ethernet

Something like the Arduino Ethernet Shield allows you to plug in an Ethernet cable from the wall or router into your Arduino. Obviously, the main limitation is that your device is now tethered by the cable. For outdoor use, I wouldn't do this.

WiFi

The Arduino WiFi Shield allows you to connect to your home WiFi network. This is just like the Ethernet except its now wireless.

The ESP8266 is a cheaper alternative that, with the default firmware, has the same functionality as the WiFi Shield. Be careful that you power it with 3.3V and not 5V as the rest of the Arduino. It also uses 3.3V logic levels so don't connect the Arduino's TX pin directly to the ESP's RX pin; use a voltage divider.

RF

If you have a lot of sensors or other devices that need to communicate with each other, the best option is usually an RF module. You have many options here, XBee being one of them. Check out the Sparkfun XBee Buying Guide to look at all the options available. And that's just XBee. There are many other wireless options available, at all sorts of prices.

The thing with RF is that none of these will connect to the Internet. You will have all your devices communicate with each other or a base station, which will then be connected to the network by either a WiFi or Ethernet module.

Wireless Router Serial

Depending on what kind of wireless router you use, you can have the Arduino communicate directly with it and use that as your connection to a network.

Arduino - Cheap wifi connectivity
Converting your Ethernet Shield to a wireless shield


Turn on each of the LEDs in order, by setting the cycle delay to 100 milliseconds I have a tutorial to finish and I don't know the code I have to use to make all (4 LEDs) to turn on in order. So this is my code and my simulation. Thanks in advance!

My Code:

void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100); // Wait for 100 millisecond(s)

  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(9, LOW);
  digitalWrite(6, LOW);
  delay(100); // Wait for 100 millisecond(s)
}

EDITED:
I have to follow this one. I guess my simulator is correct.

I see in your second diagram that you are controlling the ground side of the LEDs. digitalWrite(PinNumber, HIGH) will turn an LED OFF, digitalWrite(PinNumber, LOW) will turn an LED ON. Using delay() in a sketch should be avoided.

void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
}

void loop(){
  digitalWrite(13, LOW);
  delay(100);
  digitalWrite(12, LOW);
  delay(100);
  digitalWrite(9, LOW);
  delay(100);
  digitalWrite(6, LOW);
  delay(100);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100);
}


connecting multiple keypads My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr_1_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.

The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.

So my questions:-

1/ Is there a simple pll to serial converter that I should be using to interface the keypads?

2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.

3/ Are there simple serial versions of the classic membrane keypad.

As far as I know, you can connect multiple keypads of this type to a single set of 8 pins.  However, it seems like a lot of wire needs to be strung to get this to work, for each switch, 8 wires for the keypad, and two, or more, for power control.

Were I to do this project.  I would likely handle each switch independently, embedding a Pro Mini in each switch box along with an HC-12, or some such.  This means no wires are needed, any pad could control any switch, and expansion is much easier.

Of course, this is only what I would do, and you understand your own requirements far better than I.


Help to decode xbee S2 API packet I'm new at using Xbee and I would like to get some help on how to interpret API packets. Me setup consists of two arduino unos, two xbee S2, two xbee shields and a one magnetometer sensor HMC5883L.  The sensor is connected to the arduino via I2C and transmitting the data to the xbee (router) using serial communication. On the other side (coordinator) I'm reading and displaying the data on the serial monitor. I have read the data sheet of the xbee but I still can't figure how to interpret the packet. Here is a screen shot of the values that I'm getting on the serial monitor on the router and the corresponding packets on the coordinator's serial monitor.

There are four bytes that are changing each time so how can I translate them to an integer value. Any help would be greatly appreciated.

You have a bunch of "stuff", followed by the data you sent, followed finally by another bunch of "stuff".  I don't know what the "stuff" is, but I can see and decode your data easily enough.

I suspect you transmitted the data using .println(...).  That will send an ASCII representation of the data.

So to take the line: -196.88<CR><LF>, if we find the ASCII values and represent them as hexadecimal we have:

  2D,31,39,36,2E,38,38,D,A

Which I am sure you can find in one of those lines - maybe this one:

  0,15,90,0,13,A2,0,40,C1,A8,2E,98,8D,1,2D,31,39,36,2E,38,38,D,A,3B

So you have 14 bytes defining something interesting about the packet (I'm sure Google can tell you what - source and destination maybe, probably a packet length too), then your data, and finally what looks like it's probably a checksum.


Arduino and hard drive So in a laptop you have a CPU and a hard drive. The hard drive feeds data to the CPU and the CPU executes it. In Arduino you flash the CPU and the "hard drive" is built into it. Is it possible to have a hard drive or SD card feed data into the Arduino to be executed and then feed more data in and so on? If it is possible how is it done?

Is it possible to have a harddrive or sd card feed data into the Arduino to be executed and then feed more data in and so on. If it is possible how is it done?

A harddrive would be difficult to connect, but an SD card will work just fine.

You can write a sketch that reads data from an SD card. There is library support for both SD and FAT16/32 file systems.

Another interpretation of your question is; is it possible to load a sketch from an SD card. The answer is yes; there are a number of projects that have done that.

Cheers!


How do I know which is ground and power in Piezo? I have a piezoelectric sensor. Both pins are the same length. I have one like this: Piezo picture. On the Piezo it's written muRata and 01P. How do I know which do I send to the digital pins and which to the ground? I have an Arduino Uno.

On the one I have, the shorter pin is ground. I discovered that empirically - a scientific word for "I tried it the wrong way round the first time but the magic smoke stayed inside." Afterwards I inspected it more carefully, I found a '+' embossed in the top surface nearer one side. :-o


Connecting multiple boards to Arduino Uno r3 How can I connect the Arduino RFID RC 522 and SD card adapter to one Arduino Uno R3? As each library takes specific pins in Arduino for MOSI, MISO, CLK. So I have conflict in the pins, how can this be solved?

Short answer: yes, you can. No pin conflict, but you will need an extra SS pin for the second SPI device. [If you can, use the I2C version of your device.]

Unlike the I2C, the SPI bus uses separate lines for sending and receiving data, and it employs an additonal line (SS, SS1, SS2, ...) for selecting which slave device you are talking to. This adds additonal wires, but also eliminates needing different slave device addressses. So what this means is instead of specifying the address of the slave device, we simply address that slave device by turning on its SS pin. It's a lot more simple.

So, if you have two devices (RFID reader and SD Card Adapter), the conections looks like this:

The thing is, you need to use two Arduino pins for selecting the devices you want to talk to: one pin select the RFID reader; the other, the SD card.

Arduino has a fixed pin assignment for SPI comunications:

Because all devices share the MOSI, MISO, and SCLK lines, all commands sent from the master arrive at each slave device. The SS pin tells the slave whether it should ignore this data or respond to it. Importantly, this means that you must make sure to only have one SS pin LOW.

So you can see now how it's a minimum of four data lines that must be present in any SPI system. The MISO, MOSI, and SCLK signals are shared common with all slave devices. However, the SS chip cannot; it must be separate, because each slave device needs its own unique connection so that it alone can be addressed when the master device wants to communicate with it. So for each additional slave device that you add, you must have an additional line available on the master device for that slave device. So, using the above diagram as an example, if we have added a third slave device, we would have to add another SS3 data line to the master device and then connect to the SS pin of that third slave device.


Wiring BMP280 to Arduino Uno I bought a BMP280 and it looks like this:

How can I connect BMP280 to Arduino Uno?
I tried the following examples on the web, but they didn't work.
I used  this library, connecting the PINS in this way:

VCC  ->  3.3V
GND  ->  GND
SCL  -> 13
SDA  -> 12
SDO  -> 11

But the sensor did not initialize.

Eventually as reported here, it worked using this pinout:

VCC --> 3.3V
GND --> GND
SCK --> A5
SDI --> A4

And this code:

#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int hum_raw,temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;
 int8_t  dig_H1;
 int16_t dig_H2;
 int8_t  dig_H3;
 int16_t dig_H4;
 int16_t dig_H5;
 int8_t  dig_H6;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
    signed long int temp_cal;
    unsigned long int press_cal,hum_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    hum_cal = calibration_H(hum_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    hum_act = (double)hum_cal / 1024.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");

    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];
    dig_H1 = data[24];
    dig_H2 = (data[26]<< 8) | data[25];
    dig_H3 = data[27];
    dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
    dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); // Fix 2014/04/06
    dig_H6 = data[31];                                   // Fix 2014/04/06
}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    hum_raw  = (data[6] << 8) | data[7];
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

unsigned long int calibration_H(signed long int adc_H)
{
    signed long int v_x1;

    v_x1 = (t_fine - ((signed long int)76800));
    v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) +
              ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) *
              (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) *
              ((signed long int) dig_H2) + 8192) >> 14));
   v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
   v_x1 = (v_x1 < 0 ? 0 : v_x1);
   v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
   return (unsigned long int)(v_x1 >> 12);
}

Actually, BMP280 doesn't monitor relative humidity so you can delete the part related to the humidity control.

#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0;
    signed long int temp_cal;
    unsigned long int press_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.println(press_act);
    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];

}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}


How do I communicate with a sensor via an Arduino's RX/TX ports? I have a sensor that communicates via serial communication. CTi Sensors TILT-05. It transmits an ASCII string with data separated by commas. I want to be able to read the incoming ASCII data in the Arduino IDE's Serial Monitor in real time (the device is an accelerometer).

I am struggling to convey this in the code. Currently, I have the sensor's RX connected to an Arduino Uno's TX port (digital 1) and sensor TX-> Arduino RX (digital 0). The sensor is powered and grounded via the Arduino.

I have searched for serial communication methods but can't find any that seem to work. How can I receive and interpret the incoming data from the sensor?

You don't mention the sensor brand or a datasheet so this will be a very general answer to the problem.

Firstly, how you have the sensor connected now should just spool info into the Serial monitor of the Arduino IDE without any code on the Arduino.

What are the data speed and the exact way the Serial comes out from the sensor?

If you want to interpret the data as it is coming through you should use Software Serial as you can't relay info to the PC with an Arduino's RX TX lines connected to something else.

What you can do is below(Untested):

#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4); //RX TX

//these are char areay because its from Serial
char accel[3] = {'0'};
uint8_t place = 0;

// array to print in sync with the accelerometer values array
const char* SerialText[3] = {
   "\nX Axis: ",
   "\nY Axis: ",
   "\nZ Axis: ",
};

char inData = '0';
char separator = ','; // separator you described

void setup(){
//set to the normal baud, mines for the example
     Serial.begin(9600);

     mySer.begin(9600);

}//~ end setup

void loop(){

    if(mySer.available()){

     inData = mySer.read(); // get the value at the instance of the serial data being there

        if(inData != separator){
          accel[place] = inData;
          Serial.print(SerialText[place]); // print the current values identifier
          Serial.print(accel[place]); // print value
          place++; // increment for the next time
     }
   }

if(place >= 3) place = 0;
}//~ end loop

The above gives this output at the moment, with an input of $CSACC,-0156.4,-0226.3,+0981.2*49

X Axis: $
Y Axis: C
Z Axis: S
X Axis: A
Y Axis: C
Z Axis: C
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 1
Z Axis: 5
X Axis: 6
Y Axis: .
Z Axis: 4
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 2
Z Axis: 2
X Axis: 6
Y Axis: .
Z Axis: 3
X Axis: +
Y Axis: 0
Z Axis: 9
X Axis: 8
Y Axis: 1
Z Axis: .
X Axis: 2
Y Axis: *
Z Axis: 4
X Axis: 9
Y Axis:
Z Axis:
X Axis:

The code doesn't filter this the way it should but is a stepping stone. I will update it to do it properly when I have a chance.


Serial communication from Arduino to ESP8266 NodeMCU works, but from NodeMCU to Arduino isn't working My circuit connection is like: (I am following this tutorial)

Code uploaded to Arduino:

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);

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

void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["data1"] = 100;
  root["data2"] = 200;
  if(s.available()>0){
    root.printTo(s);
  }
}

Code uploaded to NodeMCU:

#include <SoftwareSerial.h>
int D5 = 14, D6 = 12;
SoftwareSerial s(D6,D5);
#include <ArduinoJson.h>

void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) continue;
}

void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.parseObject(s);
 if (root == JsonObject::invalid())
   return;

 Serial.println("JSON received and parsed");
 root.prettyPrintTo(Serial);
 Serial.print("Data 1 ");
 Serial.println("");
 int data1=root["data1"];
 Serial.print(data1);
 Serial.print("   Data 2 ");
 int data2=root["data2"];
 Serial.print(data2);
 Serial.println("");
 Serial.println("---------------------xxxxx--------------------");
}

Arduino sends JSON data and NodeMCU parses it as expected.

--------Till this everything is fine. ---------

But my requirement is vice versa. When I create JSON object in nodeMcu and try to parse in arduino, JSON not received.

This time I wrote this code in nodeMcu:

#include <SoftwareSerial.h>
#include <ArduinoJson.h>

int D5 = 14, D6 = 12;
SoftwareSerial s(D6,D5);

void setup() {
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) continue;
}

void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.createObject();
 root["data1"] = 100;
 root["data2"] = 200;
 if(s.available()>0){
   root.printTo(s);
 }
}

And code in Arduino:

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);

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

void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(s);
  if (root == JsonObject::invalid())
    return;

  Serial.println("JSON received and parsed");
  Serial.print("Data 1 : ");
  int data1=root["data1"];
  Serial.println(data1);
  Serial.print("Data 2 : ");
  int data2=root["data2"];
  Serial.println(data2);
  Serial.println("---------------------xxxxx--------------------");
 }

This code doesn't work. I don't receive anything in serial monitor of arduino.
The circuit connection remains the same as before.

Anymore information should I provide ? What modification do I need?

The problem may stem from Arudino boards being 5v logic pins while ESP boards are 3.3v logic pins.  3.3v high might not be enough for Arduino to see the data.


What pin is the external interrupt #0 for an arduino micro? I'm putting an MPU6050 on an arduino Micro but the interrupt is different than the arduino uno. The external interrupt #0 pin on an arduino uno is pin 2 but its not pin 2 on an arduino micro. So I'm trying to figure out what pin it is on an arduino micro


How do I use an ATMega 328 (not P) chip with an Arduino board? I just burned the bootloader on an ATMega328 chip and then I put in on the Arduino board. But when I try to upload a program to it, it says programmer not in sync and programmer not responding.

For burning the bootloader I changed the address in the avrconfig file and reset it back to the original one. Do I need to keep changing the address of the board?

How do I use this as a normal Arduino board, as I fried my original chip? Do I need to get an ATMega328P chip?

So I found the solution:

Here is the link to the method that worked for me. I think the reason my previous method didn't work was because of fuses for the clock as mentioned by Majenko in the comments.


Thanks for @Majenko.
I solved problem by upgrade firmware to 1137B15SIM900M64_ST.


Fastest way to test if two integers differ by 4 or equal to each other I'm searching for the fastest way to test if two integers are equal or differ by 4. The integers can be positive, negative and equal to zero. They are between -1000 and 1000 and are exclusively multiples of 4.

The simplest approach to test this should be this:

if(x == y || x - y == 4 || x - y == -4)
{
     //do something...
}

But since I want to do this 4 times inside of a interrupt sub routine I wanted to know if there is a faster way to do this.

If you need to do the same comparison 4 times you can just put the result into a boolean variable.

boolean b = (x == y || x - y == 4 || x - y == -4)

if( b )
{
     //do something...
}

If you are talking about optimizing the actual code, I shouldn't worry about it. The compiler is already pretty good at this. Here is the assembler code for it.

void test(int x, int y)
{
    if(x == y || x - y == 4 || x - y == -4)
  a8:   86 17           cp  r24, r22
  aa:   97 07           cpc r25, r23
  ac:   39 f0           breq    .+14        ; 0xbc <_Z4testii+0x14>
  ae:   86 1b           sub r24, r22
  b0:   97 0b           sbc r25, r23
  b2:   84 30           cpi r24, 0x04   ; 4
  b4:   91 05           cpc r25, r1
  b6:   11 f0           breq    .+4         ; 0xbc <_Z4testii+0x14>
  b8:   04 96           adiw    r24, 0x04   ; 4
  ba:   09 f4           brne    .+2         ; 0xbe <_Z4testii+0x16>
    {
        asm ("wdr");
  bc:   a8 95           wdr
  be:   08 95           ret

first it compare the two values x and y. Then is subtract y from x and compares it with 4. After that it gets the subtracted value from the previous step; adds 4; and check if it is 0.

EDIT

As to Dave X's suggestion; using if(abs(x-y)<=4)

void test(int x, int y)
{
    if(abs(x-y)<=4)
  a8:   86 1b           sub r24, r22
  aa:   97 0b           sbc r25, r23
  ac:   04 96           adiw    r24, 0x04   ; 4
  ae:   09 97           sbiw    r24, 0x09   ; 9
  b0:   08 f4           brcc    .+2         ; 0xb4 <_Z4testii+0xc>
    {
         asm("wdr");
  b2:   a8 95           wdr
  b4:   08 95           ret

So half the number of instructions needed. But as Paul said, this might not the fastest. This code always takes 5 instructions, while the previous code will only take 3 instructions if x==y. So if 90% of the time x==y, the previous code will be faster 90% of the time.

As to the assembler code, you can see how clever the compiler is. It first subtracts y from x. Then it adds 4. If -4 <= x-y < 0 the carry bit is set. Then it subtracts 9 (so it's like (x-y)-5 because of the previous +4). If 0<= x-y <= 4 the carry bit is set. It then check if the carry bits is set by either of the last to instructions. Pretty clever.


Pause between switching motor direction I'm new both to this forum and to Arduino. My robot is comprised of Arduino Uno with Arduino Motor Shield, 12V DC gear motor, and two limit switches. The robot supposed to move endlessly on rails between the two walls back-and-forth. I have it all wired up and am able to switch the directions of the motor's rotation by pushing the limit switches. However, I also want to have a pause between switching of directions:

... Robot moving forward ...

If front limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CCW

... Robot moving backwards ...

If rear limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CW

... Robot moving forward ...

Simple delay(2000) doesn't work as the limit switch remains pushed against the wall. I've been trying out millis() approach but the fact that limit switch remains pushed (HIGH) I can never produce a difference in time needed to trigger an action. I learned about State Machine but not sure if and how this could help my case?

Can anyone please help me in implementing a two second pause between the switching of the motor's direction?

Below is the code that momentarily switches the motor's direction when robot reaches the wall and limit switch is pushed.

int switchFront_State = 0;
int switchRear_State = 0;

const int ledYellow = 6;
const int ledGreen = 5;

const int switchFront = 4;
const int switchRear = 2;

const int motorDirection = 12;
const int motorBreak = 9;
const int motorPWM = 3;

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

  pinMode(switchFront, INPUT_PULLUP); // Front switch
  pinMode(switchRear, INPUT_PULLUP); // Rear switch

  pinMode(ledYellow, OUTPUT);
  pinMode(ledGreen, OUTPUT);

  // Setup Channel A
  pinMode(motorDirection, OUTPUT); // Motor direction pin
  pinMode(motorBreak, OUTPUT); // Motor break pin
  pinMode(motorPWM, OUTPUT); // Motor PWM pin
}

void runMotorBackward(){ // Motor moving backward
  digitalWrite(motorDirection, LOW);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void motorStop(){ // Stop motor
  digitalWrite(motorBreak, HIGH);
  digitalWrite(motorPWM, 0);
}

void runMotorForward(){ // Motor moving forward
  digitalWrite(motorDirection, HIGH);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void loop(){
  switchFront_State = digitalRead (switchFront);
  switchRear_State = digitalRead (switchRear);

  if (switchFront_State == HIGH){ // If front switch is pressed
    digitalWrite(ledYellow, HIGH); // Yellow LED
    motorStop();
    runMotorBackward();
    } else {
    digitalWrite(ledYellow, LOW);
  }

  if (switchRear_State == HIGH){ // If rear switch is pressed
    digitalWrite(ledGreen, HIGH); // Green LED
    motorStop();
    runMotorForward();
  } else {
    digitalWrite(ledGreen, LOW);
  }
}

I think the problem is because there is no delay time after your motor switch its direction, so the robot is stay on position where the switch is pressed. I don't know if this gonna work, but perhaps you can add delay after the direction changed.
But based on your code, I can't find a condition to run if no switch is pressed. For alternative, you can try this

int direction_state = 1; //state where robot moves forward

void loop(){

  /*notes that here I assume while robot moving forward,
   *the rear switch is impossible to pressed, so does while
   *robot moving backward, the front switch is impossible to
   *pressed.
   */

  while ((digitalRead (switchRear)==LOW) && (digitalRead (switchFront)==LOW))
  //no switch pressed, loop will break if any switch pressed
    {
      if (direction_state == 1) runMotorForward(); else
                                runMotorBackward();
    }

  //indicator which switch is pressed and start of 2s motor stops
  if (direction_state==1) digitalWrite(ledYellow,HIGH);
  else digitalWrite(ledGreen,HIGH);

  motorStop(); //stop the motor
  delay(2000);

  //indicator 2s motor stops finished
  if (direction_state==1) digitalWrite(ledYellow,LOW); //indicator front switch is pressed
  else digitalWrite(ledGreen,LOW);

  direction_state = -direction_state //toggle the state
  if (direction_state == 1) runMotorForward(); else
                            runMotorBackward();

  delay(2000);

}

Feel free to ask if it's not works


Can I use analogRead to read a digital pin? analogRead(nGPIO_max + lockerVal) were nGPIO_max(maximum digital pins in Arduino Uno is 13) and lockerval is 2. Which pin is it reading?

To answer the question in the title: No, you cannot use analogRead() to read a digital pin. A digital pin cannot behave as analog because it isn't connected to the ADC (Analog to Digital Converter).

If you call something equating to analogRead(15) on an Uno, then it should read pin A1. You can see the pin assignments in the board-specific versions of pins_arduino.h (shipped with the IDE):

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Using those raw numbers directly is generally not a good idea though as it obscures your code's meaning, and will potentially make it non-portable to other boards. It's better to call something like analogRead(A1).

It's worth noting that the Arduino library fudges the pin numbers slightly. Calling analogRead(1) has the same result as calling analogRead(A1). That means that even if you tried to use analogRead() on a digital pin, it might actually end up reading an analog pin instead. Alternatively, it might just return a meaningless result, depending on the pin number you give it.


I just fried my Arduino on a breadboard. Can I still use the breadboard? So, I just fried my arduino nano on a breadboard. Can I still use the breadboard and usb cable?

you can test the breadboard if you have a multimeter. Even if you don't, you can place an LED, a resistor and a power source across the suspect portions of the breadboard. If you locate a trace or two that appear unreliable, you should be able to mark them appropriately and continue to use the board.


Trouble making TMP102 work with any ADD0 other than ground I'm trying to get an Arduino Uno to run four sensors (all I2C). The first two are TMP102 temperature sensors. The address is controlled by tying the ADD0 pin to GND, VCC, SDA, or SCL (four possible addresses, without multiplexing). I get it to receive data just fine through the GND setting.

I wrote some code to collect from two, but before I was even talking to the second one, plugging it in causes the data stream from the GND one to stop. Unplugging it from the breadboard makes it work again. Either sensor in either location on the breadboard will work fine, as long as it's addressed as ground. Neither sensor will, even by itself, work with any other address. I tried some other sketches from the net (one attached below that should read from any of four different sensors), but all have the same issue.

#include <Wire.h>
byte res;
byte msb;
byte lsb;
int val;

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

void loop()
{
  res = Wire.requestFrom(72,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "72:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(73,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "73:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(74,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "74:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(75,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "75:");
    Serial.println(val*0.0625);
    delay(1000);
  }
}

Breadboard:
(image link: the forum kept crashing when I tried to upload the image directly)
https://www.sugarsync.com/pf/D333436_95042359_6938296

Thanks!

You see that little solder jumper block on the breakout board labelled "ADD0"?  You need to remove the solder from that.  It's currently connected in a pre-defined position and you trying to use the ADD0 pin is conflicting with that.


Several Piezo contact mics with Arduino I'd like to connect about 6 contact mics to my arduino and receive simultaneous signals to be used in my computer for an art installation.

Nonetheless, I don't know what's the ideal way to go. Shall I use Analog pins or Digital? How should I connect them - what schematics shall I follow? I read that ADC is CPU intensive, but I couldn't really find any viable alternative that explicitly shows the Digital deal.

Can I connect several contact mics to different analog pins and receive their input simultaneously as shown here? If this works, then it's perfect.

https://www.arduino.cc/en/Tutorial/Knock

simulate this circuit – Schematic created using CircuitLab

A piezo element can be connected to an analog input (A0 for example) of your microcontroller, but extra resistors are advisable if you wish to have a digital sample that is linearly proportional to the element's alternating voltage.
Andy's caution about over-voltage is relevant too - these elements can produce voltages far greater than your Arduino's DC supply voltage. Such over-voltage can cause damage. Resistor R3 helps limit potential damage.
Each piezo element will require its own set of three resistors (duplicates of R1, R2, R3). Many microcontrollers have multiple analog inputs - you can have as many piezo circuits as there are analog inputs. You cannot sample them all simultaneously, since most microcontrollers usually have only one analog-to-digital converter, which is switched between its various analog inputs by program control. A piezo element would have to be sampled, then switched to the next element for sampling, then the next....etc.
Sampling can be done fast enough that "audio" (however you define it) is fairly represented by the digital sample stream. However, be aware that processing these audio samples may be beyond the speed capability of simple microcontrollers like Arduino. That part is up to you.
Be aware that piezo elements make poor microphones. Units mounted in plastic shells are designed to output audio tones, and have significant resonant peaks. Frequency response is not flat, as required by a proper microphone.


Can someone explain how to program i2C communications without using the library? I am starting to get into i2C, SPI, and other forms of communication. I have read about them and have a fuzzy idea of how they work electrically, but can someone explain how I would turn the electronic portion into the coding/controlling portion? I really want to get a great understanding of it.

The AVR microcontrollers that Arduino uses have built-in hardware support for the said protocols.

That means that you don't have to write program to control the transmission/reception process but you only need to configure the appropriate registers and the hardware will initiate transfer and inform you when it's done.  I suggest you carefully read the datasheet of the microcontroller you are using with your Arduino and you should find all the information there.  It even has code examples, so you can actually copy-paste functions and use them in your program, here is one of the examples:

void SPI_MasterInit(void)
{
    /* Set MOSI and SCK output, all others input */
    DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
    /* Enable SPI, Master, set clock rate fck/16 */
    SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}

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

The keywords with the capital letters are usually register and bit names: you can look them up in the datasheet.


Arduino connection websocket always fails I am using the Arduino Websocket Client library to connect my Arduino Uno to a Socket.IO server. But the connection always returns 0 (fail) after the handshake.
Anyone has used this library before? How could I debug this?

#include "Arduino.h"
#include <Ethernet.h>
#include <SPI.h>
#include <WebSocketClient.h>

byte mac[] = {0xB8,0x27,0xEB,0x7E,0x2D,0xC9};
char server[] = "labathome.rexlab.ufsc.br";
int port = 8001;
WebSocketClient client;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Serial.println(client.connect(server, port));
  client.setDataArrivedDelegate(dataArrived);
  client.send("Hello World!");
}

void loop() {
  client.monitor();
}

void dataArrived(WebSocketClient client, String data) {
  Serial.println("Data Arrived: " + data);
}

PS: I tested the server and it works fine, and I also tested with a normal WS server instead of the Socket.IO, and nothing :(

With the help of the library developer, I found out that it was a problem on the handshake version. So, I just downgraded my socket.io app from 1.0 to v 0.9.11 and it worked.


Arduino code for continuous rotation for 3 servos with Bluetooth This code is working, any ideas?

Please check the code - Bluetooth is connecting but the servo motors are not varying with respect to the app sliders.

#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo2 = realservo;
      servo2 = map(servo2, 1000, 1360, 0, 360);
      myservo2.write(servo2);
      Serial.println("servo 2 On");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo3 = realservo;
      servo3 = map(servo3, 1000, 1360, 0, 360);
      myservo3.write(servo3);
      Serial.println("servo 3 On");
      delay(10);
    }
  }
}

pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.

If you do want to use softwareserial try this code https://gist.github.com/emil01/afedff4c3ba4625ebc75 Here i am using pins 2 & 3.

If you do not want to use software serial you can try this code https://gist.github.com/emil01/9a89800e383ec7f95b3f

In your code

  if (bluetooth.available() >= 2 )
  {
   unsigned int servopos = bluetooth.read();
   unsigned int servopos1 = bluetooth.read();

You are performing 2 consecutive read functions, this is not ideal as there can be data loss. A more ideal solution would be send a string with known string terminators and then parsing this string to get your required data.

For e.g. you could send

  S1:90\nS2:180\n

from this string you can clearly figure out the start and end of the string and accordingly manipulate the data for your need


How can I attach sensors without a shield for a wearable project? I am looking for a solution regarding the gsr, accelerometer, heart rate, skin temperature. From this other question seems that Grove isn't clear enough with their documentation. So I am looking for other ideas. I already know cooking hacks and I am afraid that with their hardware I can't make my Arduino wearable and comfortable enough, because at the end I'd like to attach a lithium battery with a case (that's why I don't want the extra bulk of a shield).

More details of what I am looking for.

Accelerometer:
Range: +/- 1.0g
Minimum resolution: 0.01g

Galvanic Skin Response
Range: 56k Ohms to 20M Ohms
Two-standard-deviation error of +/- 4.0% otherwise

Skin Temperature
Range: 20.0°C to 40.0°C
Resolution: 0.05°C
Error: +/- 0.8°C

The accelerometer may be pretty easy (since it may not need to be in close contact with the person), but the GSR and skin temperature will need to be touching the person to work.

The first thing you will want to do is to identify the sensors that you want to use, and then come up with some ideas for how to make them wearable so that you can measure the parameters that you're looking for. Will you be able to attach them with straps, or does the attachment need to be more subtle or more comfortable? Small breakout boards are handy, but they may make the sensor uncomfortable to wear.

I'd suggest taking at look at the Adafruit site for some ideas on wearables and sensor interfacing. There is a lot of useful information there and much of it focuses on Arduino based designs. For the most part the sensors they sell and use are well documented either with data sheets or code (or both).


Reading the rpm of multiple fans I am trying to build a fan controller for my pc, the problem is that the example code(http://playground.arduino.cc/Main/ReadingRPM) im using utilizes interrupts. On my uno I can then only read the rpm of one fan. I want to also control the rpm (via pwm) and monitor temperatures (via thermistors) Anyone know how I coud do it differently? I. E. Without interrupts. I would also like it to be as close to real time as possible

If temperature regulation is what you seek, why bother with the Tachometer signal at all?

Thermistors don't require interrupts. Why do you need fully closed loop fan control? A simple proportional control of each fan and each hot item would likely suffice in keeping your system cool. Noise concerns, perhaps?

A brief article on proportional temperature control

A data sheet on a TI chip that may have some inspiration for you


How do I use Sound Sensor LM393 + Speaker in Arduino I have this voice sensor:

I need to know how bytes pass through soundsensor into arduino and get this bytes and put out in a speaker.

I read on the net a Lib PCM thats converts chars in voices, but how do I extract bytes from sound sensor in analog-in?

This post was awhile ago, but I wanted to offer some more definitive info for others like myself who were trying to identify it. What you have there is the Keyes KY-037 "high-sensitivity voice sensor" module. Mine came with the Inland Arduino Uno RFID Learning Kit.

Apparently the KY-037 and the KY-038 are the same except the KY-037 has a higher sensitivity microphone. I could not find any specs to quantify what that sensitivity difference is, however. Both have a LM393 voltage comparator on the board. The same Arduino code ought to work for both.

Here are a few helpful links I found, some also showing a bunch of the other Keyes modules and how to use them:

http://linksprite.com/wiki/index.php5?title=Advanced_Sensors_Kit_for_Arduino

http://brd4.braude.ac.il/~ksamuel/ElIn.31361/Lectures/022-Basic%20Definitions%20and%20Concepts%20Sensors%20and%20Actiators%202013-10-10.pdf  (Page/slide 40)

tkkrlab.nl/wiki/Arduino_37_sensors


Parsing HTTP get response to extract values Basically I created a web page to control 4 channel relay, then I made an HTTP get request from that page and got the following response:

Linked

T+CIPSEND=4,50

> GET /ard/sensor.html HTTP/1.1
Host: localho
SEND OK

+IPD,4,351:HTTP/1.1 200 OK
Date: Sat, 07 Apr 2018 01:22:58 GMT
Server: Apache/2.4.9 (Win32) PHP/5.5.12
Last-Modified: Sat, 07 Apr 2018 01:17:13 GMT
ETag: "72-56937eec1c277"
Accept-Ranges: bytes
Content-Length: 114
Content-Type: text/html

<p> Relay1 = 1#  </p> </br>
<p> Relay2 = 0#  </p> </br>
<p> Relay3 = 0#  </p> </br>
<p> Relay4 = 1#  </p> </br>
OK

OK
Unlink

Now I want to store Relay1 status (which is 1 here) in a variable, also all other Relays in order to control them high or low
Note : # is supposed to be the separator
and here is my code:

    #include <SoftwareSerial.h>

const int LED_PIN = 13;

String ssid = "ABC";
String password = "a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {

  Serial.begin(9600);
  ESP8266.begin(9600);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

  ESP8266.println("AT+RST");
  ESP8266.println("AT+CIOBAUD=9600");
  delay(1000);

  if (ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  ESP8266.println(cmd);

  delay(4000);

  if (ESP8266.find("OK")) {

    Serial.println("Connected!");

  }

  else {

    connectWifi();

    Serial.println("connect to wifi");
  }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1\r\nHost: localhost";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());

Byte R[ ] = ESP8266.read () ;
Serial write (R[ ]);

//    if (readString.indexOf("Relay1=1">0))
{
    Serial.write("found");
}
  }

}

Any suggestions ?

First of all, I would avoid using the String class, because of the
memory fragmentation issues that come with it. The most obvious solution
is probably to store the result in a character array, then parse the
array, with strstr() or sscanf(), to extract the values you want.
However, this requires storing the whole response in RAM, which is
expensive. A better option is to parse the string as it comes, character
by character, using a kind of finite state machine.

Here is how I would do it. First, I assume you know what you want to do
with these values. Since I don't, I will instead use this dummy function
to just print the values out to the serial port:

static void parse_relay_callback(uint8_t index, uint8_t value)
{
    Serial.print("parsed: relay ");
    Serial.print(index);
    Serial.print(": ");
    Serial.println(value);
}

You will have to replace this with whatever is appropriate for your
application.

Then here is the parser:

static void parse_relay(char c)
{
    static const char templ[] = "RelayI = V#"; // I: index, V: value
    static uint8_t pos, index, value;
    char expected = templ[pos++];
    if (expected == 'I' && c >= '0' && c <= '4')
        index = c - '0';
    else if (expected == 'V' && (c == '0' || c == '1'))
        value = c - '0';
    else if (expected == '#' && c == '#')
        parse_relay_callback(index, value);
    else if (c != expected)
        pos = 0;
}

You just feed it one character at a time, with something like:

while (ESP8266.available())
    parse_relay(ESP8266.read());

Feeding the parser with your response example gives the following on the
serial port:

parsed: relay 1: 1
parsed: relay 2: 0
parsed: relay 3: 0
parsed: relay 4: 1


Send data to Programmable Power supply from Arduino by RS232 I have a programmable power supply, which has serial communication port. If I send a string "VSET1:11.00" then power supply will be set to 11.00V.
But, I need to write a program which will increase the voltage of power supply by 0.10V
For ex from 0V to 11.00V in incrementing steps of 0.10V.
Also, power supply needs a fixed data frame format like Parity bit, Data bits, stop bit.
So, how to create a data frame structure and send from arduino.
Do I need to use Software Serial library?
PS. I'm new to arduino, so may sound foolish.

First you will need a TTL to RS-232 adaptor. These are most commonly known as the "MAX232" and is available as a little module.
This will convert the 0-5V TTL signal the Arudino produces into the ±10V signal that RS-232 uses. There's plenty of tutorials online about how to use them.
Then you need to generate the signal. Yes, for the Arduino UNO the SoftwareSerial library is what you want.  Again there's plenty of tutorials on using it.
To actually send the instructions it may be something like:
#include <SoftwareSerial.h>

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

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

void loop() {
    for (int i = 0; i < 11000; i += 100) { // I'm working in millivolts here.
        PSU.print("VSET1:");
        PSU.println(i / 1000.0, 2); // Convert millivolts into volts with 2 DP
        delay(10); // 10ms delay
    }
}

I haven't tested it, but that should give you 0-11v rising at 0.1v per 10ms.


Overloading function loop I want to introduce a boolean that is the first iteration of loop and then false
every subsequent iteration. I want it invisible, so I have to modify loop in some way. Is that possible?

The way to do this isn't to overload the loop function, the way to do this is to abuse the linker and replace main().

The main.cpp file that gets used in the Arduino make prototypes main as int main(void). On my system at least the linker prefers the longer prototype, so you can just do this:

int main(int argc, char* argv[])
{
    init();

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

    setup();

    //The one shot loop...
    loop();
    if (serialEventRun) serialEventRun();
    //Put whatever else you need to do between before the unending loop here.

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

    return 0;
}

Both get compiled, but the int main(int argc, char* argv[]) prototyped version gets linked as the entry point, so your "invisibile" code gets executed.


How to read long value sent by Arduino in C I have a quick question regarding this code below in Arduino:

Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.println(5);

In C code, currently I'm receiving the message using this method below:

int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
{
    char b[1];  // read expects an array, so we give it a 1-byte array
    int i=0;
    do {
        int n = read(fd, b, 1);  // read a char at a time
        if( n==-1) return -1;    // couldn't read
        if( n==0 ) {
            usleep( 1 * 1000 );  // wait 1 msec try again
            timeout--;
            if( timeout==0 ) return -2;
            continue;
        }
        buf[i] = b[0];
        i++;
    } while( b[0] != until && i+1 < buf_max && timeout>0 );

    buf[i] = 0;  // null terminate the string
    return 0;
}

In C i defined:

char message[13];
uint32_t num;
char until = '\n';

serialport_read_until(fd, message, newLine, sizeof message, 20000);
// the 20000 is timeout in millisec
// this method stores the data in serial buffer into message array

printf("message is %d\n", num);

I am expecting a raw value of 0501050105 first.
Then I convert this raw string into 501050105 using:

sscanf(message, "%d", &num);

Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

In addition, when i use serialport_read_until() method above, even though i specify the char until as '\n', the method terminates after reading '\r' (leaving the \n in the serial buffer), and the '\n' is only captured in the next method call.

Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

Thank you very much.

char b[1];  // read expects an array, so we give it a 1-byte array

No, it expects a pointer to a destination to store the data. You don't need a 1-entry array - you can simplify your code with:

char b;
...
int n = read(fd, &b, 1);  // read a char at a time
...
buf[i] = b;
... etc ...

  Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

C has the function strtoul() which is far more efficient that sscanf.

uint32_t val = strtoul(buf, NULL, 10);

The 10 is the base to convert from, so you could convert hexadecimal (base 16), octal (base 8), etc using it.

  Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

You're defining the variable until to contain \n, yet passing the variable newLine to your function. Maybe that has something to do with it?

  Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

You can send a 32-bit value using just 4 bytes. However it's not reliable without implementing a whole protocol around those 4 bytes which, for just 4 bytes, is a bit of a waste. Simplest just to stick to ASCII encoding your data.


Two voltage sources on the same circuit I am looking to power a Trinket Pro 5V microcontroller using a 9V voltage source. I have logic running on this controller to gather the data from an accelerometer (powered off of the 5V pin on the controller) and output it to three strands of 21 RGB LEDs (https://www.adafruit.com/products/1655).

RGB LEDs cannot exceed a power source of 5V and after passing through the Trinket voltage regulator the 5V pin on the Trinket just does not have enough power for all three strands.

Please, advise on the appropriate hardware for this case. What is the maximum voltage that RGB LEDs can handle and how does the schematic look on the protoboard.

Thank you for your expertise.

First of all: 9V means that you are using a 9V "transistor" battery (like this), right?

If so it won't last very long: I suggest you to use a different approach (e.g. four AA batteries in series).

As for your question, I couldn't find the power consumption for these leds. Try to measure it yourself, setting the max brightness and white color. I think that, anyway, the max current for each LED should be 60mA (20mA for each color). This means that each strand absorbs 1.2A (quite a lot!).

This power requires you to use at least a switching regulator. I always used some small modules I found on ebay (they have a LM2596 IC, so just search LM2596 on ebay to find them). They are rated for 3A, so you should put at least two of them (1.2 * 3 strands = 3.6A > 3A).

The connections are quite straightforward: the board has four pins: IN+, IN-, OUT+ and OUT-. IN+ of all the modules go to the positive terminal of the battery, IN- and OUT- of all the modules go to the common ground node (negative terminal of trinket, battery and leds), OUT+ is the 5V regulated output. Oh, by the way, they are adjustable modules, so BEFORE ATTACHING THE LEDS use a multimeter to set the correct voltage (if you attach the leds without regulating the voltage you can destroy them).

Since you will have a lot of current left on the second module, you can power the trinket from there (so you will not waste a lot of power).

One last thought: 9V batteries usually have a capacity of around 600mAh; if you use one of them with the switching modules and drain 4A from the 5V your battery will last 0.6Ah / 4A * 9/5 = 0.27h = 16 minutes; if you switch to 4 AA batteries (around 2000mAh) it will last 2Ah / 4A * 6/5 = 0.6h = 36 minutes. More than double (calculations made rounding up the power drained by 21 leds set at max brightness and white color)


AVR software reset without watchdog I wrote a generic avr program wrapper which already use the watchdog timer to restart - and after the watchdog reset - recover the the bad situation.

After this recover process i have to restart the avr. Everything i've found in topic "software reset arduino" is about to set the shortest watchdog (15ms) timeout, then spins the CPU (for(;;);) until it cause watchdog reset.

But this results to enter the recovery process which is already done in this point.

It is any elegant way to achieve this?

Some non or less elegant way:

I can bind a digital pin to the reset and pull up with a resistor.
I can write to a fixed address in the flash or eeprom (but this maybe happens frequently) before soft restart, to prevent entering to recovery mode.

Is there any register that "survives" soft resets?

Edit:

I add mock example code to hint what i trying to do.

In the actual code, in the recovering the microcontroller connect to the serial bus, waits for commands then resets itselft in oder to return to application mode.

/*************************** Application wrapper ******************************/

//define call_application and call_recover as weak empty functions
//so they can be rewritten.

bool isWatchdogReset()
{
    return MCUSR == 8;
}

void softwareReset()
{
    //  wdt_enable(WDTO_15MS);for(;;);// (this way enters recovery mode)
    //or
    //  asm ("jmp 0x0");// (this way function registers not being resetted)
}

bool isSoftwareReset()
{
    //???
}

int main()
{
    bool needRecover = isWatchdogReset() && !isSoftwareReset();
    MCUSR = 0;
    init_board();
    wdt_enable(WDTO_1S);
    while(1)
    {
        if(!needRecover)
        {
            call_application();
        }
        else
        {
            call_recover();
        }
        wdt_reset();
    }
}

/********************************* Application ********************************/

void call_application()
{
    if(randomTrue())
    {
        //stuck more that 1 secounds, that results WDT reset
    }
    else
    {
        //proper operation
    }
}

/********************************** Recover ***********************************/

void call_recover()
{
    //initialize UART, attach interrupts, Write flash and EEPROM, modify
    //function registers.

    //recovering completed, returning to the original application as like
    //nothing's happened.
    softwareReset();
}

Edit:
I try explain short to spot the point:

1) I already use the watchdog timer to detect when the application code is flawed.

2) soft reset is an inproper solution, because it doesn't reset the registers. So onyl the program will be resetted, the state of the microcontroller doesn't.

3) To commit a proper reset, the solution is to timeout the watchdog timer. But see point 1), it is already used, so how can you make the difference of a requested reset and a flawed code recovery reset?

The reset is basically jumping to the reset vector address 0x0000 (if you don't have the bootloader, or you don't want to start it).

There is also the MCUSR register, indicating which reset source caused the reset. It won't be set if you do simple jump to the reset adress.

The memory is also preserved, but C/C++ init code takes place and initialize your global variables. This can be ommited by placing variable/variables into the .noinit section. But it's not defined, what is there after the reset. With combination with MCUSR register you can init the variables for regular reset sources and keep it unchanged if you jump to the reset vector address.

Also the regular reset sources jumps to the bootloader, so it can use the same memory locations as your .noinit variables and trash them.


Arduino and PHP communication only work if I open the Arduino IDE I have a problem. I try to open a channel to arduino and PHP talk, the PHP would send a command and the Arduino should answer that. It works, but only if I execute some steps before:

sudo chmod 777 /dev/ttyACM0
sudo arduino
Open the serial monitor in arduino IDE
Close the serial monitor
Now everything is ok, they can talk

The first step is ok, I really need to do this, the 2-4 seems irrelevant, but the communication do not start without it. I put one LCD in arduino to print what he receive, when I send "HEYARD" with PHP to him, the RX led blinks and the TX led also, but nothing is printed on LCD. If I do the 2-4 steps, when PHP send "HEYARD", LCD show HEYARD and arduino answer with "HEYPHP"

Anyone could help? There is some way to open it via Terminal, or, at least, open the Serial Monitor from arduino and close to see if this start

Here the setup block:

<?php
    require("php_serial.class.php");
    $serial = new phpSerial();
    $serial->deviceSet("/dev/ttyACM0");
    $serial->confBaudRate(9600);
    $serial->confParity("none");
    $serial->confCharacterLength(8);
    $serial->confStopBits(1);
    $serial->confFlowControl("none");
    $conect = mysql_connect("localhost", "root", "") or print (mysql_error());
    mysql_select_db("ANM", $conect) or print(mysql_error());
?>

And here the connection block:

<?php
    $serial->deviceOpen();
    exec("echo 'HEYARD' > /dev/ttyACM0");
    sleep(1);
    $read = $serial->readPort();
?>


Can I supply the board's 3.3V directly to the AREF pin? Short dumb question: can I connect the 3.3V pin and the analog reference pin (AREF) directly?

I've heard mentions of a 32K internal resistor but I'm not willing to risk a short circuit without confirmation. Should I add an external resistor? Won't that create a voltage divider?

In Atmel's doc8271 pdf (with specification details for ATmega48A; ATmega48PA; ATmega88A; ATmega88PA; ATmega168A; ATmega168PA; ATmega328; and ATmega328P), table 29-20 on page 117 shows R_REF (the AREF input resistance) as 32KΩ (typical).  Section 24.5.2 on page 248 suggests that AREF is to be treated as a high-impedance input or output:

  ... the reference voltage can be made more immune to noise by connecting a capacitor between the
  AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that
  VREF is a high impedance source, and only a capacitive load should be connected in a system.

Also note that there is no reason to connect anything to AREF (pin 21), because on a standard Uno, AVCC (pin 20) is connected to VCC (pin 7), and one can select AVCC as the reference voltage during analog converter setup [as explained below].  Quoting again from section 24.5.2:

  VREF can be selected as either AVCC, internal 1.1V reference, or external AREF pin.  AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC...

Summary: you can connect the 3.3V pin and the analog reference pin (AREF) directly, but on a 3.3V system  there is no reason to do so.

Selecting AVCC as the reference voltage:  Say analogReference(DEFAULT) to select AVCC as the reference voltage.  According to arduino.cc, this will choose “the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)”.


I want to get incomming call number and compare it Hello i want to get and compare incomming call number, it works but not as I want.
When im calling from good number it print that I was calling form saved number when the number is stop calling i need to do it on start. And else is printing when nobody is calling. How can i do it? Here is my code:

String d = "";
void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.println("AT");
  delay(500);
  Serial1.println("AT+CLIP=1");
  delay(1000);
  Serial1.println("AT+CPIN=1439");
}
void loop()
{
 d = Serial1.readString();
 if(d.indexOf("xxxxxxxxx") >=0)
   {
 Serial.println("call is from saved number");
    } else {
       Serial.println("call is not from saved number");
      }
}

The Arduino Serial class member function readString() has a builtin timeout. The function will return on timeout. The default timeout period is 1000 ms. The timeout can be set with setTimeout().

The sketch needs to filter out empty lines (timeout). This can be done by adding a check of the string length. See below for an example of checking:

void loop()
{
  String d = Serial1.readString();
  if (d.length() == 0) return;
  Serial.print(d);
  if (d.indexOf("xxxxxxxxx") >= 0) {
    Serial.println(": call is from saved number");
  }
  else {
    Serial.println(": call is not from saved number");
  }
}

Cheers!