avrdude: stk500_recv(): programmer is not responding - OSX10.11 I'm getting the following error with a genuine Arduino Uno on Mac OSX10.11 El Capitan when uploading to it (the green light is on, the orange light flashes intermittently while attempting to upload). Here's the error:

avrdude: stk500_recv(): programmer is not responding

I've tried all the solutions I can find. I've selected the correct port and board. I've tried pressing the reset button before uploading. I've tried different USB cables. I've tried unplugging and replugging everything. I've read this: http://arduino.cc/en/Guide/Howto .

I tried all these solutions here: https://stackoverflow.com/questions/23993111/mac-uno-avrdude-stk500-recv-programmer-is-not-responding

I tried the FTDI fix, (but not sure if was actually able to disable the mac drivers, or which drivers are now running, the example I tried is for for OSX 10.10 Here). I ran into the following issue in the Terminal:

Mac-Pro:~ m$ cd /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns
Mac-Pro:PlugIns m$ sudo mv AppleUSBFTDI.kext AppleUSBFTDI.disabled
mv: rename AppleUSBFTDI.kext to AppleUSBFTDI.disabled: No such file or directory

I don't get why it says No such file or directory because AppleUSBFTDI.kext definitely exists as a package in the Extensions folder, but I guess it's talking about another file named that in the plugins folder? Confusing ... Was this moved in OSX 10.11 and should I rename this package in the Extensions folder?

I did download and install the old FTDI drivers, but I don't know if they're actually the ones working right now? How do I clarify that?

Any ideas how to get this working?

I also tried on an old Mac Laptop 10.6.8 - Snow Leopard, and had the same issue :(

Has this ever worked?
Can you use avrdude and hit the target?
There is a terminal mode in avrdude you can also use.  At least this would help you determine what is working.

Sounds like a configuration issue.  If you have the ability to 'follow the tail' (tail -f ) I'm assuming that you have 'like' tools we have in Linux like lsusb to assist?

You can ensure yourself that if it says it isn't found, it's not finding it, so it's not wherever it's looking. :)


Arduino's digitalWrite, precautions for direct port manipulation? I stumbled upon this piece in digitalWrite.
I'm unsure why clearing interrupts and setting/resetting SREG is neccesary here.

Can anyone shed a light on this?

uint8_t oldSREG = SREG;
cli();

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

SREG = oldSREG;

I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes *out = *out & ~bit?

And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

When speed matters, I often use the direct port manipulation, I'd like to get an idea if it's neccesary for me to include these "precautions".

I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes *out = *out & ~bit?

Correct. That is known as a critical section.

  And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

SREG is where the flag that says if interrupts are enable or not is stored.  Basically that is storing the current state, disabling interrupts, then restoring the current state.

The upshot is:

If interrupts are enabled to begin with, they are disabled, then re-enabled.
If interrupts are disabled to begin with, they are again disabled, and they remain disabled.

It's a way of restoring the previous state without actually having to check what the state was and set or clear accordingly.


Arduino Code for Pulse Skip Modulation (PSM) I have recently bought this light dimmer, and only when I received it I noticed it works with PSM (Pulse Skip Modulation) and not PWD (Pulse Width Modulation).

Does anyone know how to write Arduino code and do the wiring for this dimmer? I can't seems to find a working example.

Thanks

Just adding to chrisl's answer since I bought this module, too.

There is a simple example on the manufacturers website of this module which does not seem to implement PSM the obvious way:

/*
Connect RobotDyn AC Light Dimmer as follows:
Dimmer pin  --  Arduino pin
    VCC     --    5V
    GND     --    GND
    Z-C     --    D2
    PWM     --    D3

Glow sketch for AC Voltage dimmer with Zero cross detection
Based on the sketch by Charith Fernanado
Adapted by RobotDyn: http://www.robotdyn.com
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table (the Pin numbers are digital pins, NOT physical pins: digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All
3      |  1            |  All
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

// the interrupt function must take no parameters and return nothing
void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle) For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Off cycle
  digitalWrite(AC_LOAD, HIGH);   // triac firing
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // triac Off
}

void loop()  {
  for (int i=5; i <= 120; i++){  // We use 120 as the lowest and 5 as the highest brightness setting. May be adjusted depending on the lamp used.
    dimming=i;
    delay(20);
   }
  for (int i=120; i >= 5; i--){  // Same as above
    dimming=i;
    delay(20);
   }
}

They are using an interrupt as suggested by chrisl.
There is no flickering present with low dim values (using an incandescent bulb).
See this video for a similar board with the original version of the above sketch.

Note: If you want to integrate your own code into this example, it will likely not work as intended because the Arduino is busy with delayMicroseconds() most of the time

EDIT: The manufacturer of this module just released a library. Check it out on their github


HID communication between Arduino Uno and computer I used some firmware I found online to turn the UNO into an emulated HID device. The Arduino is no longer connected to a Serial COM port so I can't send serial data from my computer to the device. Is there a way that the Arduino can receive data from the computer in order to drive a function while in the HID emulated state?

You could use a second USB on the PC and use Hardware Serial to transmit commands. (Either via a second Arduino or a FTDI adapter) But be aware that at least the firmware I use and the controller programs are very sensitive to being disturbed in the loop. So you should have a good understanding of timers, interupts and non blocking code.


What USB to UART chip provides highest data rates with Arduino boards? Checking out online stores for a USB/TTL adapter, I came across a wide range of products, and I'm having a hard time selecting the one which would achieve the highest data rate. I was comparing datasheets of the chips I have seen so far, to understand which baud rates are supported:

FT232R (FTDI): 183 to 3M baud, including 250k, 500k and 1M, 128 RX / 256 TX FIFO
PL2303 (Prolific): 75 to 1.2M baud, not including 250k, 500k and 1M, 256 RX / 256 TX FIFO
CP2102 (Silicon Labs): 300 to 921600 baud, including 250k and 500k, 576 RX / 640 TX FIFO
CH340G (WCH): 50 to 2M baud, not including 250k, 500k and 1M, unknown FIFO size

As explained here, 500k, 1M and 2M are particularly important, because those are the highest baud rates supported with 16MHz crystals. Moreover, data transmission becomes CPU-limited above 500k, so real data rates are practically the same with all three baud rates.

Am I right to assume that in order to get the highest data rate, I essentially have to stay away from PL2303, and prefer FT232R adapters, the other two chips being in the middle? Or are there other factors that I didn't take into account which may affect my choice?

Here's my experience with the above chips over the last two years:

FT232R is the fastest, works well with any baudrates. UART adapters with it are sometimes more expensive than alternatives.

PL2303 is good if you don't plan to go faster than 115200. Additionally, it has the strongest 3.3V reference (available on some adapters as 3.3V output) which can be abused as a 3.3V 20mA power supply. Other chips will refuse to work if you draw more than 5mA from the 3.3V reference.

Prolific is currently fighting against clones by making their up-to-date drivers incompatible with non-original chips, so if your adapter won't work in Windows with code 10, take a look at this page.

CP2102 which looks great in theory didn't work well for me (in Windows 10, with driver v10.1.3). Bulk data transfers at 115200 were in some cases 4 times as slow compared to other chips.

CH340G has a sketchy-looking windows driver, but otherwise works quite well and is often the cheapest option available. Unfortunately, it lack the intermediate baud rates, and getting 2Mbps UART link to work may be hard sometimes. Arduino clones which have this chip on-board do work at 2Mbps without issues (the ones I have seen do, anyway).


Getting Bluetooth addresses of connected devices via Arduino Uno? I want to find all the Bluetooth addresses of connected devices using  an HC-05/HC-06 Bluetooth module and an Arduino. I can't find any code related to this. Basically I need the addresses to put in an array. Is it possible to do this with an HC-05 or 06?

The HC-05 has an AT command, AT+BIND?, that will tell you which slave device it is connected with currently. Since you can connect to one device only at the same time, your array is going to be a very short one.

AT+INQ will provide you with a list of nearby devices, to which it can connect.


PUT request: PHP code to Arduino HTTPClient I'm uploading a file to Azure blob storage using REST API request. The file uploaded successfully using PHP curl request. But when I transfer the code into ESP32 HTTP client I'm getting an Authentication error. I also verify the HMAC key generated by the ESP32 Arduino code in PHP code.
I'm thinking that I'm missing something in adding header.
Here is my PHP code :

       $header = array (
        "x-ms-blob-type: BlockBlob",
        "x-ms-date: " . $date,
        "x-ms-version: " . $version,
        "Authorization: SharedKey account_name:" . $signature_str,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Length: " . strlen($fdata),
        );

    $url =  "https://acount_name.blob.core.windows.net/container/test.txt";
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata);
    curl_setopt ( $ch, CURLOPT_HEADER, True );
    echo($ch);
    curl_exec ( $ch );

and here is the corresponding Arduino IDE code:

    String sig = get_hmac();
      Serial.println(sig);

      if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        HTTPClient http;
        http.begin("https://account_name.blob.core.windows.net/container/test.txt");  //Specify destination for HTTP request

        http.addHeader("x-ms-blob-type", "BlockBlob");
        http.addHeader("x-ms-date", Date);
        http.addHeader("x-ms-version", "2018-03-28");
        http.addHeader("Authorization", "SharedKey account_name:"+sig);
        http.addHeader("Content-Type", "text/plain; charset=UTF-8");
        http.addHeader("Content-Length",  "20");

        int httpResponseCode = http.PUT(d);
        if (httpResponseCode > 0) {
          String response = http.getString();
          Serial.println(httpResponseCode);
          Serial.println(response);
        } else {
          Serial.print("Error on sending POST: ");
          Serial.println(httpResponseCode);
        }
        http.end();  //Free resources
      } else {
        Serial.println("Error in WiFi connection");
      }

The error I'm getting is :

  The MAC signature found in the HTTP request
  'sVrSFpplX+Gkcb4R/iSDf6eqUP4srkZuVD68/pAeYwE=' is not the same as any
  computed   signature.....

Although the HMAC signature created from same String works in PHP
here is the reference page of the API:
https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
Thanks

I got clue from @esoterik answer and manage to send request successfully.
The problem were in adding header parameter:

 http.addHeader("Content-Length",  "20");

This duplicate the header( 2nd one added in PUT method). I just comment it and the code works.
Thanks for every one response


Unusual behaviour over serial communication I am sending data over serial connection from a python script to my Arduino UNO. Now initially whenever I tried to send data to the arduino, it would reset. The fix was to put a 10 microFarad capacitor between the 5V and RESET pins. I did that and everything started working.

Now after while,  mistakenly today I ran the same script without the capacitor between the 5V and RESET pins and for some reason it was working perfectly well. No more resetting when a value was received over serial communication.

Is something wrong with my Arduino?

Knowing the entire setup would help.  For instance, knowing if the RS232 source will drive the Arduino input's dangerously past the Arduino's power rails.

If you have connected a real RS232 signal to the Arduino, the +12 to -12 volt swings could adversely affect the processor.  Causing unexpected behavior.  In such a case you would need a converter like this one.

Over driving inputs is discussed in this Stack Exchange question where the highest scoring answer says:

  If you violate the spec sheet normal operating conditions requirements
  you can expect to experience abnormal operating conditions. These may
  range fro perfectly normal opration through complete maloperation...

That answer also links to this tutorial about logic level conversion.

Finally, there is this tutorial which specifically addresses converting RS232 to safe TTL level signals appropriate for a micro processor.


Splitting a string read from Serial into parts Is there any method with which I can split a string given by Serial.read() into an array of 3 items: [command, address, message], to write it to EEPROM?

Thanks.

The first thing you should do is to collect your serial input into a string.

If your incoming data use a separator, then you can take advantage of the useful function "readStringUntil".

For example, if your separator is comma (,):

while (Serial.available() > 0) {
  var1 = Serial.readStringUntil(','); // writes in the string all the inputs till a comma
  Serial.read();
  var2 = Serial.readStringUntil(',');
  Serial.read();
  var3 = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
}

At this point you have your data in 3 different variables and you can use the standard eeprom library to store. Don't forget you will need to declare the variables and to initialize the Serial.

A faster way is to save the whole input in string and process it when ready.

Much better it will be if you use interrupts attached on the Serial input, so you can keep free your loop from waiting data. This can't be done with the standard Serial library but you can use this library:

https://github.com/SlashDevin/NeoHWSerial

It works really well, we use it to collect data from GPS receivers at very high speed and it's fast.

N.B. eeprom is limited in the numbers of reads and writes it can support before risk a failure. Even 100,000 reads/writes sounds a big numnber, if you write the data once every second your eeprom will die in just 27 hours, a day of life. Try to write data only when it's strictly necessary and read data as well only when you start the procedure that uses those data, once.


Potentiometer with switch wiring question. Not reading correctly I have a potentiometer with switch, that seems to be working a little wonky (Keep in mind I have tried this with a few different pots and they all behave the same way which leads me to believe I am wiring them wrong).

I can easily hookup the potentiometer and it's three terminals on the side, 1 being ground, 2 being output, 3 being input power. I can monitor it's value on a serial port with Arduino.  However when I try and test the switch, which are two terminals on the bottom of the pot.  I get an on signal when the pot is on, but when it is clicked off I get a random on/off signal.  As in it reads that it is sort of on but never truly reads off.

Right now I am simply giving it 5v from the Arduino to both the switch and the third terminal.  Should I be giving the switch power via a capacitor? Not sure, have not tried that yet but that may smooth out my readings.

Any suggestions?

From your description of switch wiring, it sounds like you have one of the switch leads attached to +5 V and the other switch lead to an input.
As noted in comments and answers to  “Why all unset pins of my Arduino Uno are outputting 2 volts?”, such an input will read high when the switch is closed, and will read randomly when it is open, because an input is a high-impedance device that can accumulate charge:

... input impedance typically can be taken as 100 MΩ for design purposes. ... Each pin has a few pF (5-10?) of capacitance ... which in general is small compared to stray capacitances of attached wiring.
When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin. You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the [voltage] you are seeing.

The easy fix for the problem is to attach one switch-lead to ground, one to an input pin, and initialize the pin with INPUT_PULLUP pinmode instead of just INPUT.


Firmware gets stuck at obj.printto(client) in esp32 I am using an ESP32 to capture some data and then sending it over using ArduinoJson. However, sometimes, the firmware gets stuck at the line where it is transmitting data at obj.printTo(client). I have the logs for the same. Do you have any idea as to what might be making it freeze? And any way to avoid it in the future.

Logs:

12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...

12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...
12:47:11.229 -> [E][ssl_client.cpp:33] handle_error(): UNKNOWN ERROR CODE (004E)  12:47:11.229 -> [E][ssl_client.cpp:35] handle_error(): MbedTLS message code:-78

12:47:11.229 -> [V][ssl_client.cpp:245] stop_ssl_socket(): Cleaning SSL connection.
12:47:11.229 -> request sent
12:47:12.217 -> esp32/Arduino CI has failed
12:47:12.217 -> reply was:
12:47:12.217-> ==========
12:47:12.217 ->
12:47:12.217 -> ==========
12:47:12.217 -> closing connection

The send code:

jsonBuffer.clear();
JsonObject &rootObject = jsonBuffer.createObject();
JsonObject &dataObject = rootObject.createNestedObject("data");
JsonArray &X1dataObject = dataObject.createNestedArray("X1");
JsonArray &Y1dataObject = dataObject.createNestedArray("Y1");
JsonArray &Z1dataObject = dataObject.createNestedArray("Z1");
JsonArray &T1dataObject = dataObject.createNestedArray("T1");

vTaskDelay(10);

if (send_flag) {
  digitalWrite(2,0);
  send_flag = false;
  int connection_iterator = 0;
  int connection_iterator2 = 0;
  for (int iterator = 0; iterator < SAMPLE_SIZE; iterator++) {
    X1dataObject.add(X1dataArray[iterator]);
    Y1dataObject.add(Y1dataArray[iterator]);
    Z1dataObject.add(Z1dataArray[iterator]);
  }
  T1dataObject.add((float)(analogRead(NTC)*0.0244));

  rootObject["coreid"] = String(low, HEX) + String(high, HEX);
  //rootObject["coreid_high"] = String(high, HEX);
  rootObject["sample_time"] = int(time_taken);
  rootObject["firmware_version"] = FIRMWARE_UPDATE_VERSION;
  rootObject.prettyPrintTo(Serial);
  Serial.print("connecting to ");
  Serial.println(host);
  while ((!client.connect(host, httpsPort)) && !setup_mode) {
    connection_iterator++;
    Serial.println("connection failed! Retrying..");
    delay(5000);
    if (connection_iterator >= 10)
      ESP.restart();
  }
  if (client.verify(fingerprint, host)) {
    Serial.println("certificate matches");
  } else {
    Serial.println("certificate doesn't match");
  }
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.print("requesting URL: ");
  Serial.println(url);
  client.println(String("POST ") + url + " HTTP/1.0");
  client.println(String("Host: ") + host);
  client.println("Cache-Control: no-cache");
  client.println("Content-Type: application/json");
  client.print("Content-Length: ");
  client.println(rootObject.measureLength());
  client.println();
  rootObject.printTo(client);
  Serial.println("NUMBER OF INTERRUPTS:");
  Serial.println(interruptCounter);
  Serial.println("request sent");
  while ((client.connected()) && !setup_mode) {
    connection_iterator2++;

    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
    Serial.println("Waiting for response");
    delay(500);
    if (connection_iterator2 >= 40)
      break;
  }
  String line = client.readStringUntil('\n');
  if (line.startsWith("{")) {
    Serial.println("esp32/Arduino CI successfull!");
  } else {
    Serial.println("esp32/Arduino CI has failed");
  }
  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");
  digitalWrite(LED_BUILTIN, LOW);
  // readRegister(INT_SOURCE, 1, &dummy_read);
}

I see that you are using SSL. SSL uses a lot of RAM and it is possible that the stack and the heap are colliding which will corrupt the running sketch. I recommend you add the amount of free heap to your log statements so that you can see how it changes, which will help you see if this is what is happening.

To obtain the free heap you can use esp_get_free_heap_size() - there's more documentation about this function in the espressif online documentation.


DS18B20 setting resolution without addressing As i understand the dallas library, there are two ways of referencing the sensor, one is to refer to the address, and the other is just to grab it as it is indexed.(gettempbyindex)

I want to know how to set the resolution of the sensor when i'm using the gettempbyindex method, all the examples i can find seem to only set resolution when specifying the address explicitly..

Is it even possible?

You can use getAddress: bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index)

If you want to set the resolution for all devices, you can just use void DallasTemperature::setResolution(uint8_t newResolution). (It will call getAddress for all indices.)


For the digital output pins, how is LOW different than no connection? I am working with relays and I noticed that connecting the trigger pin to ground (or a digital pin set to LOW) is not the same as having the trigger connected to anything.  For the digital output pins, how is LOW different than no connection?  Is there actually a current flowing into the LOW pin, or is there a tiny current flowing into the relay?

Is Ground and LOW the same voltage?

(Edit for clarification: I've assumed in this answer that you're asking about the difference between connecting the relay to ground/LOW vs. connecting the relay to nothing at all. I've also assumed by the word "trigger" that your relay has some kind of digital actuation built-in, such as a transistor, or that it's simply a Solid State Relay.)

If something is unconnected, it is described as 'floating'. This means there could be random voltage spikes in it caused by nearby electromagnetic fields, making it appear to be switching on/off.

Connecting something to ground or LOW can stop this from happening by drawing away any induced currents.


Can internal and external pull up/pull down resisters be used together? What happens if a sketch uses code like pinMode(18,INPUT_PULLDOWN) to configure internal pull-down (or pull-up) resistors, but is used in a circuit where external resistors are also present?
Are there likely to be any problems, conflicts or unexpected behaviour, e.g. if software sets a pull-down, but there is an external pull-up, or visa versa?
I am using an ESP32 (which has both internal pull-ups and pull-downs available on most GPIO pins), but I would appreciate a general answer. To clarify, I am not after the pros and cons of using external resistors (which is discussed in other questions), but the potential pitfalls of using both, especially if they are pulling in opposite directions.

The main risk if you use both internal and external pullup/down resistors working in opposite directions is that the input will be left at an intermediate voltage that is not guaranteed to be read as high or low. Furthermore a little noise on the input might flip a read from high to low or vice versa. There is no risk of damaging the input however


How can I communicate from Arduino to MATLAB I want to use sensors on an Arduino to control values in a MATLAB program. What are my options for communicating?

I've used Processing to receive data sent via the serial cable, and that strategy has worked pretty well. Is there something similar I can do using MATLAB? I'm somewhat new to MATLAB, so gentle guidance would be great.

I'm not really looking for something like the ArduinoIO package -- I want to have separate computation executing on the Arduino and occasionally informing my MATLAB program (which will occasionally poll the serial line, I suppose).

MATLAB Support Package for Arduino (aka ArduinoIO Package) allows you to do it fairly easily.

  Sample usage:

  %-- connect to the board

  a = arduino('COM9')

  %-- specify pin mode

  a.pinMode(4,'input');

  a.pinMode(13,'output');

  %-- digital i/o

  a.digitalRead(4) % read pin 4

  a.digitalWrite(13,0) % write 0 to pin 13

  %-- analog i/o

  a.analogRead(5) % read analog pin 5

  a.analogWrite(9, 155) % write 155 to analog pin 9


Heads Up Display Helmet With arduino I want to make a HUD Helmet similar to the one shown in Ironman movies. Please suggest me some links and parts needed for this type of project

There is a fairly inexpensive solution, but it's not Arduino based.

All you need is:

the Google Cardboard sdk
a fairly modern and powerful Android phone (I have a OnePlusOne and it works well with Cardboard apps) - assuming you already own something similar, this is where the big saving happens :-)
a compatible head unit: there are many available on ebay (on some you might have to drill a hole where the camera of the phone is located.) price got from about $5 to $25
some high level programming skills to write your augmented reality application, but there's no way around it :-) - you might even find some demo on the net.

Here the basic of the solution I'm proposing is to take the video stream from the front camera on the phone, use the CardBoard API to create a view for each eye (yes, you will loose stereoscopy, since each eye will see the same image from the camera) and overlay it with whatever info you would like to show. The simpler case could be a compass, where you show N-W-S-E at the top of the field of view. Or you could even add a map, like in a FPS :-)

The part where the arduino might come useful is if you want to create some (bluetooth, for example) sensor and/or controller (using the usb port from the phone requires both a phone with HW that supports host mode and a rooted device).


Configuring Accelerometer on BNO055 sensor I'm using the BNO055 9DOF Adafruit sensor to measure the acceleration/orientation. How can I change the configuration of the accelerometer from 4G (default) to 16G?

What I already know:

The datasheet : https://cdn-shop.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf

From point 3.5.2 from page 27, I need to change xxxxxx01b to xxxxxx11b in the configuration file (that is the library). I use https://github.com/adafruit/Adafruit_BNO055 but I could not find any information on what to change and where in the .h file.

Any ideas?

Thank you

This was partly discussed as an issue on the library's github

https://github.com/adafruit/Adafruit_BNO055/issues/48

Here's how I understand it:

The library doesn't configure the registers you want. I don't see a reference to writing to the ACC_CONFIG register (address 8). Not even defined in the header.

The sensor has two register-pages (0 and 1) [refer page 50]. I.e. if you select page 0 then the register at address X means something, at page 1 it means something else.

We want to write to ACC_Config at address 0x08 on Page 1.

Page 77 tells us that, regarding writing to the register: "Write: can only be changed in sensor mode, see section 3.5.2"

In code, you could hack something in there:

https://github.com/adafruit/Adafruit_BNO055/blob/master/Adafruit_BNO055.cpp#L115

After changing to the sensore mode, you could then write to the register as

//values taken from section 3.5.2 page 27
#define BNO055_ACC_CONFIG_2G (0) //0B00
#define BNO055_ACC_CONFIG_4G (1) //0B01
#define BNO055_ACC_CONFIG_8G (2)  //0B10
#define BNO055_ACC_CONFIG_16G (3)  //0B11

//bandwidth definitions
#define BNO055_ACC_BW_7_81_Hz (0)
#define BNO055_ACC_BW_15_63_Hz (1)
#define BNO055_ACC_BW_31_25_Hz (2)
#define BNO055_ACC_BW_62_5_Hz (3)
#define BNO055_ACC_BW_125_Hz (4)
#define BNO055_ACC_BW_250_Hz (5)
#define BNO055_ACC_BW_500_Hz (6)
#define BNO055_ACC_BW_1000_Hz (7)

//powermode definitions
#define BNO055_ACC_PWRMODE_NORMAL (0)
#define BNO055_ACC_PWRMODE_SUSPEND (1)
#define BNO055_ACC_PWRMODE_LP1 (2)
#define BNO055_ACC_PWRMODE_STANDBY (3)
#define BNO055_ACC_PWRMODE_LP2 (4)
#define BNO055_ACC_PWRMODE_DEEP_SUSPEND (5)

#define BNO055_ACC_CONFIG_ADDR 0x08

//Select page ID 1 to write to the right register
write8(BNO055_PAGE_ID_ADDR, 1);
//build the config value with bitshifts
//see page 77
//use all standard values except 16G parameter
uint8_t acc_config = (uint8_t)((BNO055_ACC_PWRMODE_NORMAL << 5)
                   | (BNO055_ACC_BW_62_5_Hz << 2)
                   | BNO055_ACC_CONFIG_16G);
//write new accelerometer config
write8(BNO055_ACC_CONFIG_ADDR, acc_config);

//change back to page ID 0 (or whatever was before there)
//Otherwise we read sensor data from the wrong page with entirely different meaning
write8(BNO055_PAGE_ID_ADDR, 0);

Since I don't have that sensor here I have no way to test it. So this is just the basic idea. You can also read registers with read8, with which you can verify that before you write anything to the register, it has some standard (or expected) value. E.g., ACC_CONFIG should read as 0B00001101 = 0x0d. And after you write a value there you should be able to read the same value back, otherwise the chip didn't let you execute the write and you have to investigate why.

Yes, you mostly have to do the hard work by yourself. Changing from 4G to 16G might also have the implication that some other calculations on the raw data has to be done different, however I am not sure of that.


How to change LDR output in simulator 123D Circuits? I used simulator 123d.circuits.io to create simulation of basic circuit with LDR: LDR is connected to 5V and via 10K resistor to GND. Wire between LDR and resistor is connected to analog pin where I read ADC values and display them using serial monitor. This works fine. But I would like to how to change lighting level of LDR in simulation because this way LDR shows still the same value. I tried putting LED or light bulb near LDR but it doesn't seem to have any influence. Any ideas?

Ok, so I found it myself. You can click on LDR during simulation and bar to adjust lighting appears above it.


Interrupts on the Arduino NG I am a newbie to using arduino.

I am using an arduino NG  (using an atmega8). One of the pins is a button that triggers an interrupt.

The problem I am trying to solve is that I want an arduino NG to store the timestamp (we are using mills as a timer -no need to consider the 50 day rollover error here) when the interrupt pin is pressed.

The timer of the interrupts in milliseconds is stored in an array and there are up to 100 such interrupt button presses.

After searching around I didnt find any information for using interrupts with atmega8 on arduino NG (though there is information of how to use interrupts on atmega168 with arduino NG ).

So my question is: Is this problem solvable with an atmega8 arduino NG? Does the atmega8 arduino NG have interrupts? Just need one interrupt. And what would be the code to read an interrupt on atmega8 version of arduino NG?

Does the atmega8 arduino NG have interrupts?-

Page 1 of the datasheet:

Yes, it has interrupts.

  just need one interrupt.

Page 46 of the datasheet:

It looks like you have 19 of them.

  regarding interrupts atmega8 is different168 there-so that may imply the the same code wont work -and I couldnt find any examples when searching

Try using the Arduino libraries. If that doesn't work post your code.


Getting individual outputs from 4 load cells This is my first time using an Arduino, and I want to connect 4 load cells to one Arduino board and then get 4 separate outputs for each load cell on a computer.
What would I need to accomplish this and how would I set it up?
Can all four load cells connect to a single Arduino?

Also, could I get it to work with these load cells in particular:

https://www.amazon.co.uk/HALJIA-Weighing-Resistance-Half-bridge-Original-Silver/dp/B0792WCGJC/

or would I have to use ones with a 4 wire output?

For this purpose there are 'simple' interface boards like the HX711 (google on HX711). A guy named Bogde has written an Arduino library to manage this board which you can find on GitHub (https://github.com/bogde/HX711). There you can also subscribe to the corresponding email group, which is rather lively and also handles similar questions as yours.

Also Sparkfun sells these sort of interface boards and has very good and extensive documentation and tutorials on the site (see comment from VE7JRO below your question).

You can manage 4 load cells with one Arduino depending on the frequency with which you want to read them. If all 4 load cells are used to weigh one platform then Sparkfun sells an interface board to combine them in one "weight sensor" making it even more simple to interface with the Arduino.


use arduino IDE for USB isp programmer A few years ago I programmed AVR ATmega8 with AVR studio by USB isp programmer.
I was using C language. Now I would like to use arduino(C++) langauge and my external USB isp programmer. Is it possible?

The Arduino IDE compiles and outputs standard Intel HEX format files that are compatible with (nearly?) all programmers. If you enable detailed logging in the preferences panel you can find out which directory the IDE is building your code in and if the IDE does not include specific support for your programmer you can then locate the .hex file and upload it using the tool you are familiar with. The projects are typically built in a build.* subdirectory under %TEMP% (or /tmp on unix).


"Stand-alone" serial monitor I usually use Platformio as IDE for my Arduino projects. I like it as an editor, but I don't like its serial monitor feature. So I often open the Arduino IDE in background to use its serial monitor, but this has some drawbacks (including a significant increase in my computer's CPU usage and battery consumption).

Is there an Arduino-compatible serial monitor application that just works as a serial monitor (and not also as an IDE)? I'm most interested in a MacOS application, but if you know a Windows one please tell me as well.

I use CoolTerm, which is available for Mac, Windows and Linux. It is a great serial app, and you can have several windows open at the same, for each serial pipe you may be using (Bluetooth, Arduino Serial, etc).


Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library) I've been using the Arduino IDE for some time now, and I want to shift to coding for the bare AVR microcontroller. So I wanted to begin by porting required arduino libraries to C/C++.
I started with the Radiohead library, but I've noticed a lot of variables/tokens that are directly used without a definition for them. For example:

    // path :RadioHead/RH_ASK.cpp
#if (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
 #ifdef RH_ASK_PTT_PIN
    RH_ASK_PTT_DDR  |=  (1<<RH_ASK_PTT_PIN);
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #else
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #endif
#else
    // Set up digital IO pins for arduino
    pinMode(_txPin, OUTPUT);
    pinMode(_rxPin, INPUT);
    pinMode(_pttPin, OUTPUT);
#endif

None of the tokens in this snippet like "RH_ASK_PTT_PIN" or  "RH_ASK_TX_PIN" were mentioned anywhere in the code before or any other file that was included.

I understand what the code does, but how does the compiler know what these tokens mean? I tried to compile this code using Atmel Studio but it gives me an error (As it should):
"RH_ASK_PTT_PIN" not declared in this scope
So how does this library work with the Arduino IDE?

Link to the library : https://github.com/PaulStoffregen/RadioHead

Also can someone suggest tags for this post? Its my first post here.

They're not defined. If you notice that whole block is wrapped in a #ifdef which will be false unless you're on some specific platform, where the platform defines those macros.

Everything else uses the last little bit:

pinMode(_txPin, OUTPUT);
pinMode(_rxPin, INPUT);
pinMode(_pttPin, OUTPUT);

You only need to care about that bit - nothing else is of any concern unless you're using a "RH_PLATFORM_GENERIC_AVR8" (whatever that is).


Why my 4WD Bluetooth car run so slow Code

/*Arduino Bluetooth Controlled Car
 *  * Created by Glen Tech
 * https://www.youtube.com/glentech
  */

#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

char command;

void setup()
{
  Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
}

void loop(){
  if(Serial.available() > 0){
    command = Serial.read();
    Stop(); //initialize with motors stoped
    //Change pin mode only if new command is different from previous.
    //Serial.println(command);
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(1000);//Define maximum velocity
  motor3.run(FORWARD); //rotate the motor clockwise
  motor4.setSpeed(1000);//Define maximum velocity
  motor4.run(FORWARD); //rotate the motor clockwise
}

void back()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(1000); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(1000); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void left()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(FORWARD);  //rotate the motor clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(FORWARD);  //rotate the motor clockwise
}

void right()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void Stop()
{
  motor1.setSpeed(0); //Define minimum velocity
  motor1.run(RELEASE); //stop the motor when release the button
  motor2.setSpeed(0); //Define minimum velocity
  motor2.run(RELEASE); //rotate the motor clockwise
  motor3.setSpeed(0); //Define minimum velocity
  motor3.run(RELEASE); //stop the motor when release the button
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}

I can't find issue in your code that I'm convinced is your problem. Without seeing your datasheet for the motor, I would bet your issue is one of two things:

1) A 9V battery is low-current relative to most batteries I've used for powering any decent DC motors. Do you have access to a better current source you could try?

2) Every motor has a trade-off in torque vs max-speed, dictated by the internal gear-ratio. Depending on the motor type, it may not have the torque to accelerate the vehicle to a significant speed.


Engraving machine with arduino I'm trying to control an engraving machine with an Arduino Uno. I don't have so many knowledges in electricity so I'm trying something very simple. I think my program is OK but I have no idea how to plug the wires. I just want to mark non-stop
-Send a 250ms signal to the marking Input of the machine

-Marking.

-Waiting for output "Ready to mark" from the machine

-Wait 1 s

-Send a 250ms signal...ETC

These are the I/O of my machine:

and this is my program :

I need to send 20V to the inputs of my machine. How is it possible : I know that my company does it without external power supply and the arduino is just plugged on the I/O and the USB.

Can you help me ?

Thank you in advance.

I need to send 20V to the inputs of my machine. How is it possible

You need some form of power supply for that. It is not possible to
send 20 V from the Arduino directly.

  I know that my company does it without external power supply

Then you misunderstood something about either the electrical interface
of the machine, or about how your company connects it to the Arduino.

One possibility is that the machine inputs are 20 V logic with
built-in pull-up resistors. This kind of input is normally meant to
be driven by an open collector output. If this is the case, then you
can drive those inputs from the Arduino through a transistor (either an
NPN or an N-channel MOSFET) with no external supply.

But this is only a guess. What you really need to do is read the
datasheet of the machine and see how those inputs are meant to be
driven, at the electrical level. It may be more efficient to find
someone at your company who knows already and can explain that to you.


RF24 library commands, channel, and address I'm trying to use the RF24 library for wireless communication.
However, it appeared that this library does not have "help" option.
There was a keywords file but it did not explain what it does.
I found couple of examples online, and in the library, but id did not explain things quite in detail.

Could you explain to me how those command works, and weather there's any help file for the library?

Especially, I have a question about the channel and address used in the library.

A. Does address take character or number as input?
The official example in the library used

byte addresses[][6] = {"1Node","2Node"};

But I also say some example use

byte addresses[][6] = {"00001","00002"};

The byte command was suppose to be a 8-bit unsigned number, from 0 to 255, but why they used string " " as input?

I found a sentence in RF24.h file: Addresses are assigned via a byte array, default is 5 byte address lengths. But why they wrote byte addresses[][6] instead of byte addresses[][5]?

B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

setChannel  KEYWORD2

The pin was explained in RF24.h. However,

Can one open multiple channel at once?
If one use the same addresses in multiple channel at once, can the address being distinguished, or were they treated as the same address?
Is channel-pin/port(while writing)-address a tree structure?

C.
Can one open up more pin/port in transmitting and writing?

  openWritingPipe   KEYWORD2
  openReadingPipe   KEYWORD2

A. Does address take character or number as input?

The address is 5 bytes. In this library it is provided as an array. In C a string is merely an array of bytes. So it is possible to represent an array of bytes as a simple string. Internally the two representations:

byte address[] = "123ab";

and

byte address[] = { '1', '2', '3', 'a', 'b' };

and even:

byte address[] = { 0x49, 0x50, 0x51, 0x97, 0x98 };

are all identical, except that the first one adds an extra 0x00 to the end of it to mark the end of the string (which the library completely ignores).

  B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

It's helpful here that you have some understanding of basic radio communication terminology.

When you say that a device works at X frequency you are generally only referring to the "frequency band" that the device operates within (2.4GHz in this case). The device doesn't work at 2.4GHz - only "in the 2.4GHz band". That frequency band is then divided up into channels. Each channel is a specific frequency. Just like your television has channels you select one specific channel (and thus frequency) to tune into and communicate on.

Channel numbers are just used because it's far far easier to remember "channel 21" instead of 471.25MHz, for example.

For two devices to be able to communicate they both need to be tuned to the same frequency, and hence the same channel.

The "address" is more like the address your computer has on the network. Within the channel frequency you can have multiple devices communicating. The address identifies exactly which of the devices you want to send data to or are receiving data from.

  C. Can one open up more pin/port in transmitting and writing?

The nRF24L01 internally uses pipes as a method of separating data from different devices into distinct feeds that you can read from. It is merely for convenience. You can open up to 6 pipes at once, each one receiving from a different address. All pipes are in the same channel though since you can only tune to one channel at a time.

By the way - the keywords.txt file exists solely for the IDE to do highlighting of certain words. It's not meant for a human to read when working out how to use a library.


How to use map function if(pin10==HIGH)
  val=analog.read (potpin);
  val=map(val,0,1023,0,180);
  servowrite(val);
else
  val=map(0,1023,0,90);
    servo.write(val);}

It looks like you're using pin 10 to indicate whether sweep your servo through 180-degrees or through 90-degrees. Is that correct? Then you only need the if/else statements to select one of the two 'map()' calls. I see several problems:

Your indentation suggests you tried to select 3 statements with your 'if', but an 'if' only refers to one following statement or block of statements. If you want it to control a block of statements, you need to surround those statements with braces: '{' and '}'.
In this case, you need everything but the 'map' calls to be outside the 'if' statements.
Statements (except 'if' and 'else' by themselves) need to end with a semi-colon.

I think you meant to write:

val=analog.read (potpin);     // read the pot

if(pin10==HIGH)               // pin 10 selects servo range
  val=map(val,0,1023,0,180);  // map the pot value ...
else                          //   into one of
  val=map(0,1023,0,90);       //   the servo ranges

servowrite(val);              // drive the servo

Update:

  I had try every thing , but there is some shaking and vibration when
  if condition is satisfied.

Was the shaking near rotation limits? Most servos, especially the inexpensive hobby ones, get unstable near each end of their travel. Some will move smoothly to the limit, others get shaky within a few degrees of the limit. Each one is a little bit different.

Update 2:

Here is a complete, working example based on the Arduino Servo-example and your specifications. There were two bugs above:

I left out the 'val' argument in one of the map commands. This cause a compile error and should have prevented you from testing it. It could not have run, properly or improperly.
In your code example, if(pin10==HIGH) doesn't read any input pin! It just reads some (unseen!) variable named 'pin10' - unless you did read the pin in some code you didn't show us? Which is why we ask for a minimum, complete, & verifiable example.

This code runs and rotates my sg90 servo through 90 degrees, if pin 10 is low, or 180 degrees, if pin 10 is high.


Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values Any advice on what coding to adjust. New to Arduino.

const int sensorPin = A0;
float voltage=0.0;
int sensorVal=0;
int heartbeats=9;
float BPM=0.0;
const int led1=2;
const int led2=3;
int starttime = 0;
boolean counted = false;

void setup() {
pinMode(sensorPin, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
boolean counted = false;
}
void loop() {

starttime = millis();
while (millis()<starttime+10000)
{
  sensorVal = analogRead(sensorPin);
  if (sensorVal >550 && counted == false)
  {
    counted = true;
  }
  else if (sensorVal < 500)
  {
    counted = false;
  }
}

    BPM = heartbeats*6;
 Serial.println("Your BPM is");
 Serial.println(BPM);
BPM =0;
heartbeats =0;

}

There's two basic methods of measuring a frequency, which is basically what you are trying to do.

There is Frequency Counting and Frequency Timing. The latter involves measuring the time between successive pulses and calculating the instantaneous frequency from that. Good for rapidly changing frequencies where you need to know the frequency right away.

Frequency counting is what you are attempting, and is basically counting the number of edges that occur within a certain timeframe.

However your method is slightly flawed: chiefly because you forgot to actually count the edges. You wrote some reasonable code for finding an edge, but failed to actually do anything with that edge.

Also your code is blocking for 10 seconds, which may be fine in this scenario, but is not a good habit to allow yourself to get into.

Instead you should consider something more like this:

void loop() {
    static int count = 0;
    static bool counted = false;
    static uint32_t ts = millis();

    int val = analogRead(sensorPin);

    if ((val > 550) && (counted == false)) {
        counted = true;
        count++;
    } else if (val < 500) {
        counted = false;
    }

    if (millis() - ts >= 10000) {
        ts += 10000; // You could assign ts the millis() value, but
                     // by adding 10 seconds it cancels any drift
                     // caused by other delays in your sketch.
        int BPM = count * 10;
        count = 0;
        Serial.print("BPM: ");
        Serial.println(BPM);
    }
}


ATTiny85 USB Troubleshooting. Device is not recognized when programmer asks to plug in device I have bought this cheap AVR Programmer Board and I thougth that I would be OK just plugging it into my USB port. Then after I did that nothing happened so I passed last 4 hours trying to understand what was going wrong. I learned that ATTiny85 microchips often come with no bootloader.

So first I tested it with Arduino as ISP and simple blink code. It worked. Then I downloaded micronucleus and i flashed it via Arduino as ISP. I think this process worked pretty well as the output show
> avrdude -C ../etc/avrdude.conf -c arduino -p t85 -P COM3 -b 19200 -U flash:w:/micronucleus/firmware/releases/t85_default.hex

 avrdude: AVR device initialized and ready to accept instructions

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

 avrdude: Device signature = 0x1e930b (probably t85) avrdude: NOTE:
 "flash" memory has been specified, an erase cycle will be performed
          To disable this feature, specify the -D option. avrdude: erasing chip avrdude: reading input file
 "/micronucleus/firmware/releases/t85_default.hex" avrdude: input file
 /micronucleus/firmware/releases/t85_default.hex auto detected as Intel
 Hex avrdude: writing flash (8166 bytes):

 Writing | ################################################## | 100%
 0.09s

 avrdude: 8166 bytes of flash written avrdude: verifying flash memory
 against /micronucleus/firmware/releases/t85_default.hex: avrdude: load
 data flash data from input file
 /micronucleus/firmware/releases/t85_default.hex: avrdude: input file
 /micronucleus/firmware/releases/t85_default.hex auto detected as Intel
 Hex avrdude: input file
 /micronucleus/firmware/releases/t85_default.hex contains 8166 bytes
 avrdude: reading on-chip flash data:

 Reading | ################################################## | 100%
 0.09s

 avrdude: verifying ... avrdude: 8166 bytes of flash verified

 avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

 avrdude done.  Thank you.

Problem that I'm now facing is that when I try to upload a code using ATTiny Development Board via arduino IDE (selecting Attiny85 digispark default 16.5mhz) and it asks me to plug in the device, device is not recognized.
I already installed drivers downloaded from github release section of DevicestumpArduino repository, tried installing micronucleus configuration driver via zadiag like i read in this question but nothing worked.
What am I missing?

From your AVRDude output:

avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

It does not appear that you have programmed the AVR configuration fuses.
One for thing, E:FF, is extended fuse value 0xFF, which is missing the SELFPRGEN (self-programming) fuse that would allow Micronucleus to load your code onto the AVR, that is allow the AVR to execute instructions to program itself.  So, assuming it managed to show up on USB, you wouldn't actually be able to use it to put code on your chip.
You can see what they should be where the makefile fuse target defers to your t85_default configuration:
FUSEOPT = -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m

The fuses that are actually preventing it from showing up on USB are more likely the clock related fuse bits in the low fuse byte.  In particular CKDIV8 (factory default) is set to divide-by-8 where it is not in the makefile.  The CKSEL bits are set to 0x2 (factory default) for the 8Mhz internal RC oscillator whereas the makefile wants them to be set to 0x1, for internal PLL (phase locked loop) that generates higher clock rates from the RC oscillator.  In short, your chip is running at 1MHz rather than 16Mhz.  The Micronucleus code may also be written such that it needs PLL for bit-banging USB, though I haven't looked into that to be certain.


Forensic security of Arduino (SRAM) Pardon the double post, but I'm not getting much traction with this question over at arduino.cc so I'm looking for answers here now.

Original post: http://forum.arduino.cc/index.php?topic=391698.0

  I get the idea of uploading a "stop" sketch for the purpose of
  overriding a previously uploaded program in Flash memory space.

  Then of course we have EEPROM for "long-term" storage.

  However, let's say an Arduino: Read user input as secret key and store
  in memory (SRAM) Performed a signing operation with secret key
  Subsequently powered off

  We know that computers introduce a wide range of complications to
  security because data can still be recovered, even after being erased
  or overwritten in some cases, variables stored in memory float around
  (unless pinned for decryption in SecureString contexts, etc.), etc.

  To establish context for the following questions, let's [overly]
  simplify the attack vector in saying this would be a scenario where an
  Arduino used in a security application is physically disconnected,
  stolen, and then powered on sometime later.

  Question 1: Obviously we're not talking about storing keys on disk
  necessarily (i.e. EEPROM). How likely (or difficult) would it be to
  analyze SRAM with the intent to recover keys that may have been
  previously stored in memory?

  Question 2: Similarly, let's say sensitive information was in fact
  stored in EEPROM.  Does the same hold true of data previously stored
  in EEPROM that has since been overwritten with new (i.e. zero) data?

Any help would be greatly appreciated. Thanks!

RAM memory looses its contents when it's powered off. However, this
natural erasure process is not instantaneous: it can take several
seconds, or even minutes. It has been demonstrated that cooling down a
memory chip can extend its data retention time to hours, which enables
a type of attack known as cold boot
attack.

This type of attack has been studied mostly on DRAM computer modules.
The Arduino memory, however, is based on SRAM, which is physically very
different from DRAM (a transistor feedback loop vs. a capacitor). There
seems to be very little research on cold boot attacks against SRAM. I
found nonetheless a technical report from the computer laboratory of the
University of Cambridge: Low temperature data remanence in static
RAM, by Sergei
Skorobogatov. Quoting from the conclusion:

  Contrary to the established wisdom, there are several chips that
  retain data for dangerous periods of time at temperatures above −20°C.
  The temperature at which 80% of the data are retained for one minute
  varies widely between devices. Some require cooling to at least −50°C,
  while others retain data for this period at room temperature.
  Retention times can be significantly reduced by shorting VCC to ground
  rather than by leaving it floating.

From this perspective I would say that, although the attack seems non
obvious, your secret key is not completely safe even in SRAM. Since the
data retention time varies widely between devices, it could be worth
testing on your Arduino. If possible, I would suggest you overwrite the
key after the signing operation.

Update: I did a quick test on my Arduino Uno, at room temperature,
by just unplugging and plugging back the board. Here is my test code:

// This memory buffer will not be zeroed at startup by the C runtime.
uint8_t __attribute__((section(".noinit"))) buffer[1024];

void setup()
{
    Serial.begin(9600);
    Serial.println(F("Program started."));
}

void loop()
{
    switch (Serial.read()) {
        case 'i':  // Initialize the buffer with pseudo-random bits.
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++)
                buffer[i] = rand();
            Serial.println(F("Buffer initialized."));
            break;
        case 'f':  // Report number of flipped bits.
            int count = 0;
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++) {
                uint8_t mask = buffer[i] ^ rand();
                while (mask) {
                    count += mask & 1;
                    mask >>= 1;
                }
            }
            Serial.print(F("Flipped bits: "));
            Serial.print(count);
            Serial.print(F(" / "));
            Serial.println(8 * sizeof buffer);
    }
}

And this is the output, with my comments on the right:

Program started.            ← fresh boot
Buffer initialized.         ← pressed 'i'
Program started.            ← pressed the reset button
Flipped bits: 0 / 8192      ← pressed 'f'
Program started.            ← unplugged and plugged back
Flipped bits: 4166 / 8192   ← pressed 'f'

It appears the RAM is preserved across a warm reboot (pressing the reset
button), but it is completely lost after a power cycle: half the bits
flipped is a total loss of information. I tried to do this as fast as I
could, which is slightly less than one second. It would seem the SRAM in
the ATmega chips decays pretty fast, at least at room temperature.

Update 2: I found an enlightening story about an unpowered AVR
keeping data in RAM for more than 10 minutes, but only on mornings:
The mystery of the Zombie
RAM.


NodeMCU V2 ESP8266 - Use 5VIN as power for heater of a MQ-9 Sensor Right now I'm trying to understand how I could (easily) power the heater of my MQ-9 carbon monoxid and gas sensor.

Here is the datasheet: http://www.haoyuelectronics.com/Attachment/MQ-9/MQ9.pdf

It needs 5V for some gases, so I thought I could maybe power the heater via the 5VIN pin (while plugged via usb), since the other output pins have a max. voltage of only 3.3 V?

And to control the power, I could then add a relay switch, which would cut the circuit between heater and VIN (if I only want to measure the gases)?

Or am I completely wrong?

P.S: And no - I don't want to add a 5V power supply additional to the normal USB plugging on VIN :)

The VIN pin is NOT directly connected to the USB's 5V supply as it is an VIN PIN for powering the MCU from an external source other than the USB - this means the pin cannot be used as a 5V supply output.

Never ever connect VIN to a power source AND connect the USB plug. That can destroy the USB port in your computer. There is zero back-powering protection on the MCU board.

According to the datasheet the sensor (heater) needs upto 350mW which IMHO makes powering via an extra power board (which can also power the MCU) a necessity.


Using HC-SRO4 sensor and looking for obstacle I am working in TinkerCAD, I want to design and simulate a circuit in which there are following components: 1.)An Arduino board. 2.)A potentiometer 3.)An HC-SRO4 sensor 4.)An LED.
So, the sensor should be able to tell if the range that has been set via the potentiometer has any objects in it or not. And if there are one or more objects in that range then the LED should also light up. Also, the user should be able to change the range using potentiometer during simulation.
I have attached the code here, but for some reason, I don't feel satisfied. Here is a list of the possible reasons. 1.) For LED lightening up, I had to use another if else , since it was showing an error else used without a previous if if I used LED in the same if else2.) The theoretical range for the sensor I have used is 2cm-400cm but in my circuit, it was not showing the upper range as 400cm.
Please tell the possible solutions. Also, can I improve my code and circuit

Here is the code which I used.

const int echoPin = 6;
const int pingPin = 7;

void setup()
{
 Serial.begin(9600);//Starting serial terminal
}

void loop()
{
  int sensorValue = 0;//Setting variable
  int mappedValue = 0;
  const int potentiometerRange = 0;//setting the buttons to variables to avoid confusion.
  long distance;//declaring a varible in loop because we can change the range during runtime.
  long actualDuration;//...
  long duration;
  pinMode(A0,INPUT);
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);//
  sensorValue = analogRead(potentiometerRange);//reading the potentiometer value.
  mappedValue = map(sensorValue,0,1023,2,400);//mapping the value accordingly for ultrasonic sensor.
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);//to ensure a clean high pulse later
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);//to trigger the ping.
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);
  pinMode(echoPin,INPUT);//noe echo which tuns low in the time when waves return back.
  duration =  pulseIn(echoPin,HIGH);//time calculated by sensor
  //calculation of distance from any object
  actualDuration = duration/2;//reducing the time in half for the distance is half only.
  distance = 0.0343*actualDuration;//keeping in mid that speed of sound is 343 m/s and pulseIn returns time in microseonds.
  if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);
   delay(500); // Delay a little bit to improve simulation performance
}

I'm also attaching the picture of my circuit.

There's not much code there, so not much to optimize. I will however show you how to combine your two ifs.

You have:

if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);

and I guess you tried this:

if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
  else
    Serial.println("NO");
    digitalWrite(11,LOW);

That would be correct in Python where the indenting matters (oh how that brings back the PTSD of having to work with COBOL...) but not in C.  In C indenting is ignored completely. It's only there for our benefit in reading the flow of code.

Instead to group statements together within an if or an else (or any other conditional or loop structure) you wrap those statements in a block. That is, place { before it and } after it.  Thus:

if(mappedValue>=distance)//checking if the object is in range
{
    Serial.println("YES");
    digitalWrite(11,HIGH);
}
  else
{
    Serial.println("NO");
    digitalWrite(11,LOW);
}

Or with my preferred formatting:

if(mappedValue>=distance) { //checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
} else {
    Serial.println("NO");
    digitalWrite(11,LOW);
}


Serial Data through Pin 13 LED I am looking to utilize Pin 13 and an external LED to flicker as either the Rx or Tx LEDs do when Serial data is transferred through the Arduino. The existing code is all in real time to function with external buttons, so there can't be any delay.

I came across this link which seems useful, but I can't quite get it to read from Serial:

http://arduino.cc/en/Tutorial/BlinkWithoutDelay

Thanks in Advance

If you are going to use an external LED, then using software to make the LED blink when the RX or TX line is busy is a waste of your CPU.

Instead, simply connect the LED to the RX or TX line using a transistor as a buffer to prevent the current draw from messing with the serial signal.

To borrow an image from this answer to a similar question:

You can try omitting the transistor buffer, but the serial waveform will be altered, possibly to the point where data becomes corrupted. The transistor prevents the current draw of the LED and resistor from loading down the RX or TX lines.


How is the diode here effective? I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.

Here is the schematic:

The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit.

According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)?

If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.

If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.

So how is this diode working?

Thanks!

Under normal operation the + connection of  any inductive component (motor, relay, etc) is at a higher potential than the - connection.

During a "back EMF" event (the collapsing of the magnetic field) a large voltage of the opposite potential is generated.  That means that the - connection suddenly becomes a much higher potential than the + connection.

That is very bad for anything connected to the - pin of the inductive load.

With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing.  However, when the - pin becomes a higher potential than the + pin the diode will become forward biased and start to conduct.  That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.

Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.

The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go.  It'll (crudely speaking*) take the shortest, quickest, route to get there.  That means it goes through the diode and nowhere else.  Straight from the black wire to the red wire of your motor.

* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route.  The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.


Receiving a packet via XBee radio I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:

Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(calculatePacketSize(data, XOR)); // Size of packet
Serial.write(unitInfo);
// Check if the data byte needs to be escaped
if(data == ESCAPE || data == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(data);
// Check if the XOR byte needs to be escaped
if(XOR == ESCAPE || XOR == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(XOR);

What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via Serial.available() whether or not there are enough bytes to process the payload during this run through of loop(). How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.

A state machine is what you want. That and to increase your preamble to two bytes, not one.  The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.

You should also (if needed) escape the packet size:

Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(PACKET_HEADER); // Packet header for synchronization
uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
if(ps == ESCAPE || ps == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(ps);
Serial.write(unitInfo);
... etc ...

You might like to abstract the escaping into a function:

void sendEscape(uint8_t c) {
    if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
    Serial.write(c);
}

Then you can just call:

sendEscape(calculatePacketSize(data, XOR));

etc.

Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as look for first preamble, look for second preample, look for size, look for id, and look for data. As bytes arrive they trigger the next state.

So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.

In pseudocode it may be something like:

State is idle.
If character available:
    Read character into variable C

    Select on state:
        State IDLE:
            If C is PACKET_HEADER:
                Set state to PREAMBLE
        State PREAMBLE:
            If C is PACKET_HEADER:
                Set state to GETSIZE
            Else
                Set state to IDLE
        State GETSIZE:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable SIZE
                Clear array DATA and prepare for reception
                Reset Seen ESCAPE flag if needed
                Set state to GETID
        State GETID:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable ID
                Reset Seen ESCAPE flag if needed
                Set state to GETDATA
        State GETDATA:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Append C to array DATA
                Decrement variable SIZE
                Reset Seen ESCAPE flag if needed
                If SIZE is 0
                    If checksum matches
                        Process packet
                    Set state to IDLE

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.

The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.


Can't figure out how to distribute the power so I'm making a project, kind of BB-8 droid replica, and I stumbled upon a problem. Since I am using two RC brushless motors, ESC's and batteries, I want to make my Uno board fed up from those batteries. Also, I want to use inductive charging set that would charge both batteries. Can anyone tell me or give some kind of scheme how should I distribute the power from batteries and what additional boards should I buy?

The best option is to connect the 5V/2A output of the UBEC to the 5V pin on the Arduino. In my experience, 7.4V is not enough to feed into the input jack on an Arduino especially if it is from a battery, as the voltage will drop when current is being drawn by other loads. I have built an Arduino controlled robot using a 6V NiMH battery and brushed DC gearmotors (so no ESCs or UBEC) and used a $5 5V 1A step-up/step-down converter so that even if the battery voltage dropped below 5V, it could still power the board. However, since you have a UBEC that is not in use, use it. Note that if you put voltage into the 5V pin, disconnect it when you are connecting the arduino over USB or you might damage your board.

As for inductive charging, I don't know of any off-the-shelf solution designed for charging a 2S lithium ion battery. The best option for charging would probably be an easy way to open the ball to access the batteries.


Adafruit Huzzah and SD card breakout I have an
Adafruit MicroSD card breakout board and an Adafruit Feather HUZZAH with ESP8266 WiFi
I wired that up according to this link's last picture.
The code I am using:

#include <SPI.h>
#include <SD.h>
...
const int chipSelect = 15;
...
Serial.print("Initializing SD card...");
pinMode(SS, OUTPUT);

if (!SD.begin(chipSelect)) {
     Serial.println("initialization failed!");
     return;
 }
Serial.println("initialization done.");
...

I always get the message "initialization failed", I also tried to format my SD card to be sure to have fat32 file system on it, but had no success with that.
What can I do to debug this error further?

TIA

From experience, I know the following

Using two SPI devices sometimes does not work, especially with fake SD breakout cards. Not sure about an Adafruit, but try to use only one SPI device at the same time (to check if it works better). For my project (initial setup), I had to use a SD logger extension board instead.
Sometimes it depends on the SD card which will work. Try to use older non SDHC/XDHC cards (smaller storage normally).
Use the most simple (and preferably example circuit) to test each component separately (thus your SD breakout card) before adding others (like the WIFI component). This rules out there is no problem with other components working at the same time.


How to turn servo to a specific location and then turn over I work on my first arduino car project and i want to turn my servo to a position with a letter input

This is my code so far

 #include <Servo.h>
Servo servo;

 void setup() {
 Serial.begin(9600);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
 }

 void loop() {

 if(Serial.available()>0){
 int  caz=Serial.read();
 switch(caz)
{
  case 'w':
      digitalWrite(8,LOW);
      digitalWrite(7,HIGH);
      break;
  case 's':
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      break;
  case'd':
       servo.attach(12);
       servo.write(0);
       break;
  case'a':
       servo.attach(11);
       servo.write(180);
       break;
   default:
       digitalWrite(7,LOW);
       digitalWrite(8,LOW);
       servo.attach(0);
  }
}

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .

And also i would like to do that to my motor , moving a bit when i input the key.

Rather than writing to 180 and 0 write to a variable.

static const int MovementAmount = 30; //degrees
int position = 90;  // 90 is the start position.
...
case 'd':
   servo.attach(12);
   position += MovementAmount;
   if (position > 180)
   {
     position = 180;
   }
   servo.write(position);
   break;


Convert float to hexadecimal value I am trying to convert a float value to a 4-byte hexadecimal value.

For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.

My program is:

void setup() {
  Serial.begin(9600);
  float z = 128;
  unsigned i;
  unsigned char *chpt;
  chpt = (unsigned char *)&z;
  Serial.print("Float Value             : ");
  Serial.println(z);
  Serial.print("4 Byte hexadecimal Value: ");
  for (i = 0; i < sizeof(z); i++) {
    Serial.print(chpt[i],HEX);
    //Serial.print(" ");
  }
  Serial.println();
}
void loop() {
}

My current output is:

Float Value             : 128.00

4 Byte hexadecimal Value: 00043

This value looks pretty correct to me. It is stored in little endian thou.

0x43000000 is the actual value.

Serial.print(x, HEX) truncates leading zeros. so 00 gets 0
So your output is 0 0 0 43 which corresponds to the little endian representation of the above.

Make yourself familiar with the floating point representation IEEE-754.

Also try the online FoatConverter.

Try the following:

char floatString[9];
sprintf(floatString, "%02X%02X%02x%02x", chpt[3], chpt[2], chpt[1], chpt[0]);
floatString[8] = '\0';
Serial.print(floatString);


SD Card store struct: force big-endian / little-endian? Following MAJENKO's tutorial on sd card file optimization and data integrity, can I force the SDCard to read and write in either big-endian or little-endian?

I need this in order to maintain backup data integrity across a wide array of IoThings, using various boards (Arduino UNO, MEGA, Nano, NodeMCU, etc) for future parsing.

Many full C libraries have an sys/endian.h header file. This defines a number of macros so you can find out what the endianness of your device is.  It also usually defines a number of handy macros that can convert the endianness for you.

htobe16(x)
htobe32(x)
betoh16(x)
betoh32(x)

These convert Host to Big Endian values and back again.

htole16(x)
htole32(x)
letoh16(x)
letoh32(x)

And these convert Host to Little Endian values and back again.

Not many embedded C libraries provide it, though, and not all that do provide the handy macros.

It's not too hard to implement yourself, but it does mean you deciding what to do depending on the target architecture. Which kind of negates the handiness of the endian.h file.

So really you want to re-implement the functionality in a form you can include in all your sketches.

Fortunately the compiler provides a set of macros defining the endianness that you can use though:

#define __ORDER_LITTLE_ENDIAN__ 1234
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __ORDER_PDP_ENDIAN__ 3412
#define __ORDER_BIG_ENDIAN__ 4321
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

So you can examine the __BYTE_ORDER__ macro to see what byte order it equates to and use that to select whether htobe32(x) has to do anything to the byte order or not.

In the PIC32 compiler it's done as a set of macros that either call swap32 / swap16, or pass the value unchanged:

#if __BYTE_ORDER__ == __LITTLE_ENDIAN__

#define htobe16 swap16
#define htobe32 swap32
#define betoh16 swap16
#define betoh32 swap32

#define htole16(x) (x)
#define htole32(x) (x)
#define letoh16(x) (x)
#define letoh32(x) (x)

#endif /* __BYTE_ORDER__ */

#if __BYTE_ORDER__ == __BIG_ENDIAN__

#define htole16 swap16
#define htole32 swap32
#define letoh16 swap16
#define letoh32 swap32

#define htobe16(x) (x)
#define htobe32(x) (x)
#define betoh16(x) (x)
#define betoh32(x) (x)

#endif /* __BYTE_ORDER__ */

So now depending on the byte order it will either swap the bytes around, or leave them unchanged.  It's now just a matter of implementing swap16 and swap32 - which I'll leave to you (hint: it just returns the value with the bytes in the reverse order - bit shifting and masking is good for that).

Then you need to decide on an endianness for your file.  Maybe choose little-endian since that is probably the most common.  So whenever you place a value into a struct for writing you pass it through either htole32(...) or htole16(...) depending on the data type.  Then whenever you read from a struct that has been read you pass the value through either letoh32(...) or letoh16(...) to get it in the host's endianness.


Problem with hc-05 bluettoth module I wrote a simple program for controlling an LED using mobile. So, I bought the HC-05 bluetooth module configured it and then connected it to  the arduino.

This is the code that I wrote for it.

int ledPin1=13;
int state;
int flag=0;

void setup()
{
    pinMode(ledPin1, OUTPUT);
    digitalWrite(0,HIGH);

    second:
    Serial.begin(9600);
}

void loop()
{
    if(Serial.available() >0)
    {
        state = Serial.read();
        flag=0;
    }
    if (state == '0')
    {
        digitalWrite(ledPin1, LOW);
        if(flag == 0){
            Serial.println("led off");
            flag=1;
        }
    }
    if (state == '1')
    {
        digitalWrite(ledPin1, HIGH);
        if(flag == 0){
            Serial.println("led on");
            flag=1;
        }
    }
}

Everything is working cool with the serial monitor. But, I'm not able to control it using my mobile. I gave an input 1 in serial monitor and if showed "led on". the same thing appears on the commanding interface of the app used in the mobile. So, the bluetooth is transmitting information from the arduino to mobile but I'm not able to send commands from the mobile and control the led. I tried using various apps like  Blueterm, Ardudroid etc but, the situation remains the same.

What am I doing wrong? Is there something wrong with the code?

I'm using Arduino Uno.

Your android app might be sending extra characters like "end of line", which will cause the return value of Serial.read() to be other than 1 or 0 after the first byte. Nevertheless, it looks like it should still turn on or off the LED as soon as it reads the first byte, and do nothing when it reads the following bytes. I have used the "hyperterminal rs232" app successfully to send single characters, maybe give that I try to see if it helps and ensure it is configured at the correct baud rate.

I would recommend to send back to the serial stream the characters read, to ensure they have been received correctly, so I would change this:

if(Serial.available() >0)
{
    state = Serial.read();
    flag=0;
}

to:

if(Serial.available() >0)
{
    state = Serial.read();
    Serial.print(state);
    flag=0;
}

Edit:

Just realised this in setup():

digitalWrite(0,HIGH);

You are setting the receive pin of the UART peripheral to hight, so that is probably why you are not reading data from your phone.


Power Source for Arduino So I have SIM900 Shield and Arduino Uno and they have both power jack, is it possible to power one of them using one power jack and connect it's power with another? If it is possible, I sincerely need the explanation.

I've research about the VIN pin of Arduino but I didnt quite get it and can't take the risk that I might fry the board since Im new here.

It depends on what voltage the devices run at and what their current draw is from the power supply versus what voltage & current your power supply provides.

If everything runs at 3.3V or 5V and minimal amps then you're good to go.

Read the datasheet for each device and for your power supply.


Arduino Mega web server always returning JSON data even if JSON is not passed in URL I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.

if (client) {
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  boolean sentHeader = false;
  while (client.connected()) {
    if (client.available()) {
      // client data available to read
      char c = client.read(); // read 1 byte (character) from client
      // buffer first part of HTTP request in HTTP_req array (string)
      // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
      if (req_index < (REQ_BUF_SZ - 1)) {
        HTTP_req[req_index] = c; // save HTTP request character
        req_index++;
      }
      // last line of client request is blank and ends with \n
      // respond to client only after last line received
      if (c == '\n' && currentLineIsBlank) {
        if (!sentHeader) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
        }
        // Ajax request - send JSON output
        if (util::StrContains(HTTP_req, "json")) {
          // Spit out JSON data
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: ArduinoMega");
          client.println("Connnection: close");
          client.println();
          client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
          client.print(tempInC);
          client.print("\"}]}");
          client.println();
          break;
        } else {
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close")); // the connection will be closed after completion of the response
          client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
          client.println();
          sentHeader = true;
          client.println(F("<!DOCTYPE HTML>"));
          client.println(F("<title>"));
          client.println(F("Welcome to Arduino WebServer</title>"));
          util::printProgStr(client, htmlStyleMultiline );
          client.println(F(""));
          client.println(c);
          client.print(F("
 LIVE:
"));

Please help.

So figured out the problem, the issue was  I was closing the connection instead when it was json fetched, I had to keep alive the connection.

so replaced client.println("Connnection: close"); with  client.println("Connection: keep-alive");

which fixed the problem.


For Arduino, is there a meaningful difference between carriage returns? Serial.write(0x0d); // hex

Serial.write(13);   // ASCII

Serial.write('\r');  // char

Is one more efficient? I read how it depends on the terminal program. So does that mean the IDE? (This is my first time working with serial comm.)

Is one more efficient?

after compilation it is same for all notations. the function and the value are the same for all 3 notations.


Releasing gas from a bottle via Arduino - opening a valve? I'm looking for a mechanical component that enables me to do two things:

contain a gas in a bottle and if opened, the gas should smoothly flow out (with the same pressure as a child blowing out candles on his birthday cake)
a valve for the bottle that can be opened by an Arduino when powered via USB

I already figured out that there are outlets for CO2 capsules. This could work, but then I'd need to figure out a way to decrease the pressure in order to receive a gentle gas flow.

Do you know any better approaches? Thanks in advance!

If you can tolerate a decreasing flow as the pressure in the bottle drops, a simple restrictor (fluidic equivalent of a resistor) will limit the flow but of course, I = E/R; the flow will be proportional to the bottle pressure. If that is acceptable, it is probably the cheapest, simplest, and most reliable way.


What is the best way/module to talk to an Arduino from far away (WIFI)? I am new to Arduino and IoT. I plan to build a product that I will connect to an app and they have to be able to communicate from a very far distance (kilometers).

Bluetooth is not a good option then (because the distance is too far). So would Wifi work? I read something about a module called esp8266 that might be what I am searching for.

The simplest option is to use GSM for the communication. Range isn't an issue, since point A isn't communicating with point B, instead point A and point B are both communicating via third party communication subsystem C which has a much greater coverage than anything you could build yourself.

I use GSM modules for communication with agricultural monitoring and control systems at remote locations. It works well, and you're pretty much guaranteed to have a signal.

For those times when GSM isn't a possibility (no signal, or the customer doesn't want the subscription cost) you really need line of sight between the two locations. Then you can use a highly directional antenna (e.g., parabolic dish or Yagi array) to extend any other suitable wireless communication signal over a long range (WiFi can reach tens of kilometres with parabolic dishes) and there are companies that specialise in that kind of equipment (such as this one that claims 8 mile range - of course you need two of them, one for each end of the link).  Of course, with some skill and determination it's possible to get incredibly long distances from WiFi. Not for your average user though...


NFC library for M24SR64 Im currently working on a project where i build an NFC device and needed some guidance in regards to the library needed for the NFC chip to work on the Arduino IDE. The chip is an M24SR64 chip and i've looked online for the library related to the chip but i couldn't find it. Although i did found a library for the M24SR64-y chip, though i'm not sure if its possible to use it, or whether it will work. If anyone has an idea or any help it would be much appreciated

Here you will find a lib for all M24SR NFC tags
In this test sketch you find details how to connect and test the tag with Arduino. If it helps mark as accepted to help others.


airduno mega 2560 and ESP8266-07 As I am really newbie in the programming stuff I have maybe stupid question:(
Is it possible to connect my airduno mega (collecting several data from sensors) via ESP8266-07 module to the internet to be able to upload data to ubidots?
Can somebody give me hint regarding connection both modules and programming itself?
Thanks Martin

Should be.  Googling the words "Arduino ESP Ubidots" gave many, many useful resources.


Getting incorrect output from ADC over SPI in Arduino Uno I am trying to read data from an ADC ADCS7476 (datasheet) using SPI on Arduino Uno. I am using the following code to read the data from the ADC and printing it on serial monitor. However, the code is always printing 0. I never used SPI before and I am not able to debug the issue, does anyone know where I am going wrong.

I am using the following connections:

ADC's SCLK to Pin 13 on Ardunio
ADC's SDATA to Pin 12 on Arduino
ADC's CS to Pin 10 on Arduino

Code:

#include <SPI.h>
#define cs 10

SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);
byte highbyte,lowbyte;
unsigned int data;

void setup() {
  Serial.begin(9600);
  pinMode(cs, OUTPUT);
  digitalWrite(cs, HIGH);
  delay(1000);
  SPI.begin();
}

void loop() {
  SPI.beginTransaction(settingsA);
  digitalWrite(cs, LOW);
  delayMicroseconds(1);
  highbyte = SPI.transfer(0xFF);
  lowbyte = SPI.transfer(0xFF);
  digitalWrite(cs, HIGH);
  delayMicroseconds(1);
  SPI.endTransaction();
  data= ((unsigned int)highbyte << 8 ) + lowbyte;
  Serial.println(data);
  delay(100);
}

I am leaving this answer in case anyone stumbles across this question in the future

In a super frustrating, anti-climactic end, it turns out that the ADC chip itself was not working properly. I tested the (faulty) chip using the code above and observed the output of data pin on the oscilloscope and the output was the same square wave irrespective of the input. I managed to find a new ADC and I tested it and it was working correctly. But this raises a new issue for me, this is the third ADC chip I tested that was working correctly, the first two were faulty. It is very unlikely that it is a manufacturing issue and I used the same connections and the same code to test all three of them. Maybe it has to something to do with soldering, because AFAIK that's the only thing that's different.  If anyone knows anything else that might have gone wrong, I'm all ears.