Serial input parallel output shift registers with arduino I need a way to rewrite the switch case part in a more efficient way.

int y , x ;
byte dataArray[6];

void setup () {
   pinMode(8,OUTPUT);
   pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);

   Serial.begin(9600);
   dataArray[0] = 0x3 ; //00000011
   dataArray[1] = 0x5 ; //00000101
   dataArray[2] = 0x9 ; //00001001
   dataArray[3] = 0x11; //00010001
   dataArray[4] = 0x21; //00100001
   dataArray[5] = 0x41; //01000001
}

void loop () {
   while (Serial.available()>0) {
     y = Serial.read();
     x = Serial.read();
     switch ( x ) {
     case 1:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     case 2:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     case 3:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 4:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 5:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 6:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     default:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;
     }
   }
 }

unsigned char i;

digitalWrite(8,LOW);
for(i=0;i<=6;i++){
    if(x+i==6) shiftOut(11,12,LSBFIRST,dataArray[y]);
    else shiftOut(11,12,LSBFIRST,0);
    }
digitalWrite(8,HIGH);
delay(10);
digitalWrite(8,LOW);


Are there any Wi-Fi modules for the Arduino Uno that may connect to an external Wi-Fi Antenna? I have an Arduino Uno I need to connect to Wi-Fi to make HTTP POST Requests to a Raspberry Pi Web Server.

The Arduino is located only about 30 feet from the AP, but there is a brick wall in the line of sight, and it is in a metal outdoor enclosure. For that reason, I wanted to attach an external Wi-Fi Antenna which would stick out a sealed hole in the enclosure.

I was contemplating using an ESP8266 Wi-Fi module, but it does not look like there is an easy way to attach the antenna.

What would be the best Wi-Fi module to which I could attach an external antenna for an Arduino Uno?

There are variants of ESP8266-based modules which include a connection for an external antenna. The ESP-02, ESP-05 and ESP-07 modules all feature a U.FL socket.

Effectively, they are an ESP8266 mounted on a carrier board with a U.FL socket.

If you already have some code to suit an ESP8266-based module, this will avoid having to rewrite for a different unit.


Can a Lithium Polymer battery charging circuit on Arduino boards also charge Lithium Lion batteries? I have a project that the form factor of 18650 batteries works well for. The board I'm using is a esp32 based board with built in battery charging:
https://www.amazon.com/gp/product/B072HBW53G/ref=ppx_yo_dt_b_asin_title_o00_s02?ie=UTF8&psc=1

I've heard that the flatpack type Lithium Polymer batteries have built in over charge circuitry. Is this generally true?
Can I directly charge a 18650 battery from Arduino type boards that have built in battery charging functionality?

EDIT:  So from looking at the battery circuit schematic from the Wemos link and the board itself it uses a TP4054 "Standalone Linear Li-lon Battery Charger with Thermal Regulation in SOT".  And since I can confirm the board works with 3.7V batteries and my 18650 is a 3.7V type I think I'm good.

EDIT:  Found info on this board:
http://www.raspberrypiwiki.com/index.php/WEMOS_ESP32_Board_with_OLED

Also by "Arduino type" boards I mean any popular micro controller board that has a battery charging function such as the Adafruit feather boards.

EDIT:  To clarify:
Reading here Li Poly and Li Ion batteries are essentially the same
https://scottiestech.info/2015/06/21/lithium-polymer-vs-lithium-ion-batteries-whats-the-deal/

I believe the board is a Wemos D32 with an attached display though I can't find any specific info on this exact board.
https://wiki.wemos.cc/products:d32:d32#technical_specs

I basically want to know if I can charge a Lithium Ion battery with this type of board.  As this is potentially a safety concern I wanted to ask some experts.

There are Lead based, Nickel-based and Lithium-based batteries (there are actually more, but these ones are the most popular). Each need a different charger, but since lithium polymer and lithium ion are in the same group, it should work but I don't have the option to test it out for you.

Q1: Not every battery has a built in over- and undercharge function. Some do, some don't. To find out if yours does, if the internet can't help, tear it apart (be extremely careful about it).

Q2: Depends what you mean by " built in battery charging functionality". If that includes the over- and undercharge functionality, then it will work (tested).

Looking at the board (https://wiki.wemos.cc/products:d32:d32#technical_specs) it seems doable.

The most important thing is to check, if the supported voltage of the li ion battery equals the supported voltage of the li polymer battery that can be charged with the li polymer charger. Since it says 3.7V on the data sheet, don't get a li ion battery with 3.7V+


Scale Magnometer to Servo I'm trying to determine what is the best way to scale a magnometer to a servo, I am using the BNO055 from Bosch I get a heading say 50 degrees, and I want to be able to input 45 degrees and have the servo motor move accordingly. I am using a 180 degree motor. I would like to be able to input 45 degrees, and then the motor if 50 degrees was 95, would decrease in value step by step until the magnometer read 45; I'm having difficulty creating the logic to do this.

Bosch output is between 0 and 360; so I could end up with servo 0 is 120; and servo 180 is 300. Meaning the values are 300 - 360, 0 - 120 making the full 180, so I am not sure how I could use something like map in arduino to solve this issue.

Okay, lets say the output of your BNO055 is called x and the value for your servo is y. We need to translate x to y and you are correct to use the map() function. But what you are forgetting is that you do not need to map all the values of x to all the values of y. You can split it up.

In your example the values of the BNO055 relate to the servo as follows:

x   | y
0   | 0
120 | 0
300 | 180
360 | 180

The servo only rotates from 0 degrees to 180 degrees between the BNO055 sensor values of 120 and 300. So you only need to map those values, while all values below should result in 0 and all values above should result in 180 degrees for the servo.

This translates into the following code:

//x is the output of BNO055 sensor
if(x < 120){
  servo.write(0);
}
if(x > 300){
  servo.write(180);
}
if(x > 120 && x < 300){
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

Another way of coding this is:

if(x < 120){
  servo.write(0);
}
else if(x > 300){
  servo.write(180);
}
else{
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}


Vibration sensor for arduino I need vibration sensor for my project. I have found many sensors similar to this one. But it seems, that this sensor outputs only zeros for "non-hit" state and ones for "hit state". And I need something that can output levels of vibration, not only presence/abscense.

So is there any high-resolution vibration sensor for arduino?

Thank you!

I assume the OP wants the frequency of the vibration, which an accelerometer such as the ADXL345 won't give.

I have two workarounds: if the expected vibration frequency is low, say, under 100Hz, use instead an on/off vibration sensor (adafruit has them for under a dollar) and count the number of transitions. If it's more, how about a microphone and a band-pass filter?


USB disconnects when using a capacitor I'm currently working with some WS2812B LEDs and tried out adding a capacitor to be safe from voltage spikes (was recommended by Adafruit). I noticed that a soon as I connect a capacitor between 5V and ground that the USB is disconnect from the PC (Windows Usb disconnect sound plays). I wondered why and tried another setup. This time just the capacitor between 5V and ground. Nothing else. According to my knownledge this isn't a short (capacitor is intact) and therefor this setup should be valid. Again the same thing happens: USB disconnects...

I really don't know why this happens but want to understand it. The capacitor I use is rated 16V 1000 mF (electrolytic in case this is relevant). The capacitor is also connected the right polarity. What forces the USB to disconnect (and let Windows play the USB disconnect sound). Am I may damaging the USB Port somehow and therefor a disconnect is forced as a security measurement?

Oh yeah... Using an Arduino Uno R3 made by Elegoo.

Hope you can help me out,
Tmirror

The USB specifications allow a maximum of 10uF total capacitance on the USB power lines. By putting 1000uF you have given it 100x more than is allowed.

This causes a massive inrush current and the USB host (your computer) sees it as a short circuit, so it shuts off the power in a panic to protect itself.

A capacitor does have a role to play in helping to remove power supply noise caused by power-hungry and noisy devices like WS2812B LEDs, but just slapping it across the power supply pins isn't going to really help.

Instead you should increase the impedance of the power supply to the noisy device(s) and use a capacitor to reduce the impedance again. This will help to preferentially draw current from the capacitor to supply the LEDs while smoothing out the draw from the main supply over time.

A simple circuit is to use a resistor with a capacitor:

simulate this circuit – Schematic created using CircuitLab

The values I show there for the resistor and capacitor are pretty random. The smaller the resistor the more demand will be put on the power supply. The bigger the resistor the more demand will be put on the capacitor. If the resistor is too big the capacitor won't be able to store enough power to run the LEDs, and too much voltage will be dropped across  it. If the capacitor is too small it won't be able to store enough power to run the LEDs. Tuning those values depends very much on the amount of noise there is and the current draw of the LEDs.

You must also make sure the resistor can handle the amount of power dissipated by the current flowing through it.


How can there be not enough current? I am new to the Arduino world. I have a question regarding current that the Arduino outputs over its 5V port. Why is the current in the Arduino too weak for current hungry circuit when the only thing that changes in this equation V=IR is the current itself.

For instance, the voltage in an Arduino is restricted to 5 volts. Assuming that the resistance of the current stays the same, shouldn't the current also increase (following Ohm's law) over its 5V port? More specifically, I am talking about powering ESP8266 with an Arduino.

The problem is not that "there is not enough current", but that you can't dissipate enough power.

Let's assume you are powering the board from an external 12V supply. Now, the 5V are obtained from 12V with a resistive regulator: this means that the regulator (see this image if you are interested in knowing what component it is) simply behaves like a variable resistor, dissipating the power in excess. Now, let's assume you want to draw 4A from the 5V rail, since you want to turn on a lot of LEDs and other stuff. Since P=VI, the regulator (that very little component) has to dissipate (12V-5V)*4A = almost 30W. This means that it becomes a little heater and.. Puff! it breaks.

Now, 4A is a really high current, but that regulator can withstand very little power dissipations. According to the datasheet, and estimating a 1cm x 2cm heatsing under it, we can estimate a 25 K/W thermal resistance, which means that each watt you dissipate raises the internal temperature by 25K (=25°C). You can't go beyond 150°C without damaging the component, which means that if your room is at 25°C you can dissipate AT MOST 5W. In practice, never go beyond 3W. Anyway even 5W mean that, at 12V, you can't get more than 5W/7V=0.7A.

By the way, the regulator is rated 0.8A, so you should never go beyond that value in any case.

Now, this was the external regulator. As for the usb, you can't get more than 500mA from that power supply. That's written in the specs. For this reason, a 500mA fuse is on that rail, so going beyond 500mA will blow that one, interrupting your power. Well, that's a self-healing fuse, so after some time (maybe hours?) it will operate again, but.. Don't try that.

In the end, the digital pin current. The atmega datasheet says that

The absolute maximum current per I/O Pin is 40.0mA
The absolute maximum current inside VCC and GND Pins is 200.0mA

This means that from each single pin you can get at most 40mA (but I suggest you never go beyond 20mA), and the sum of all the currents (and the internal peripherals) should never exceed 200mA. So if you need to power 2 leds, you can give each of them 20mA, if you need to power 15 of them you can't (you are limited to, let's say, 10mA). If you need more, use transistors to separate the current paths.


How to structure data for HTTP upload I'm building a GPS tracker using an arduino nano, Adafruit Ultimate GPS breakout, a SD card slot and a SIM800L module.

So far everything works, the tracker uploads the data to a server as well as saving an extra copy to the SD card. The problem is now, that I don't really think that sending a HTTP request every cycle (gps data point) is very efficient and I would also like to have a way of storing information if there is no GPRS reception.

The idea is to save the GPS data to SD card and bulk send it out every 5 minutes or so.

What would be the best way to set up the data structure? I'm saving the deta in a csv style file:

2016-8-2 22:23:44, 52.53251922, 13.31121666, 18.30, 7, 1.33;

Parsing that is not the problem, but rather how to keep track of what has been sent already and what not. I was thinking about Marking the lines that I sent with a # or something similar as first character.

The only problem I could see with that would be performance, since it could take a while to go though it every time once it's getting a bit larger.

Thanks!

Lukas

The only alternative structure I can think of is, since you have a number of data fields to send, you could create a struct to contain all the fields. Write the gathered GPS data to the file in its raw format, with file.write(&your_struct, sizeof(your_struct)) and read in a similar manner into a struct.

This will reduce the number of bytes written or read for any data point, and
Reduce the overall size of the file, compared to your original method, for the same number of GPS points.

The former improvement means there will be about 3 times as many GPS data points in a single block of data read from or written to the SD card, when compared to your current structure. Another more subtle advantage is that each data point occupies a known number of bytes in the file, making file navigation potentially easier. But you can only use this structure if you don't intend to view the CSV file with some spreadsheet program like MS Excel. You could, of course, very easily write your own PC program to parse the file and write to proper CSV. The Python struct module is very capable.

However, if you wish to continue with your current format, you can keep track of your current position in the file with file.position(); no need to use # as an indicator. You create 2 position variables, one to hold the position of the next line to be uploaded, curr_pos, and the other to hold the position of the end of the file for writing new data, end_pos. Initialize the former to 0.

You gather data as usual, and after 5 mins, you save the current file position to end_pos and seek to curr_pos with file.seek().
You read a line from the file and send it to the server.
If it's sent successfully (use the return code), you update curr_pos with file.position() so that it's now pointing to the next line in the file to be uploaded and go to step 2.
Else if the upload fails perhaps due to service, you stop uploading and don't update curr_pos. You seek to end_pos with file.seek() and go to step 1.

You will, of course, use available() to know when you've hit the end of the file to stop uploading, or you can compare curr_pos with end_pos for equality, whichever's more direct for you.

This involves a lot of operations on the file and I/O operations don't come cheap with SD cards, both in terms of current drawn and latency. Depending on how often you collect data and if you don't need to view it on a PC, you might consider some other means of storage (SPI flash, perhaps) or use a more capable Arduino like the Mega with more RAM and store the data temporarily in an array before upload, granting you faster access by orders of magnitude and much reduced power drain in the long term, since each block of file data will be accessed only once.


Does receiving data with SPI stop the main loop? I have a loop of code running on a Mega 2560 that is running at a certain speed, which I get from an Arduino Uno. I have tried to talk with I2C but when I receive the data from I2C, the whole code stops and then resumes when the communication ends. Does this also happen with SPI or can I be transmitting and receiving with SPI inside my main loop?

This is my code. I have to make my own PWM, because the analogWrite function isn't precise enough. When I send data to the Arduino, and since this is in the main loop, the motors stop. I have 4 of these blocks running.

digitalWrite(backLeft, HIGH); //Back left motor driver code
delayMicroseconds(backLeftSpeed);
digitalWrite(backLeft, LOW);
delayMicroseconds(backLeftSpeed);

Some (complex) processors have dedicated hardware to handle the I2C or SPI transaction.  Other (simpler) processors do not.  In such processors with no supporting hardware the bus must be emulated using software.  This takes time away from other processor activities.

You will have to determine if the processor in your Arduino (and there are many different types of Arduinos which use many different processors) has hardware to support I2C and / or SPI bus transactions with out help from the software.

Note: Even in cases where there is hardware to handle I2C and / or SPI transactions, badly written software can still trip up the processor and make it unavailable for other purposes.

Note: Even in cases where there is no hardware to handle the I2C and / or SPI transactions, well written software can handle a moderate demand from tasks while also handling serial bus processing.

[Comments based on Arduino board type added later to answer:]

You are using an Arduino Mega 2560 which uses the Atmel ATmega2560 processor (one of several described in the linked-to specification).  Searching the ATmega640 documentation shows matches for "TWI" (Atmel's equivelent to Philips' I2C) and SPI.  So, if the I2C or SPI driver software has been well written for the ATmega2560 processor, it should be using the processor's hardware.   Which makes the I2C or SPI feature more (but not entirely) immune to what ever else you have the processor running.

At this point it would be prudent for you to check if you are using such a driver.  Make sure you are not using a driver which "emulates" these protocols in software.  Also, make sure, if there is a hardware restriction, that you are using the pins on the processor designated for the type of bus used.  Some driver may be extremely flexible allowing you to designate a pin with out hardware support and automatically implementing the protocol in software.

[Comments based on code added later to answer:]

You are your self implementing what might be handed off to built in processor hardware in software.  Specifically you are emulating the PWM hardware feature in software.  It is likely that even the most efficient I2C or SPI code (even with supporting hardware) will effect such sensitive software.

It would take a fair amount of work to make this software "work better".  In general, you should consider not using delays and implementing a call-back paradigm based on a timed interrupts.

Alternatively, you might investigate why the Arduino PWM driver does not give you enough resolution.  The hardware may in fact provide more resolution than the driver permits.  Re-writing the PWM driver may be easier solution.


Communicate with custom usb slave device with DUE? I have a arduino due which i know has usb host mode. The usb library that comes with the due supports mouse and keyboard.

I have another usb device (diacnostic tool) id like to talk to, it use a:
USB Com Board Driver ( Multi-instance )
TI USBN9604
"Universal Serial Bus Full Speed Node Controller with
Enhanced DMA Support"
datasheet: www.ti.com/lit/ds/symlink/usbn9603.pdf

Ive also logged the raw byte usb traffic between windows and it when operating and would like to try sending some of those same calls to the device with the due.

Where do i start ?

Example Capture:

    000000: PnP Event: Device Connected (UP), 12.04.2015 09:14:51.390 (1. Device: USB Com Board Driver ( Multi-instance ))
The USB device has just been connected to the system.
000001: Bulk or Interrupt Transfer (DOWN), 12.04.2015 09:15:14.953 +23.562 (1. Device: USB Com Board Driver ( Multi-instance ))
Pipe Handle: 0x8639885c (Endpoint Address: 0x6)
Send 0x1b bytes to the device
 40 05 17 C0 00 09 02 00 AA 00 00 00 00 00 00 00
 00 00 00 00 00 00 00 00 16 06 12

i found what i needed here: http://arduino.cc/en/Reference/USBHost
and
https://github.com/felis/USB_Host_Shield_2.0


Standard Length Messages over RS-485 I am a bit confused. So I want to send messages between two arduinos over RS485, but these are not fixed length, naturally, I have to send the length of the message or add a delimiter to understand that my message has ended.

Suppose, now I create a placeholder for the message, and both ends communicating are receiving the placeholder, rather than the message itself. This placeholder is x bytes long always, and each arduino can look it up from its memory what message corresponds to the placeholder.

Lets say I create a message.h file with contents like this

#define A "First Message"
#define B "Second Message"

When the two devices are communicating, they send each other A or B, and the Arduino looks it up in its .h file what A and B mean.

My question is when the Arduino recieves the A, it recieves a character 'A', but how can I use this to fetch the value assigned to variable A in memory?

There is no "variable A" - there is only a macro called "A" which gets replaced by the contents of the #define for "A" at compile time.

You have to remember that the "A" that the Arduino receives is just a number.  It is only us humans who choose to associate that number with the letter A, and write software that takes that number and display it as an A.  The letter A is number 65.  The mapping between numbers and letters is called ASCII - or American Standard Code for Information Interchange.

What you do with that number is entirely up to you.  If you want to use it to display pre-defined messages, then there's a number of ways you could do it.  You could:

Use a series of if statements to compare the number you have
Use a switch/case construct in a similar way
Store the messages in an array and use the received number as the index

For string constants the last option is tricky to get right on an Arduino where there is very limited RAM - you have to ensure that you use PROGMEM and access it properly, and doing that from an array is not as trivial as it would otherwise be.

The best method would probably be the switch/case option:

switch (letter) {
    case 'A': Serial.println(F("First Message")); break;
    case 'B': Serial.println(F("Second Message")); break;
}


Amplification of microphone circuit I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.

You are mostly correct Diana.  The gain of an OP-Amp would normally be R8 divided by R6.

However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6.

The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers).

So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated.

The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts.  Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts.

The 741 output can't get near the +5 volts, nor can it get near ground.  Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).


How to keep accurate millis() while using ADC_sleep mode? millis() uses timer0 (linked to CPU clock) to count time, but ADC_sleep mode stops the CPU clock, therefore millis() will drift (lag behind) after each ADC conversion performed in ADC_sleep mode.

With the standard number of CPU cycles needed for the ADC conversion (ADC prescaler=128 multiplied by ADC clock cycles=13), and with the standard prescaler for timer0 (64), it would look like millis() loses 13.5 tics (about 0.1 ms) for every ADC conversion performed in ADC_sleep mode.

I could update the timer0 register (TCNT0) by increasing it manually by 14 but first of all I would still have a 0.5 ticks drift (or a bit less, since the update operation would take some cycles), second I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230.

How should I proceed to use ADC_sleep mode during ADC conversions but still keep millis() accurate?

Rather than trying to update TCNT0, it might be better to track the number of cycles lost to ADC conversions, and in an intermediate routine – eg, omillis() – compensate for those cycles. [Edit:  See better alternative, below]

In more detail:

• At each conversion, add about 128·13 cycles (or perhaps 128·13.5, to account for average prescaler delay) to a cycle counter:
 long lostcycles; ...; lostcycles += ADCcycles;

• Within each omillis() call, say return millis()+lostcycles/16000

• Or perhaps say return millis()+lostcycles>>14 to avoid wasting time on a division.  This would be off by 2% on the correction, but I presume the correction is small, say 5% of total time, leading to about 0.1% error because of using a shift instead of a divide.

  Re: “I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230”

That's incorrect [if using suggested approach].  Even if the timer 0 overflow is handled a hundred microseconds late, it will be handled ok. [As noted in Edgar Bonet's comment, a method that just adds to TCNT0 without checking arithmetic overflow, as in original approach, could miss a timer tick.]

Note, the example code using SLEEP_MODE_ADC in the “Sleep during reading” section of ADC conversion on the Arduino on Gammon Forum suggests that one should check for the case where a timer or other interrupt occurs during an ADC conversion.  While SLEEP_MODE_ADC stops clkI/O, clkCPU, and clkFLASH, it leaves Timer 2, WDT, and some other potential interrupt sources active.

A better alternative:

As Gerben points out, it's slightly cleaner to update the count variable maintained by millis(), rather than using an intermediate routine.  For background, refer to his answer to an earlier question.  Here is an adaptation [untested] of the idea to the current case:

unsigned int lostcycles=0;
...;
void accountForADC() {
  enum { ADCcycles = 13*128 + 64;  ms_cycles=16000 }; // adjust appropriately
  extern volatile unsigned long timer0_millis;
  lostcycles += ADCcycles;
  while (lostcycles >= ms_cycles) { // This loop usually runs one pass only
    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++timer0_millis;       // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status
    lostcycles -= ms_cycles;
  }
}

After startup, on the tenth call to accountForADC() this code would add 1 to timer0_millis to account for a millisecond lost to ADC conversions. lostcycles -= ms_cycles would set lostcycles to 1280.  After another 9 calls we again add 1 to timer0_millis and reduce lostcycles; and so forth.


Measurement of pulse duration greater than 3mins Is it possible to measure the width of a pulse which is longer than 3 minutes? The pulseIn function can only measure duration of maximum 3 minutes accurately.
I've tried using interrupts but haven't come up with a correct solution yet.

I'm measuring the duration of pulse (HIGH) generated by AND gate connected to the outputs of two comparators. AND gate output voltage is around 4.9 volts.

Any logical solution or idea would be appreciated. Thanks!

The concept is actually quite simple.

You need to record the time when the signal goes high, and record the time when it goes low. The pulse width is the difference between the two times.

Yes, you can do it with interrupts, but you don't need to if you're not trying to do anything else at the same time.

A simple polling code could be something like this:

while (digitalRead(pin) == LOW); // Wait for input to go high
unsigned long startTime = millis(); // Record start time
while (digitalRead(pin) == HIGH); // Wait for input to go low
unsigned long endTime = millis(); // Record end time
unsigned long pulseDuration = endTime - startTime;

You basically sit doing nothing until the leading rising edge of your pulse.  You then record the time, and again sit doing nothing - this time while looking for the trailing falling edge of the pulse.  Then record the end time and subtract the two.


Interfacing with an SSI sensor? I'm trying to interface with version RM08S of this rotary encoder using an Arduino Mega. The sensor supports a "Synchro serial interface (SSI), single ended" interface. I'm unfamiliar with this protocol.

Despite the name, it doesn't appear to match the description of the formal SSI or RS-422 specification, since that requires two wires for differential clock and data lines, whereas this sensor only has a single wire for each. This makes it sound more like IIC, but without the bus-like functionality.

Googling finds very few results on interfacing the Arduino to SSI devices, much less any standard libraries. This forum thread asks a similar question, but doesn't seem to resolve the issue.

Since there's just a clock and data line, would reading from this be as simple as toggling clock, and then reading the 10-bits of data from the data line, sequentially with each clock tick, accounting for whatever bits are used to pad the packet?

It's just SPI.

SPI.begin();
SPI.setDataMode(SPI_MODE2);

// ...

uint8_t h = SPI.transfer(0x00);
uint8_t l = SPI.transfer(0x00);
delayMicroseconds(20); // Indicate EOT
uint16_t v = (h << 8) | l;
v >>= 4; // for 12 bit resolution, 5 for 11 bit, 6 for 10 bit etc.

For 8 bit resolution or less you only need one SPI.transfer, and subtract 8 from the right-shift amount.

Wiring is simple: clock to SCK (52 or ICSP 3) and data to MISO (50 or ICSP 1).

The timing diagrams in the datasheet (page 5) describe it all in detail.


Small Arduino with Bluetooth HID interface I am trying to create a bluetooth gamepad for my phone.

I saw this:

https://www.amazon.com/DFRobot-Beetle-BLE-Arduino-Bluetooth/dp/B014KQHEH6/ref=cm_cr_arp_d_product_top?ie=UTF8

It says its bluetooth HID, but there are some conflicting comments saying it is serial over bluetooth. Is there something similar in a small form factor with an hid bluetooth module that I can use?

Based on the fact that the controller you mentioned has a TI CC2540 Bluetooth processor, I have found a few webpages with information about HID capabilities in the CC2540. Based this the CC2540 should support HID.

Some example code.
Question on the TI forums, with a link to example code.


Define a string with single quotation marks? This is kind of a short question. All I want to know is, if I can define a string using single quotation marks ('), instead of the regular ones("). I want to use it in a function like this:
print('Hello world');

I unfortunately do not have an Arduino nearby so I cannot test it myself.

No, you cannot. This rules comes from the basic C++ syntax on which the Arduino platform is built.


Decoding IR codes with IR sensor rather than IR receiver module I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).

Is there a library that supports IR sensors?

A picture of the two possibilities can be seen here

EDIT: This isn't a duplicate of my previous post, it is related to the same project however.
On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen here

I had a similar project a few months back and spotted this Arduino Library:

https://github.com/z3t0/Arduino-IRremote

and it is invaluable.

For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.

The wiring is easy and straight forward

  An IR detector/demodulator must be connected to the input RECV_PIN.

Which is 11 by default but you can definitely change it :3

and the other two Legs of the IR detector/demodulator go to the power source.


TimedAction.h: No such file or directory I am new to Arduino and I am trying one of the library TimedAction.h for sudo multithreading on Arduino. However the library is not present in the Arduino. How do I install external library(if it is)?

You can use three ways to install librarys in the Arduino IDE:
The probably easiest way is to go to Sketch > Include Library > Manage Libraries, (you can use Ctrl+Shift+I too) search for the library you want to install and click the install button. After that you need to include the library in your sketch with a #include <LibraryName.h>, or if you don't know the name, head again to Sketch > Include Library and click on the library you want to include.
If a library is not in the Library Manager from step one, you have to download the .zip file, go to Sketch > Include Library > Add .ZIP Library and search for the file. You just have to do that once, and it will be moved to you library folder. Again, make sure to include the library into the sketch.
If you just have a single file, you can move it to the sketch folder and include it by using #include "LibraryName.h", but you have to do it all over again for a new sketch, so I would recommend the other solutions if you can and want to use it permanently.


Arduino Uno with ESP8266-01 with AT Here is the schematic I followed:

Here also the link: https://www.circuito.io/app?components=10167,11021,12083,13678,13959

#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(11,10);

#define DHTPIN 2       // DHT-11 Output Pin connection
#define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
#define TRIGGER_PIN 4
#define ECHO_PIN 3
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

float hum;
float temp;

DHT dht(DHTPIN, DHTTYPE);

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

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);
  sendData("AT+CWMODE=2\r\n",1000,DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG);
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
}

void loop()
{
  delay(2000);  // Delay so DHT-11 sensor can stabalize

  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  long duration,distance;
  duration = pulseIn(ECHO_PIN,HIGH);

  distance = duration/58.2;

  Serial.print("Humid: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.print(" C, ");
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(50);

  if(esp8266.available())
  is sending a message
  {
    if(esp8266.find("+IPD,"))
    {
      delay(1000);
      int connectionId = esp8266.read()-48;
      /* We are subtracting 48 from the
         output because the read() function returns
         the ASCII decimal value and the
         first decimal number which is 0 starts at 48 */
      String webpage = "
IOT Garbage Monitoring System
";
      webpage += "

";
      if (distance<5)
      {
        webpage+= " Trash can is Full";
      }
      else{
        webpage+= " Trash can is Empty";
      }
      webpage += "

";
      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend +=webpage.length();
      cipSend +="\r\n";

      sendData(cipSend,1000,DEBUG);
      sendData(webpage,1000,DEBUG);
      String closeCommand = "AT+CIPCLOSE=";
      closeCommand+=connectionId;
      closeCommand+="\r\n";
      sendData(closeCommand,3000,DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      char c = esp8266.read();
      response+=c;
    }
  }
  if(debug)
  {
    Serial.print(response);
  }
  return response;
}

I've been trying to solve this problem for almost a week.

If you want to use esp-01 over SoftwareSerial, you must set the AT firmware's default baud rate to 9600 baud. The default baud rate of AT firmware is 115200 baud. SoftwareSerial can't work at this speed.
To change the baud rate you must have a way to communicate with AT firmware at the default baud rate of 115200 baud. You can use the USB adapter of the Uno. Upload BareMinimal sketch from Examples to Uno to make it silent and connect the esp-01 to RX and TX pins of the Uno.
Connect RX to RX and TX to TX to have the cross connection to USB of the Uno. Then connect from Serial Monitor to esp-01 at 115200 with "Both line end characters" set. Try some basic AT commands and then still at 115200 baud send the command to change the default baud rate AT+UART_DEF=9600,8,1,0,0

In setup() in sketch begin for SoftwareSerial is missing. Add  esp8266.begin(9600);

Uno pin 11 is RX of software serial, pin 10 is TX. The RX pin 11 must connect to TX pin of esp-01. Same applies for TX pin 10. It must connect to RX pin of the esp-01.
On the Fritzing schema on Uno pin 11 is green wire and on esp-01 TX is green wire. But the green wire is on sides of the level converter not on the same position. The conclusion is that you have RX connected to RX not to TX. Switch wires on best at level converter.

The 3.3 V pin of some Uno clones can't supply enough current for WiFi operations of the esp8266. You need to convert to 3.3 V from Uno 5 V pin or use a separate 3.3 V power source for the esp-01.


Using millis() to time the start / stop of a DC motor I'm trying to use a DC motor with pinion engaged to a rack gear, and have that motor move a distance, save the distance, delay, reverse, and travel back the same distance from where it started, delay, do it again. I want to start/stop the initial save with a button push, then from those saves, loop the motor movement.

I have considered using a Hall effect sensor or reed switch to count, but it seems a software interrupt or timing is easier using millis(). I researched and found that millis() cannot be reset, so I'm wondering if this is possible.

I haven't started a sketch, but I got this idea from the BlinkWithoutDelay example sketch included with the Arduino IDE. Like, have the motor positioned at "home" position, button push, start the timer, motor travels to end of work piece, stop the timer, save that forward distance traveled into a variable, reverse the motor, (at this point the timer would be at 0 again for the reverse travel) travel back to "home" save that reversed distance traveled into another variable with a button push, and then use these start/stop values in a loop. So I would save the values with a button pushes, then just loop that.

Or I'm thinking about putting an if or while button push outside the loop with a nested counter++, eyeballing the motor travel, once it gets to where I want it, save those counts in variables, then using them in the loop to analogWrite() to the motor.

You can't reset the millis() function, but you can count the amount of milliseconds and stop when necessary: beware though, the positioning might not be as precise as you wish and you have to consider the error will accumulate on the long run.

Nonetheless here is the code:

uint16_t duration;
bool direction = true;
void loop() {
  if (duration != 0 and !buttonPressed()) {
    // running back and forth if setup and no "finish" button detect
    uint16_t start = millis(); // reset the timer
    startMotor(direction);
    while (millis() - start < duration && !buttonPressed()) {
      ; // keep going
    }
    direction = !direction; // reverse direction
  } else if (duration == 0) {
    // your motor positioning setup
    while (!buttonPressed()) {
      ; // wait for button to start positioning
    }
    uint16_t start = millis(); // ask for time
    startMotor(true); // run the motor cw
    while (!buttonPressed()) {
      ; wait for button to end positioning
    }
    duration = millis() - start; // store duration
    direction = false; // reverse motor direction
    // next time loop() is executed the motor will go back to home
  }
}
bool buttonPressed() {} // define this to determine if the button has been pressed, safer if you use an interrupt
void startMotor(bool cw) {} // define this to run your motor clockwise or counterclockwise


What is the equivilent of PORTx for Teensy (4.0)? I've seen people use code like PORTB |= 0x1 << 6 to set the sixth bit of PORTB in arduino. I understand that this is significantly faster than using digitalWrite. How can this be done using a modern Teensy (i.e. 3.6 or 4.0) if at all?

All Teensies support digitalWriteFast out of the box. digitalWriteFast compiles to just setting the bit in the right port register. You can not do that faster by direct register manipulation.

However, if for some reason you do want to manipulate the registers directly here the pin/gpio relation for the T4. (Generated by the sketch described here: https://github.com/luni64/TeensyTimerTool/wiki/Avoid-PWM-timer-clashes")

Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
00  |  GPIO6_03  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
07  |  GPIO7_17  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
10  |  GPIO7_00  |  QUAD1
11  |  GPIO7_02  |  QUAD1
12  |  GPIO7_01  |  QUAD1
13  |  GPIO7_03  |  QUAD2
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
16  |  GPIO6_23  |  no pwm
17  |  GPIO6_22  |  no pwm
18  |  GPIO6_17  |  QUAD3
19  |  GPIO6_16  |  QUAD3
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
33  |  GPIO9_07  |  FLEX_PWM2
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1

#### Sorted by PWM timer
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
10  |  GPIO7_00  |  QUAD1
13  |  GPIO7_03  |  QUAD2
18  |  GPIO6_17  |  QUAD3
15  |  GPIO6_19  |  QUAD3
14  |  GPIO6_18  |  QUAD3
19  |  GPIO6_16  |  QUAD3
24  |  GPIO6_12  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
23  |  GPIO6_25  |  FLEX_PWM4
22  |  GPIO6_24  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
02  |  GPIO9_04  |  FLEX_PWM4
27  |  GPIO6_31  |  no pwm
17  |  GPIO6_22  |  no pwm
26  |  GPIO6_30  |  no pwm
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
21  |  GPIO6_27  |  no pwm
20  |  GPIO6_26  |  no pwm
16  |  GPIO6_23  |  no pwm

#### Sorted by GPIO register:
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
01  |  GPIO6_02  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
19  |  GPIO6_16  |  QUAD3
18  |  GPIO6_17  |  QUAD3
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
17  |  GPIO6_22  |  no pwm
16  |  GPIO6_23  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
10  |  GPIO7_00  |  QUAD1
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
13  |  GPIO7_03  |  QUAD2
06  |  GPIO7_10  |  FLEX_PWM2
09  |  GPIO7_11  |  FLEX_PWM2
32  |  GPIO7_12  |  no pwm
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
28  |  GPIO8_18  |  FLEX_PWM3
31  |  GPIO8_22  |  no pwm
30  |  GPIO8_23  |  no pwm
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
29  |  GPIO9_31  |  FLEX_PWM3


Linux can not open arduino IDE - java.lang.NullPointerException I use arch linux. I installed arduino ide with pacman. When I try to run it, loading window will show for few socends and than program crashes. There are logs:
john@arch-thinkpad ~ [1]> arduino
Picked up JAVA_TOOL_OPTIONS:
Set log4j store directory /home/john/.arduino15
java.lang.NullPointerException
    at processing.app.Base.rebuildProgrammerMenu(Base.java:1705)
    at processing.app.Base.<init>(Base.java:286)
    at processing.app.Base.main(Base.java:150)
john@arch-thinkpad ~ [255]>

john@arch-thinkpad ~> arduino --version
Picked up JAVA_TOOL_OPTIONS:
Loading configuration...
Initializing packages...
Preparing boards...
Arduino: 1.8.13

What should I do to fix it ?
Thank you for your help

I had to install arduino-avr-core package:
sudo pacman -S arduino-avr-core

Now it works fine


How would one send radio signals from Arduino at a non-standard frequency TL;DR: How would one send a fixed radio signal at 447,54MHz with Arduino?
Background: I recently purchased a (receive only) SDR and recorded my garage door fob. I found it sends a fixed signal at the frequency 447,54MHz, which I was able to decode. Now I want to try activating the garage door via Arduino. The standard 433MHz senders obviously don't work, since they have a totally different frequency.
I tried searching for senders of my frequency (447MHz) and also for senders with different or variable frequencies. I didn't really find much. Also I read in some post (that I don't remember currently), that building an own sender circuit is not easy (since the exact PCB design plays a big role in the behavior in the ciruit). It didn't seem, that this would be a valid way for me.
Has someone here experience with such frequencies? While I know, that this site doesn't do product recommendations, maybe I just searched for the wrong term and you can help me with that. Or maybe there are no (or very very few) "maker-ready" products for this out there currently. Maybe the creator of the garage door system wanted a non-standard frequency for security-through-obscurity (since that doesn't protect against attackers with a sending SDR).
Also I researched about frequency bands. Normally I would think of a garage door fob as a Short Range Device (SRD), but instead my frequency is right above (and outside) of the band PMR. Maybe this is because the system is really old (can easily be between 15 and 30 years).
I'm kinda lost on how to proceed here, or if proceeding is even viable here.

The standard 433MHz senders obviously don't work, since they have a totally different frequency.

I think "433 MHz" is used as a band name, with 433 MHz actually being at the lower limit of a band that covers approximately 40 MHz. Your garage door opener will likely be referred to as a "433 MHz garage door opener", even though it operates at 447.54 MHz.
For your experiments, you might try the HC-12 module. It's billed as a 433 MHz radio, but in fact it covers 433 MHz to 473 MHz in 100 bands with 400 kHz spacing, so it will cover your desired 447.54 MHz. The link above has some Arduino code examples that might help get you started. And of course there is much more information on this topic if you're interested.


How to produce a .o file from code using Arduino IDE (primarily for LGPL3 compliance) I spent a great deal of time looking for any posts regarding this and came up empty.

The reason I needed to do this is that I am working on some proprietary code that will be released in an embedded device, but makes use of an LGPL 3.0 licensed library which requires (4.d.0) that I release "corresponding application code in a form ... permit the user to recombine or relink the application with a modified version of the library."

Since the application is on an embedded device, the "corresponding application code" works out to the pre-link .o file which is normally well hidden in the Arduino process.

To extract the .o produced during compilation in the Arduino IDE, do the following:

Go to the Arduino->Preferences menu item. This will open a preferences window.
In the preferences window find the line that says "Show verbose output during" and make sure that compilation is checked. (you can leave upload on or off as you prefer).
Click "OK" to close the preferences window.
Compile (or compile and upload) your Sketch.

You will get lots of extra output. In the white text, you will either see messages about files being compiled or about "using previously compiled file". In either case, there will be a path provided which will indicate where your Sketch was compiled. On my Mac environment this is /var/folders/<long random string>/T/arduino_build_<number>/sketch/<sketch_name>.ino.cpp.o

The line where your sketch is compiled is very long, but the path is also visible in most of the library lines and you can just work down into .../sketch/... instead of .../library/... instead of scrolling so far to the right on the exactly correct line.

To find the exact line where your sketch is compiled, look for the line directly below a line which simply says "Compiling sketch..."

I know this is rather basic (now that I know how to do it), but it took quite a bit of digging to find it and I figured others might want an answer that's searchable.


Multiple if statements - stuck I have a robot that uses two motors to skid steer. The robot gets input from three ultrasonic sensors (left, middle, and right) and a passive infrared sensor. If the robot detects a person in front of it, then it follows.

The sensors seem to work as they are intended. The infrared sensor sees a person and the ultrasonic sensors see that the person is between 65cm and 150cm and it follows. If the left ultrasonic sensor has the person in range, it turns left, and if the right ultrasonic sensor has the person in range, it turns right.

The problem is that the robot gets stuck turning left or turning right depending on which sensor it checks first in the code. It's like it's stuck in a while loop even though I'm not using a while loop.

I have adapted NewPing and library. The code in question is at the bottom in the last function. The rest is part of NewPing to read the ultrasonic sensors.

If anybody has any suggestions, it would be greatly appreciated.

#include <NewPing.h>

#define SONAR_NUM     3 // Number of sensors.
#define MAX_DISTANCE 170 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 35 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(11, 4, MAX_DISTANCE), //Left -- Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(8, 3, MAX_DISTANCE),  //Center
  NewPing(7, 9, MAX_DISTANCE),  //Right
};

int ledR = 13;
int ledG = 2;
int ledB = A0;
int motorPinL = 5;
int motorPinR = 6;
int ePIR = 10;
boolean epirVal;

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
  pinMode (ledR, OUTPUT);
  pinMode (ledG, OUTPUT);
  pinMode (ledB, OUTPUT);
  pinMode (motorPinL, OUTPUT);
  pinMode (motorPinR, OUTPUT);
  pinMode (ePIR, INPUT);
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1)
        oneSensorCycle();                             // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 155;                      // Make distance 155 in case there's no ping echo for this sensor. changed from zero
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  // Other code that *DOESN'T* analyze ping results can go here.
}

void echoCheck() { // If ping received, set the sensor distance to array.
  if (sonar[currentSensor].check_timer())
    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}

void allStop () {
  analogWrite (motorPinL, 0);
  analogWrite (motorPinR, 0);
  digitalWrite (ledG, LOW);    //LED corresponding to right ultrasonic sensor
  digitalWrite (ledR, LOW);    //LED corresponding to left ultrasonic sensor
  digitalWrite (ledB, LOW);    //LED corresponding to center ultrasonic sensor
}

Your logic is flawed. Translating your loop in pseudocode gives
something like this:

if (PIR does not detect OR ANY sonar is out of range) {  // cond. 1
    stop
} else if (PIR does detect AND right sonar is in range) {  // cond. 2
    turn right
} else if (PIR does detect AND left sonar is in range) {  // cond. 3
    turn left
} else if (PIR does detect AND center sonar is in range) {  // cond. 4
    go straight
}

Notice that, if condition 1 is false, then that means that the PIR does
detect AND ALL of the sonars are in range. Which implies that condition
2 is necessarily true. Which implies that the following elses have no
effect. Your code can then be optimized (and the compiler probably did
optimize it) into

if (ANY sonar is out of range OR PIR does not detect) {  // cond. 1
    stop
} else {  // cond. 2 is true if cond 1. is false
    turn right
}

You should rethink your problem asking yourself the following questions:

under what conditions should the robot turn right?
under what conditions should the robot turn left?
under what conditions should the robot go straight?
under what conditions should the robot stop?

Make sure that in any circumstance EXACTLY one of the above conditions
holds true. In other words, the conditions should be mutually exclusive
and cover every possibility. One you have the answers, the coding should
be straightforward.

Edit: Your updated code still contains logic flaws. For example, if
the PIR senses the person and BOTH the left and right sonars are in
range, then you are asking the robot to BOTH turn left and turn right.
Unless it's a quantum robot evolving in an Everett's multiverse, it
won't be able to comply. To the risk of repeating myself, you must
decide on one and only one action for every possible situation.

If you are struggling with that concept, I suggest you start by filling
the truth table below. On each of the 16 lines of the table you should
fill the last column with one (and only one) action among: allStop,
turnRight, turnLeft and straight. Yes, I know it's tedious to
consider all the possible situations one by one, but you must do that
before starting to write the code. Otherwise you end up with completely
broken logic.

+--------+----------+----------+----------+-----------+
| PIR    | sonar 0  | sonar 1  | sonar 2  |  robot    |
| senses | in range | in range | in range |  action   |
+--------+----------+----------+----------+-----------+
|  no    |   no     |   no     |   no     |           |
|  no    |   no     |   no     |   yes    |           |
|  no    |   no     |   yes    |   no     |           |
|  no    |   no     |   yes    |   yes    |           |
|  no    |   yes    |   no     |   no     |           |
|  no    |   yes    |   no     |   yes    |           |
|  no    |   yes    |   yes    |   no     |           |
|  no    |   yes    |   yes    |   yes    |           |
|  yes   |   no     |   no     |   no     |           |
|  yes   |   no     |   no     |   yes    |           |
|  yes   |   no     |   yes    |   no     |           |
|  yes   |   no     |   yes    |   yes    |           |
|  yes   |   yes    |   no     |   no     |           |
|  yes   |   yes    |   no     |   yes    |           |
|  yes   |   yes    |   yes    |   no     |           |
|  yes   |   yes    |   yes    |   yes    |           |
+--------+----------+----------+----------+-----------+


Running ESP8266 at 3.78V to work with ATMEGA328P at 16 MHz I have a project that is powered by 2x 18650 battery and feeds it to a step down switching voltage regulator that is configured to give a steady output of 3.78V to both esp8266 and atmega328p.

The esp8266 only sends an HTTP post request to an API every 30 mins and on standby mode whenever it does not do anything.
I have tested it for 1 hour and the esp8266 seems to work fine and does not warm. I intend to use the esp8266 in an airconditioned office 24/7 or until the battery runs out. I know it is not safe to give 3.78V because its supposed to have only a maximum of 3.6V but I am asking if anyone has ever had the same application and did not experience any problems?

Other possibilities include:

Running the Atmega328p at 8MHz and powering at 3.3v. Both devices would be operating within spec.
Running the whole system at 3.3v but without changing the clock on the '328. The advantage here is you'll get the full throughput from the '328, assuming you need it. The disadvantage (assuming a 16MHz Atmega328p) is that it will be running out of spec (overclocked) but they seem to be conservatively enough speced that most chips do fine. I have built two boards this way for the same reason: to put both a 328p and an ESP8226-01 on one board. I ran some rather rudimentary tests on the Atmega chips I put on those boards to find out if they would work at that voltage. I didn't see any issues and I haven't discovered any since.

Update:

  Would it be possible to run the ATmega at 8 MHz using a 16 MHz
  external oscillator by simply uploading a new sketch?

It may be possible to use its internal resonator and ignore the connected crystal; I haven't tried this. Could you clip off the external crystal if you needed to?

This article talks about setting the fuses that control the clock frequency. One thing to keep in mind is you'll need to replace the bootloader with one appropriate for the new clock frequency. You may find an 8Mz bootloader ready to upload, or recompile it yourself from source. Optiboot is a good choice: open source, has a small footprint, and you can set its upload baud-rate. You can upload a new bootloader using another Arduino as an ISP programmer - there are lots of articles about doing this and the code for the Arduino-as-programmer is one of the Arduino IDE example-programs.


Is it possible to make 4hz readings with the DS18S20 temperature sensor? My current code that doesn't convince me:

#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

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

void loop(void) {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1); // start conversion, with parasite power on at the end

  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad

  for (int i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
  }

  ds.reset_search();

  byte MSB = data[1];
  byte LSB = data[0];

  float tempRead = ((MSB << 8) | LSB); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

the outcome of few seconds of recording:

22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31

EDIT: I inserted the suggestion of @frarugi87 and I inserted the sensor in my pants to test it:

22.50
22.50
22.50
23.69
23.69
23.69
23.75
23.75
23.75
23.75
23.75
23.75
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
24.00
24.00
24.00
24.06
24.06
24.06
24.19
24.19
24.19
24.25
24.25
24.25
24.31
24.31
24.31
24.44
24.44
24.44
24.50
24.50
24.50
24.56
24.56
24.56
24.56
24.56
24.56
24.62
24.62
24.62
24.69
24.69
24.69
24.75
24.75
24.75
24.81
24.81
24.81
24.87
24.87
24.87
24.87
24.87
24.87
24.94
24.94
24.94
25.00
25.00
25.00
25.00
25.00
25.00
25.06
25.06
25.06
25.12
25.12
25.12
25.12
25.12
25.12
25.19
25.19
25.19
25.25
25.25
25.25
25.25
25.25
25.25
25.31
25.31
25.31
25.37
25.37
25.37
25.44
25.44
25.44
25.44
25.44
25.44
25.50
25.50
25.50
25.50
25.50
25.50
25.56
25.56

I still find the change of temperature slow

I would expect some variations in temperature, but I would not say that is a problem caused by the 4Hz readings. You can test my assumption by reading every 3 seconds, does the temperature value change or is it still the same?

I see two potential problems:

your DS1820 is defect.
from your code I assume that you use parasitic power. In that case the chip consumes power from the data wire ( one wire ;-) ) through a pull up resitor (~4.7 kOhms). If you do not provide a special handling, to drive more current while the DS1820 is converting or copying data to EE or from EE memory to the scratchpad, then there will be (most likely) voltage drops.
Then the Temperature conversion will not happen and you read the old value from the scratchpad in your read cycle.

You can test point 2 by adding VCC to the DS1820, and do not use parasitic power.
If that is your problem, you can fix it with a switching FET Transistor, that provide more current (see DS1820 Datasheet from Maxim) or by using an additional VCC wire.


ESP8266, I am trying to establish a SoftAP and I cant seem to get the WiFilocalIP function to give me my IP I am just trying to establish a server and it seems that I can't get the serial monitor to read the local IP of my device and my Client can't establish a connection to update the sensor value. when I run the monitor I get this:

IP Address: (IP unset)

here is my code:

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    /// Config parameters for Access Point
    char * ssid_ap = "This Little Buddy";
    char * password_ap = "guessing";
    IPAddress local_ip(192,168,4,4);
    IPAddress gateway(192,168,4,1);
    IPAddress subnet(255,255,255,0);

    //Setup Server Object
    ESP8266WebServer server;

    //Sensors and what not here
    float sensor_value = 0.0;

    void setup() {
        //identify and start WiFi
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(local_ip, gateway, subnet);
      WiFi.softAP(ssid_ap, password_ap);
      //sanity check
      Serial.begin(115200);
      Serial.println();
      Serial.print("IP Address: "); Serial.println(WiFi.localIP());
      //Configure the server's routes
      server.on("/", handleIndex); //using top root path for last sensor value
      server.on("/update", handleUpdate); //use this to update sensor value
      server.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    server.handleClient();
    }

    void handleIndex(){
      server.send(200, "text/plain", String(sensor_value));//need to refresh page to get information
    }

    void handleUpdate(){
      //value is passed by an URL argument
      sensor_value = server.arg("value").toFloat();
      Serial.println(sensor_value);
      server.send(200,"text/plain", "Updated");
    }

The WiFi.localIP() is a function of the STA. To print the IP address of the SoftAP, use WiFi.softAPIP().


How to handle a ESP8266 webserver only to the access point? I'm developing a application that needs to be somewhat secure, so to configure the parameters it handles a GPIO interrupt (from a button) to open a server, that lets you configure it. The problem is that it is configured to send an email, so it is connected to the wifi.

With this in mind, I need to detect the source of the connection so I can serve the html only to the access point connections.

Is it possible?

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.

#include <ESP8266WiFi.h>

WiFiServer telneServer(23);

void setup() {
  ...
  telneServer = WiFiServer(WiFi.softAPIP(), 23);
//  telneServer = WiFiServer(WiFi.localIP(), 23);
  telneServer.begin();


How to multitask while writing on Serial I am trying to send real-time data taken from an ADC by Arduino Uno (SPI) to Arduino IDE through a USB cable. I found that one byte takes around 70 microseconds when Serial.write() is used at a baud rate of 115200. My question is that if I send 14400 bytes (which would be the maximum limit at this baud rate), can I perform any other tasks? Does Arduino allow multitasking while the serial buffer is busy writing data?

Until you fill the transmit buffer (64 bytes by default but can be recompiled to enlarge it if you need to), Serial.print() or Serial.write() will return immediately. The characters in the buffer will be transmitted by an interrupt service routine, so essentially, the Arduino is double-tasking for that purpose. If the buffer is full when you call Serial.print() or Serial.write() or Serial.print() fills it before having sent all of its characters, those calls block (won't return) until there is buffer-space for their remaining characters.

So yes, you can do other things while the writing happens, as long as you haven't filled the buffer. You can call Serial.availableForWrite() to find out how many characters you can send without blocking.

By the way, at 115200 baud, or 11520 bytes/second, each character should take 1/11520 seconds or 86.8 microseconds, not 70 milliseconds.


How can I connect H-Bridge motor driver (using four 2n222 transistors) to Arduino? First of all I'm a noob.

I was trying to do the H-Bridge using 2N2222 controlled by an Arduino Uno.

This is the design--->

I joined A1 and A2 to form a common terminal (say A), similarly, I joined B1 and B2 to form B. Now I connected A and B to 2 pins of the arduino (say pin 9 & pin 10 respectively).

So, theoretically, when I should digitalWrite pin 9 HIGH, then current should flow via A1 and A2, i.e. left to right in the motor AND when I should digitalWrite pin 10 HIGH, then current should flow via B1 and B2, i.e. right to left in the motor.

Hence, I can control the direction of rotation of the motor.

BUT.....it wasn't working...!!!!

I need help...!!!

After much thinking I had a hunch...."Perhaps, I am not giving GROUND to the transistors". I thought about it, but was unable to figure out the way of doing it.

So, again, please help me...!!!

I am not an electronics guru yet either so others might give you a better answer, but this is one circuit I have messed with a lot because I keep trying to build robots, so I will take a shot at an answer.

Normally you need both NPN and PNP transistors for an H-bridge:

The 2N222 is NPN so you'd want to pair two of them with two equivalent PNPs such as the 2N2907.

I've see diagrams that have all NPNs but I have never gotten a circuit to work that way. There is a distinction about where the load goes, before or after the transistor, that makes you chose to use an NPN or a PNP in order to make it all flow properly.


Arduino Uno R3 HID with HC-06 BT module Im trying to make a macro pad using Arduino Uno r3 and 4x4 matrix (cherry blue clone) . I know using a pro micro is better than uno cause there isn't HID compatibility in uno but since i already have one , i want to work with this . I have already tested the macro pad after compiling and flashing a keyboard.hex file . But wondering if i buy a bt module like HC-06 (which is about 3.2$ here ) would that be able to send inputs even aftar flashing ? I have like basics coding knowledge so i have no clue what flashing actually would do to the module so . Anyone know would making that macro pad BT compatible    be possible or not ?

It is unclear to me, where you flashed what, so I will describe some basics.
The Uno cannot act as a keyboard/HID device, since the microcontroller on it (the Atmega328p) doesn't have native USB capability. For connecting to USB the Uno has a USB-to-Serial chip on it (actually another microcontroller, the Atmega32u4 I think). So with the Uno you only have a serial connection, unless you hack the Atmega32u4 and program it with your own firmware (firmware is a term for software, that runs very near to the hardware, in this case directly on the microcontroller, in contrast to normal software running on an operating system on a computer; so in the middle between hard- and software, thus firmware).
Flashing is the same as programming a microcontroller. It has this name, because the program is saved in flash memory on the microcontroller (that is a specific type of memory technology; the same technology, that USB sticks use for storing your data). Flashing the HC-06 means programming it with a different firmware.
All bluetooth devices use the same base technology (thought to be clear, BLE is a different technology). The role of the device depends on the characteristic/profile, that it exposes to the host. There are profiles for HID, Serial, Audio, ... .
The HC-06 is a bluetooth slave device, which acts as a bluetooth-serial-bridge (like the Atmega32u4 acts as a USB-serial-bridge). But this is a software limitation. The HC-06 has standard bluetooth hardware, but the firmware on it just gives you the Serial profile (in fact a HC-06 is mostly the same like the master device HC-05, just different firmware and corresponding breakout boards can break out other pins). So by flashing (programming) it with a different firmware, you can get different profiles. If you find a firmware, that gives you HID functionality, you can flash that to the HC-06 and use it. Though this is a bit hacky I think (haven't done it myself), so it might be a bit too much for a beginner.
Bluetooth Slave/Master: The bluetooth protocol uses fixed roles for the two connected devices. One is the master and one is the slave. The master controls, if the communication is really happening. For example a bluetooth headset is a slave device. You cannot connect the bluetooth headset to your bluetooth keyboard, because both are slave devices. You always need one master and one slave. The HC-05 is basically the same module as the HC-06, but it's firmware enables it do be master or slave (configurable by you). So some devices support both modes, but still in any specific connection they can only have one of the modes (need to either master OR slave at any time).

Anyone know would making that macro pad BT compatible be possible or not ?

Possible, yes. But I suggest you invest in buying a ready to use bluetooth HID controller (immediately found this one from adafruit, though you might might cheaper versions). That will be way easier, than directly jumping into flashing a HC-06. Though that is still a possible path to go.
Another way to go would be to just use the serial functionality and write a small program for your PC, which reads from the Serial interface and issues key strokes according to the serial data. Then you don't need to reflash the HC-06.


Description about arduino relay I have this relay module. I don't understand what is a role of the jumper on it (for now it's shorting the jd-vcc (what??) and vcc pins).

The jd-vcc pin can be used to power the relay coils using a separate 5V power supply. Why would you want to do that? Each relay coil draws about 73mA @ 5VDC when energized. Theres a circuit schematic on this website: http://howtomechatronics.com/tutorials/arduino/control-high-voltage-devices-arduino-relay-tutorial/


Connecting two pressure sensors with one uno I'm trying to connect two BMP180s to an arduino uno by using a multiplexer.

Here is the code that a guy has written before:
I imported SFE_BMP180 library but didn't do anything with the "typedef.h" thing.

I'm getting "Data does not name a type" error at the line 9.
How can  I solve this problem?

     #include <SFE_BMP180.h>
    #include <Wire.h>
    #include "typedef.h"

    #define SELECT_PIN 9
    #define ALTITUDE 510.0

#define P1_ACTIVE digitalWrite(SELECT_PIN,HIGH); //delay(10);
#define P2_ACTIVE digitalWrite(SELECT_PIN,LOW);  //delay(10);

SFE_BMP180 bmp1,bmp2;
boolean readSensors(Data *data1, Data *data2);

Data newData(char id)
{
  Data d ;
  d._id = id ;
  return d ;
}
void setup()
{
    boolean failed = false ;
    pinMode(SELECT_PIN, OUTPUT);

    Serial.begin(9600);

    P1_ACTIVE

    if(bmp1.begin()){
        Serial.println("BMP #1 init success.");
    }
    else
          failed = true ;

    P2_ACTIVE
    if(bmp2.begin()){
          Serial.println("BMP #2 init success.");
    }
    else
        failed = true ;

    if(failed){
        Serial.println("Error in BMP180 init.");
        while (1);
    }
}

void loop()
{
  Data d1 = newData('1');
  Data d2 = newData('2');

  boolean read = readSensors(&d1,&d2);

  if(read){
          /* print the value to serial terminal */
...

You can try my BMP080/BMP180 Arduino library
My library doesn't require use of floats of math library, making your sketch very small and fast.


Make Arduino send and receive at the same time I am working on a project where I connect a GPS module and GPRS SIM900 shield. The location will be sent when it recives a certain character.

Now my question is, can the Arduino receive from GPRS and GPS module data at the same time? The GPS is not given coordinates, however it works properly without receiving a message from the GPRS.

I am using softwareserial  for both. Should/can I use hardware serial and softwareserial?

I am using SoftwareSerial for both.

As others have said, you cannot listen to 2 SoftwareSerial ports at the same time.

  Should/can I use HardwareSerial and SoftwareSerial?

  ... can the Arduino receive from GPRS and GPS module data at the same time?

Yes, but...

This answer provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

Use the HardwareSerial port (i.e., Serial) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
Use AltSoftSerial for the other device.  It is the most efficient software serial port, and it can be used at the same time as Serial.  It only works on two specific pins.
NeoSWSerial is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on NeoSWSerial prevents them from receiving.
SoftwareSerial is the worst choice.  Receiving or transmitting on SoftwareSerial prevents all of the above from receiving anything.  It disables interrupts for long periods of time.


Java NetBeans sending value and receiving value from Arduino This is my Java code to send a value to Arduino and a receiving value from Arduino. Can anyone tell where I made a mistake? I am able to send the value but can't receive a value from Arduino.

package hell;

import com.panamahitek.ArduinoException;
import com.panamahitek.PanamaHitek_Arduino;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class led extends javax.swing.JFrame
{
    PanamaHitek_Arduino Arduino  = new PanamaHitek_Arduino();
    private BufferedReader input;
    SerialPort serialPort;

    public led(){
        initComponents();
        try {
            Arduino.arduinoTX("com3", 115200);
        }
        catch (ArduinoException ex) {
            Logger.getLogger(led.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent)
    {
        System.out.println("lol 31");
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                System.out.println("lol 1.1");
                Scanner s = new Scanner(serialPort.getInputStream());
                int mes =Integer.parseInt( s.nextLine());
                System.out.println(mes);
                System.out.println("lol 1");
            } catch (Exception e) {
                System.err.println(e.toString());
                System.out.println("Syncronice ");
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(0);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is off");
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(1);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is on");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new led().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;

    try{
        Arduino.sendByte(1);
    }
    catch(Exception ex){
        Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
    }

    System.out.println("led is on");

    private javax.swing.JButton jButton2;
}

Here is my Arduino code, which receives a value from Java and prints it accordingly:

int val = 0;
int led = 8;

void setup() {
  Serial.begin(112500);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available()>0) {
    val = Serial.parseInt();
    if(val == 1) {
      //Switch on the LED, if the received value is 1.
      digitalWrite(led, HIGH);
      Serial.println("Succesfully received.");
    } else if(val == 0) {
      //Switch off the LED, if the received value is 1.
      digitalWrite(led, LOW);
    }
  }
}

EDIT:
There is no problem to controlling arduino via Java code, the problem is that I can't received message from Arduino to display in a Java.

You are writing a number as a single byte and expect it as a string on the other end.

Replace

val = Serial.parseInt();

with

val = Serial.read();


Attiny88 as SPI slave I have programmed Attiny88 with Arduino IDE 1.6.5 using https://github.com/SpenceKonde/ATTinyCore . I chose Attiny88 because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins with dedicated SPI.  I wrote a code for arduino to work as SPI master, and a code for Attiny88 as SPI slave but I get only 0 as answer from Attiny.

SPI master code for ARduino UNO

#include <SPI.h>

// set up the speed, data order and data mode
SPISettings settingsA(2000000, MSBFIRST, SPI_MODE0);
const int slaveAPin = 10;

void setup() {
  // set the Slave Select Pins as outputs:
  Serial.begin(9600);
  Serial.println("SPI ON");
  pinMode (slaveAPin, OUTPUT);
  SPI.begin();
}

uint8_t stat, val1, result;

void loop() {
   // read two bytes from device A
   SPI.beginTransaction(settingsA);
   digitalWrite (slaveAPin, LOW);
   // reading only, so data sent does not matter
  stat = SPI.transfer(0);
  val1 = SPI.transfer(0);
  digitalWrite (slaveAPin, HIGH);
  SPI.endTransaction();
  Serial.println("data");
  Serial.println(stat);
  Serial.println(val1);
  Serial.println("end");
  SPI.endTransaction();
  delay(300);
}

SPI slave code for Attiny88:

#include <SPI.h>

// set up the speed, data order and data mode
SPISettings settingsA(2000000, MSBFIRST, SPI_MODE0);
const int slavePin = 14;
const int ledPin = 9;

uint8_t stat, val1, val2, result;

void setup() {
  // set the Slave Select Pins as outputs:
  pinMode (slavePin, INPUT);
  pinMode (ledPin, OUTPUT);
  // initialize SPI:
  digitalWrite(ledPin, HIGH);
  delay(1000);
  SPI.begin();
  stat =128;
  val1= 1;
}

void loop() {

  if (slavePin==LOW) {
    SPI.beginTransaction(settingsA);
    SPI.transfer(stat);
    SPI.transfer(val1);
    result = SPI.transfer(0);
    digitalWrite(ledPin, result);
    SPI.endTransaction();
  }

}

You do not appear to be configuring the slave as an SPI slave. Merely changing the pin modes won't achieve this. Example code at SPI - Serial Peripheral Interface - for Arduino - however that does not specifically mention the Attiny88.

In my example in reply #1 on that page I have this code:

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

This sets SPCR bit MSTR to zero (by not mentioning it). If you call SPI.begin() it will be activated in master mode.

It looks like the Attiny88 has the same register.

So in my opinion your code merely has two SPI masters.

Also, you seem to be doing 3 transfers in the master, but only 2 transfers in the slave.


Stacks on arrays on arrays I am trying to find a "vanilla" way of writing several arrays into one. I spent a lot of time searching for how to do this but everything that comes up is either a tutorial that doesn't cover concatenation or someones question that ended up being an unrelated syntax problem.

I put several strands of WS2812B LEDs wired in series so the Arduino sees them as one continuous strand. I have been able to run some very cool patterns as one strand using the Pololu library but I would like to program the strands separately. The number of lights I have is very resource intensive and I like to keep things simple so I'm looking for advice on the best way to go about combining arrays without importing more libraries.

Because the patterns I have used so far write to an array and the output is an array, my first thought was that I could write one pattern to an array made up of sections 1, 4, and 5, and another pattern that would be mapped to sections 2, 3, and 6 and then concatenate it all together in order. However, adding arrays seems to be somewhat complicated without worrying about this or that persons favorite library or looping through one value at a time and I am trying to work on my C skills. Is there a simple way to concatenate arrays or a better way for me to think about this? Any best practice or organizational advice is welcome. I want to write clean code.

Bonus Round: I use several different languages at work and I cant figure out why I have it in my head that this would work...

array1 = [a, b, c]
array2 = [x, y]
array3 = array1 + array2

// array3 = [a, b, c, x, y]

Any idea if that is possible or what language I am thinking of?

C(++) does not natively let you "add" arrays like that.  Your code looks like maybe Python.

There are several ways to do what you want to do.  You could make your code which writes the pattern to the array accept an offset - so rather than always starting at position 0, you could tell it where to start.

You could write a function to "concatenate" arrays, or use one someone else has written, if you can find one.  It's pretty trivial to do.

However the method I'd use in your situation, probably just a matter of preference really, is this:

Let's say (for example) you have 6 strips of 10 LEDs each.  You need 60 elements to represent them all.  (I'm assuming each element is an int; I can't remember if it is.)  Create one big array for the whole lot:

int allElements[60];

You might think of the variable allElements as an array, but it is really an int* (a pointer to an int), with that memory address happening to have 59 other memory addresses after it reserved.  C knows that when you say allElements[7] it needs to looks 7 ints on from the address pointed to by allElements.  What this means is that you can create new variables which point to parts of that array, and use those variables as if they were their own arrays.  For example:

int *firstStrip = &(allElements[0]);
int *secondStrip = &(allElements[10]);
int *thirdStrip = &(allElements[20]);
/* ... and so on */

(There is a more idiomatic way to write this which is exactly equivalent, but I think the above is more explicit if you're new to it.)

As an extra improvement you might now notice that you have a load of similarly-named variables with similar functions -- and you might want to put them into an array.

int* strips[] = { &(allElements[0]), &(allElements[1]), &(allElements[2]) /* and so on */};

Now you can use strips[3] to give you the fourth strip.

There are several other ways too, but I think this will get you going.


Speaker not producing the right sound after a led strip was introduced Grove speaker:
http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html
ws2812-led strip

Hi, I have been working to produce tones on a speaker and it works with the following code

    int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};
    ...
    ...
    tone(pin, melody[pitch]);

After I included my addressable LED strip sketch codes, the speaker does not produce the same tone as normally it does. It sounded distorted this time round.

void loop()
{
  strip.Update(); //NeoPatterns strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800, &StripComplete);
}

Class:

// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns : public Adafruit_NeoPixel
{
  public:

// Member Variables:
    ...
    ...

void (*OnComplete)();  // Callback on completion of pattern

// Constructor - calls base-class constructor to initialize strip
NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
  : Adafruit_NeoPixel(pixels, pin, type)
{
  OnComplete = callback;
}

// Update the pattern
void Update()
{
  if ((millis() - lastUpdate) > Interval) // time to update
  {
    lastUpdate = millis();
    switch (ActivePattern)
    {
      case RAINBOW_CYCLE:
        RainbowCycleUpdate();
        break;
      default:
        break;
    }
  }
}

// Initialize for a RainbowCycle
void RainbowCycle(uint8_t interval, direction dir = FORWARD)
{
  ActivePattern = RAINBOW_CYCLE;
  Interval = interval;
  TotalSteps = 255;
  Index = 0;
  Direction = dir;
}

// Update the Rainbow Cycle Pattern
    void RainbowCycleUpdate()
    {
      for (int i = 0; i < numPixels(); i++)
      {
        setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
      }
      show(); // When I comment this line, the speaker will work properly. What is happening?
      Increment();
    }

The tone() command is interrupt driven.

To get the tight timing needed by the LED strips interrupts are disabled while sending the data.

That means the tone() command stops while you're updating the LED strips and starts again afterwards.

The end result will be the sound is corrupted - maybe sounding like it's bubbly or underwater or just "rough".

The two basically can't work together and I'm not sure what to suggest to make them work together on a low-end MCU like the AVR.


How do I power my Arduino Micro directly? I just need some confirmation, before I break something. So far I have been powering my project from USB, no I would like to power it from a battery. The official spec claims I should use a voltage anywhere from 7-12V, so I got myself a 9V block battery and would connect the positive lead to the VIN pin and the negative lead to the ground pin right next to it, based on this schematic: https://40.media.tumblr.com/cdadca4e95808b376de52a88a5468367/tumblr_mi61oww6cu1s5t695o1_1280.png
Do I need a resistor?

According to this schematic, VIN goes to the on arduino-micro's 5 and 3 volt regulators.  So you should not need a resistor.

The 5 volt regulator needs a bit more than 5 volts at it's input to do a good job.  That is why the specification calls for 7 to 12 volts.


expected primary-expression before ',' token EDIT: have solved the problem. It was missing the quotation marks around each letter. Thanks for your help, st2000!

I am very new to Arduino and C++ (coding in general!). Have copied an example code, only modifying the notes to make my own tune. But when I click 'verify', I am getting the error above, and I can't for the life of me, work out what is wrong! I've searched and read several forums and FAQs, but am just coming up blank. This is the code I have, where the error is occuring:

  int melody[]={
    a,C,D,
    a,a,C,D,D,C,
    C,C,D,D,C,
    C,D,E,F,E,D,C};

Any help would be greatly appreciated!

To answer your question we will assume your project is based on the Melody example at www.arduino.cc.

Likely you wanted to enter the ASCII values of these letters into an array of type char (type int would work as well.  But, in some cases, char would be more efficient).  To do this you need to place single quotes around each letter.  Specifically, you need to change your code:

int melody[]={ a,C,D, a,a,C,D,D,C, C,C,D,D,C, C,D,E,F,E,D,C};

...so that your line of code look like this:

int melody[]={'a','C','D','a','a','C','D','D','C','C','C','D','D','C','C','D','E','F','E','D','C'};


Void value not ignored as it ought to be im trying to build an rc plane using arduino nano and nrf24l01 as receiver but im having some issues in the code

it has error on the line
done = radio.read(joystick,sizeof(joystick)); which says that void value not ignored as it ought to be

the whole code is below

#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include<Servo.h>

Servo Throttle,Rudder,Elevator,LeftAileron,RightAileron ;

const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(9,10);
int joystick[5];

void setup()
{
  /*Serial.begin(9600);
  delay(1000);
  Serial.println("Starting Rx");*/ //Enable serial for debugging

  attachMotors();

  calibrateMotors();

  radio.begin();

  detachMotors();

  radio.setPALevel(RF24_PA_MAX);
  radio.setPayloadSize(10);
  radio.setDataRate(RF24_250KBPS);
  radio.setRetries(15,15);

  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}

void loop()
{
  detachMotors();

  if(radio.available())
  {
    bool done=false;
    while(!done)
    {
      done=radio.read(joystick,sizeof(joystick));
    }

  attachMotors();

  int a=joystick[0];
  int b= joystick[1]; //stores values from tx
  int c=joystick[2];
  int d=joystick[3];
  int e=joystick[4];

  //Serial.println(a);
  //Serial.println(b);
  //Serial.println(c);
  //Serial.println(d);
  //Serial.println(e);
 // Serial.println(f);

  delay(20);
  Throttle.writeMicroseconds(a);   //write values to motor
  Rudder.write(b);
  Elevator.write(180-c);

  if(d== LOW)
  {
  LeftAileron.write(180); ////to activate right aileron
  RightAileron.write(180);
  delay(15);
  }

  else if(e == LOW)
  {
    LeftAileron.write(0);  //to activate left aileron
    RightAileron.write(0);
    delay(15);
  }
  else
  {
    LeftAileron.write(100);
    RightAileron.write(110); //Ailerons at neutral pos
    delay(15);
  }
    }
  else
  {
    calibrateMotors();
    delay(15);

  }
  }

void attachMotors()
{
  Throttle.attach(3);
  Rudder.attach(4);
  Elevator.attach(5);
  LeftAileron.attach(6);
  RightAileron.attach(7);
}

void calibrateMotors()
{
  Rudder.write(90);
  Elevator.write(90);
  LeftAileron.write(100);
  RightAileron.write(110); //centering servo shafts
}

void detachMotors()
{
  Throttle.detach();
  Rudder.detach();
  Elevator.detach();
  LeftAileron.detach();
  RightAileron.detach();
}

Something changed while you were looking away. This is the updated description of read(). As you can see, it not longer returns a bool.
Use available to determine if packets are available:

/**
   * Read the available payload
   *
   * The size of data read is the fixed payload size, see getPayloadSize()
   *
   * @note I specifically chose 'void*' as a data type to make it easier
   * for beginners to use.  No casting needed.
   *
   * @note No longer boolean. Use available to determine if packets are
   * available. Interrupt flags are now cleared during reads instead of
   * when calling available().
   *
   * @param buf Pointer to a buffer where the data should be written
   * @param len Maximum number of bytes to read into the buffer
   *
   * @code
   * if(radio.available()){
   *   radio.read(&data,sizeof(data));
   * }
void read( void* buf, uint8_t len );